简介:
1、RMI 实现Java程序间的交互;
2、RMI 很难穿越防火墙,因为RMI使用任意端口来交互----这是防火墙通常所不允许的;
3、客户端和服务端都是 java 开发的,并且传输的对象类型必须要保证在调用两端的Java运行时中是完全相同的版本。
一、服务端代码
1、编写普通的接口和接口实现类:
public interface RMIService {
List<Map<String,Object>> queryAllUser();
}
@Service
public class RMIServiceImpl implements RMIService{
@Autowired
private UserDao userDao;
@Override
public List<Map<String, Object>> queryAllUser() {
return userDao.getUsers();
}
}
2、服务端配置:
@Bean
public RmiServiceExporter rmiServiceExporter(RMIService rmiService) {
RmiServiceExporter rmiServiceExporter = new RmiServiceExporter();
//表明RmiServiceExporter会把该bean rmiService 发布为一个RMI服务
rmiServiceExporter.setService(rmiService);
rmiServiceExporter.setServiceName("RMIService"); //该服务的命名
rmiServiceExporter.setServiceInterface(RMIService.class); //该服务所实现的接口
//设置主机和端口号
//rmiServiceExporter.setRegistryHost("");
//rmiServiceExporter.setRegistryPort(0);
return rmiServiceExporter;
}
二、客户端代码:
1、编写和服务端相同的接口:
public interface RMIService {
List<Map<String,Object>> queryAllUser();
}
2、客户端配置:
@Bean
public RmiProxyFactoryBean rmiService() {
RmiProxyFactoryBean rmiProxyFactoryBean = new RmiProxyFactoryBean();
rmiProxyFactoryBean.setServiceUrl("rmi://localhost/RMIService");
rmiProxyFactoryBean.setServiceInterface(RMIService.class);
return rmiProxyFactoryBean;
}
3、客户端调用:
@Autowired
private RMIService rmiService;
@RequestMapping("testRmi")
public String testRmi() {
List<Map<String,Object>> maps = rmiService.queryAllUser();
String result = maps.get(0).get("id").toString();
return result;
}