spring发布RMI服务
最近交流了一个项目,需要从RMI、WebService、接口文件中采集数据到大数据平台,下面自己测试了通过Spring发布RMI服务。
说明:RMI服务要求服务端和客户端都是Java代码的,两端不能采用异构的语言开发。
服务端
1、编写服务接口和实现
package com.yaa.web.interfaces.rmi.springRMI; public interface HelloRMIService { public int getAdd(int a, int b); }
package com.yaa.web.interfaces.rmi.springRMI; public class HelloRMIServiceImpl implements HelloRMIService { @Override public int getAdd(int a, int b) { return a+b; }
2、RMI通过spring发布:
服务端采用java注册方式将RMI服务接口交由spring容器管理。在MVCconfig的配置如下:
//发布一个RMI服务 @Bean public HelloRMIServiceImpl helloRMIServiceImpl() throws IOException{ HelloRMIServiceImpl hello = new HelloRMIServiceImpl(); return hello; } @Bean public RmiServiceExporter rmiServiceExporter() throws IOException{ RmiServiceExporter rmi = new RmiServiceExporter(); rmi.setService(helloRMIServiceImpl());//实现类 rmi.setServiceName("helloRMI");//服务名 rmi.setServiceInterface(HelloRMIService.class);//接口类 rmi.setRegistryPort(8889);//发布的端口,这里默认使用本机的localhost 或 127.0.0.1. return rmi; }
完成后即运行服务端Web服务。
MVCconfig是spring容器的初始化类(替换了spring-servlet.xml,零配置xml),实现如下:
@Configuration @EnableWebMvc //启动spring MVC容器,相当于 xml中的 <mvc:annotation-driven/> @ComponentScan(basePackages = "com.yaa") @ImportResource(locations={"classpath:META-INF/cxf/cxf.xml","classpath:META-INF/cxf/cxf-servlet.xml"}) public class MVCConfig extends WebMvcConfigurerAdapter{ @Autowired RoleToUserProfileConverter roleToUserProfileConverter; @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(roleToUserProfileConverter); } @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } /* * 处理静态资源 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/static/"); } @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } //发布一个RMI服务 @Bean public HelloRMIServiceImpl helloRMIServiceImpl() throws IOException{ HelloRMIServiceImpl hello = new HelloRMIServiceImpl(); return hello; } @Bean public RmiServiceExporter rmiServiceExporter() throws IOException{ RmiServiceExporter rmi = new RmiServiceExporter(); rmi.setService(helloRMIServiceImpl()); rmi.setServiceName("helloRMI"); rmi.setServiceInterface(HelloRMIService.class); rmi.setRegistryPort(8889); return rmi; } }