RMI,为远程方法调用,我们要用spring来实现调用:
步骤1:
编写远程接口和远程接口的实现类
接口:
package com.rmi;
public interface ISomeService {
public String doSomeService(String some);
public int doOtherService(int other);
}
实现类:
package com.rmi;
public class SomeService implements ISomeService {
public int doOtherService(int other) {
// TODO Auto-generated method stub
return ++other;
}
public String doSomeService(String some) {
// TODO Auto-generated method stub
return some+" is proceeed";
}
}
服务端的配置文件:
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="someService" class="com.rmi.SomeService"></bean>
<bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="service" ref="someService"></property>
<property name="serviceName" value="SomeService"></property>
<property name="serviceInterface" value="com.rmi.ISomeService"></property>
</bean>
</beans>
服务端启动代码:
public class RMIServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("rmi.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
if(br.readLine().equals("exit"))
{
break;
}
}
RmiServiceExporter rse = (RmiServiceExporter)ctx.getBean("serviceExporter");
rse.destroy();
}
}
步骤2:
编写客户端
客户端配置文件:
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="someServiceProxy" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://127.0.0.1/SomeService"/>
<property name="serviceInterface" value="com.rmi.ISomeService"/>
</bean>
</beans>
客户端调用服务端的代码:
package com.rmi;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class RmiClient {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("rmi-client.xml");
ISomeService service = (ISomeService) ctx.getBean("someServiceProxy");
System.out.println(service.doSomeService("some request"));
}
}
注意:客户端必须要有服务端ISomeService.class的文件,这样客户端才可以有关于该服务端接口的引用,这个是和一般的webservice的调用方法是一样的
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/682008,如需转载请自行联系原作者