服务端服务接口:
package com.llg.service;
public interface HelloService {
public String hello();
}
服务端服务接口实现类:
package com.llg.service.impl;
import com.llg.service.HelloService;
public class HelloServiceImpl implements HelloService {
@Override
public String hello() {
return "我是服务端的信息";
}
}
使用org.springframework.remoting.rmi.RmiServiceExporter将HelloService发布为远程服务:
<?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 name="helloService" class="com.llg.service.impl.HelloServiceImpl"></bean>
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="service" ref="helloService"/>
<property name="serviceName" value="HelloService"/>
<property name="serviceInterface" value="com.llg.service.HelloService"/>
<property name="registryPort" value="1100"/>
</bean>
</beans>
service属性表示需要发布为远程服务的bean。
serviceName属性表示服务名称,在客户端使用这个名称来引用服务。
serviceInterface属性表示服务实现的接口。‘
registryPort属性表示传输数据的端口
客户端要想远程调用服务必须定义相同的接口,在这里是HelloService,但不需要实现:
客户端HelloService接口:
package com.llg.service;
public interface HelloService {
public String hello();
}
客户端使用RmiProxyFactoryBean来将远程服务注入到spring容器中:
<?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 class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://localhost:1100/HelloService"></property>
<property name="serviceInterface" value="com.llg.service.HelloService"></property>
</bean>
</beans>
serviceUrl属性是远程服务的url,在这里是本机的1100端口的HelloService服务。
serviceInterface属性是指明服务实现的接口。
接下来测试一下:
开启服务端:
package com.llg.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestServerHelloService {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("applicationContext.xml");
}
}
在客户端调用:
package com.llg.test;
import com.llg.service.HelloService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestClientHelloService {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloService helloService = context.getBean(HelloService.class);
System.out.println(helloService.hello());
}
}
控制台输出:
注意:如果远程服务中使用了实体类,则客户端要定义相同的实体类并且都要实现序列化接口