上文我们利用Spring rmi实现了Spring的远程访问《Spring 实现远程访问详解——rmi》,本文主要讲解利用HttpInvoke实现远程访问。
Spring httpInvoker使用标准java序列化机制,通过Http暴露业务服务。如果你的参数和返回值是比较复杂的,通过httpInvoker有巨大的优势。
1. 远程访问流程
1) 服务端定义服务接口
2) 服务端实现服务接口
3) 暴露服务对象
4) 客户端定义暴露的服务端接口
5) 客户端配置服务参数
6) 客户端调用服务接口
2. Spring HttpInvoker具体实现
1) 服务端定义服务接口
<span style="font-family:Times New Roman;">packagecom.lm.core.service;
importjava.util.List;
importcom.lm.core.entity.User;
publicinterface UserHttpService {
List<User> getUserByAcount(Stringname,String password);
void insert(User user);
}</span>
2) 服务端实现服务接口
<span style="font-family:Times New Roman;">packagecom.lm.core.service.impl;
importjava.util.ArrayList;
importjava.util.List;
importorg.springframework.beans.factory.annotation.Autowired;
importcom.lm.core.entity.User;
importcom.lm.core.mapper.UserMapper;
importcom.lm.core.service.UserHttpService;
importcom.lm.core.service.UserRmiService;
publicclass UserHttpServiceImpl implements UserHttpService {
@Autowired
private UserMapper userMapper;
@Override
public List<User>getUserByAcount(String name, String password) {
System.err.println("httpInvoker获取用户信息:"+ name + password);
return new ArrayList<User>();
}
@Override
public void insert(User user) {
System.err.println("httpInvoker开始插入用户信息:"+ user.toString());
}
}</span>
3) 暴露服务对象
<span style="font-family:Times New Roman;"><bean name="userHttpService"class="com.lm.core.service.impl.UserHttpServiceImpl"/>
<bean name="userExporter" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="userHttpService"/>
<property name="serviceInterface" value="com.lm.core.service.UserHttpService"/>
</bean></span>
4) 客户端定义暴露的服务端接口
<span style="font-family:Times New Roman;">packagecom.lm.core.service;
importjava.util.List;
importcom.lm.core.entity.User;
publicinterface UserHttpService {
List<User> getUserByAcount(Stringname,String password);
void insert(User user);
}</span>
5) 客户端配置服务参数
<span style="font-family:Times New Roman;"><bean id="httpInvokerProxy"
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl"
value="http://127.0.0.1:8080/spring_remote_server/remoting/userExporter"/>
<property name="serviceInterface"value="com.lm.core.service.UserHttpService"/>
</bean></span>
6) 客户端调用服务接口
<span style="font-family:Times New Roman;">@RequestMapping(value = "/httpInvokerTest")
@ResponseBody
public BaseMapVo httpInvokerTest(String name, String password) {
BaseMapVo vo = new BaseMapVo();
long startDate = Calendar.getInstance().getTimeInMillis();
System.out.println("httpInvoker客户端开始调用" + startDate);
UserHttpService rmi = (UserHttpService) ApplicationContextUtil.getInstance().getBean("httpInvokerProxy");
rmi.getUserByAcount("张三", ":张三的密码");
System.out.println("httpInvoker客户端调用结束" + (Calendar.getInstance().getTimeInMillis()-startDate));
vo.setRslt("sucess");
return vo;
}</span>