不说废话了,直接上代码。
服务端:
pom.xml中加入spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
远程方法声明接口,IHelloWorld.java
package com.poreader.rmi;
public interface IHelloWorld {
public String say(String name);
}
接口实现:HelloWorld.java
package com.poreader.rmi.impl;
import com.poreader.rmi.IHelloWorld;
public class HelloWorld implements IHelloWorld {
public String say(String name) {
return name + ":" + "HelloWorld";
}
}
Spring配置文件context.xml
<?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.xsd">
<bean id="helloWorld" class="com.poreader.rmi.impl.HelloWorld"></bean>
<bean id="serviceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="service" ref="helloWorld"></property>
<property name="serviceName" value="hello"></property>
<property name="registryPort" value="8088"></property>
<property name="serviceInterface" value="com.poreader.rmi.IHelloWorld"></property>
</bean>
</beans>
宿主运行Main
package com.poreader.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
System.out.println("Service Running!!");
}
}
客户端代码:
和服务端相同的远程接口声明
package com.poreader.rmi;
public interface IHelloWorld {
public String say(String name);
}
Spring配置文件context.xml
<?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.xsd">
<bean id="helloWorld" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://127.0.0.1:8088/hello" />
<property name="serviceInterface" value="com.poreader.rmi.IHelloWorld" />
</bean>
</beans>
调用Main
package com.poreader.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.poreader.rmi.IHelloWorld;
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"context.xml");
IHelloWorld hs = (IHelloWorld) ctx.getBean("helloWorld");
System.out.println(hs.say("suyang"));
}
}