Spring RMIリモートサービス

3814 ワード

Spring RMIリモートサービス
 
      SpringにRMIサービスを設定する
 
      サービスでは、RmiServiceExportは、任意のSpringが管理するBeanをRMIサービスとしてリリースすることができます.
 
      クライアントでは、SpringのRmiProxyFactoryBeanは、RMIサービスのためのエージェントを作成することができます.RmiProxyFactoryBenは、クライアントとリモートRMIサービスとの通信を担当するプロキシオブジェクトを生成する.
 
      サービス端末はRMIサービスを発表します.
 
package com.x.rmi;

public interface HelloService {
	
	public String sayHello(String name);
	
}
 
package com.x.rmi;

public class HelloServiceImpl implements HelloService {

	public String sayHello(String name) {
		System.out.println("Hello " + name);
		return "Hello " + name;
	}

}
 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
		<property name="service"          ref="helloService"></property>
		<property name="serviceName"      value="HelloService"></property>
		<property name="serviceInterface" value="com.x.rmi.HelloService"></property>
	</bean>
	
	<bean id="helloService" class="com.x.rmi.HelloServiceImpl" />
	
</beans>
 
      ここではハローService Benをservice属性に組み入れて、RmiServiceExportがこのBeanをRMIサービスとしてリリースすることを示しています.
      serviceName属性はRMIサービスと命名されました.
      serviceInterface属性は、このサービスが実現するインターフェースを指定しています.
 
package com.x.rmi;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RmiServer {  
  
    public static void main(String[] args) throws InterruptedException {  
        new ClassPathXmlApplicationContext("com/x/rmi/remote-server.xml");
        
    }  
}
 
      クライアント呼び出しRMIサービス
 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<bean id="helloService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
		<property name="serviceUrl"       value="rmi://localhost/HelloService"></property>
		<property name="serviceInterface" value="com.x.rmi.HelloService"></property>
	</bean>
	
</beans>
 
package com.x.rmi;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RmiClient {  
    public static void main(String[] args) {  
        ApplicationContext ctx = new ClassPathXmlApplicationContext("com/x/rmi/remote-client.xml");  
        HelloService helloService = (HelloService) ctx.getBean("helloService");  
        String ret = helloService.sayHello("Rod Johnson");  
        System.out.println(ret);
    }  
  
}