天天看點

Spring RMI遠端調用服務

用戶端和伺服器端必須是純Java實作。RMI服務是典型的面向接口程式設計,隻有在遠端接口裡定義的方法才會作為遠端服務,遠端方法的傳回值和參數都必須實作Serializable接口,因為遠端在網絡上傳輸隻能傳輸位元組流,是以,要求參數、傳回值都可以轉換成位元組流-即實作序列化。

如果要暴露遠端方法,Spring提供了RmiServiceExporter類,該類可以将一個普通Bean執行個體綁定成遠端服務。将普通bean執行個體綁定為遠端服務的完整配置如下(伺服器端配置server.xml):

<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
		<!-- 該屬性表示提供服務的類 -->
		<property name="service">
			<ref bean="userService"/>
		</property>
		<!-- 該屬性表示服務名 -->
		<property name="serviceName">
			<value>userService</value>
		</property>
		<!-- 該屬性表示服務接口名 -->
		<property name="serviceInterface">
			<value>com.sdj.core.service.IUserService</value>
		</property>
		<!-- 該屬性表示服務端口 -->
		<property name="registryPort">
		   <value>9999</value>
		</property>
	</bean>
           

 用戶端配置如下client.xml:

<bean id="userServiceClient" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
		<property name="serviceUrl">
			<!-- url=rmi://{host}:端口/服務名 -->
			<value>rmi://localhost:9999/userService</value>
		</property>
		<property name="serviceInterface">
			<value>com.sdj.core.service.IUserService</value>
		</property>
	</bean>
           

 首先啟動伺服器端,代碼如下:

public class RMIServer {
	public static void main(String args[]){
		ApplicationContext context=new ClassPathXmlApplicationContext("classpath:server.xml");
		System.out.println("server start...");
	}
}
           

伺服器端啟動後,即注冊了服務userService,此時用戶端便可以遠端調用userService,用戶端代碼如下:

public class RMIClient 
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {

        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:client.xml");
        System.out.println(context);
        IUserServiceservice = (IUserService)context.getBean("userServiceClient");
        System.out.println(service.getUserByID(1)); 

    }

}