Spring RMI 超时(Timeout) 和 自动重连

其实Spring RMI 提供自动重连,这样的话,如果服务端的程序重启,就不会影响到客户端.
而且大家应该知道,Spring 在容器启动的时候,就实例化所有BEAN,所以提醒大家,如果不一定用到,或者可以等下加载的,可以设置为延时加载的。
对于Spring RMI的实现我就不多说了,如果不知道的请看:
http://feng-henry.iteye.com/blog/1090339
下面是具体实现。
/**
 * 自定一个SCOKECT连接,可配置超时时间
 * @author Henry
 */
public class RMICustomClientSocketFactory implements RMIClientSocketFactory {
    
    
    private int timeout;
    
    /**
     * 设置超时时间
     * @param timeout
     */
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public Socket createSocket(String host, int port) throws IOException {
        Socket socket = new Socket(host, port);
        socket.setSoTimeout(timeout);
        return socket;
    }

}

Spring配置文件如下:
<bean id="rmiClientSocketFactory" class="com.rmi.RMICustomClientSocketFactory">
		<property name="timeout" value="5000"></property>
	</bean>
<bean id="rmiService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">  
        <property name="serviceUrl" value="rmi://127.0.0.1:10999/Demo"></property>  
        <property name="serviceInterface" value="com.demo.IDemoRMIServer"></property>  
		<!-- setting refresh connect -->
		<property name="refreshStubOnConnectFailure" value="true"></property>
		<property name="lookupStubOnStartup" value="false"></property>
		<property name="registryClientSocketFactory" ref="rmiClientSocketFactory"></property>
	</bean>


lookupStubOnStartup : 这个属性是表示,不在容器启动的时候创建与Server端的连接;
refreshStubOnConnectFailure : 这个属性是表示是否连接出错时自动重连;
registryClientSocketFactory : 这个是客户端与服务端创建SOCKECT的一个工厂。
它只需要是实现RMIClientSocketFactory 接口的类就行。
RMIClientSocketFactory 的 原码如下:
public interface RMIClientSocketFactory {

    /**
     * Create a client socket connected to the specified host and port.
     * @param  host   the host name
     * @param  port   the port number
     * @return a socket connected to the specified host and port.
     * @exception IOException if an I/O error occurs during socket creation
     * @since 1.2
     */
    public Socket createSocket(String host, int port)
	throws IOException;
}

当然以上这些属性都在RmiProxyFactoryBean的超类 RmiClientInterceptor 里。这个源码太长,大家如果想深入了解,可以阅读此类源码。

猜你喜欢

转载自feng-henry.iteye.com/blog/1106299
今日推荐