【Java 远程服务】Spring发布RMI服务
转载:https://www.cnblogs.com/yangchongxing/p/9084066.html
RmiServiceExporter可以把任意Spring管理的Bean发布为RMI服务。
1、Service端口实现,我自己是在Spring MVC种集成这
package cn.ycx.web.service; public interface DateRemote { public String now(); } package cn.ycx.web.service; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.stereotype.Service; @Service public class DateRemoteImpl implements DateRemote { @Override public String now() { SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss"); return format.format(new Date()); } }
配置@Bean
@Bean public RmiServiceExporter rmiExporter(DateRemote dateRemote) { RmiServiceExporter rmiExporter = new RmiServiceExporter(); rmiExporter.setService(dateRemote); rmiExporter.setServiceName("DateRemoteService"); rmiExporter.setServiceInterface(DateRemote.class); rmiExporter.setRegistryPort(1199);//不设置默认为端口1099 return rmiExporter; }
2、客户端
服务接口
package cn.ycx.service; public interface DateRemote { public String now(); }
package cn.ycx.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.rmi.RmiProxyFactoryBean; import cn.ycx.service.DateRemote; @Configuration public class TestConfig { @Bean public RmiProxyFactoryBean dateRemote() { RmiProxyFactoryBean rmiProxy = new RmiProxyFactoryBean(); rmiProxy.setServiceUrl("rmi://localhost:1199/DateRemoteService");// localhost也可更换为本机IP rmiProxy.setServiceInterface(DateRemote.class); return rmiProxy; } }
package cn.ycx.test; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.ycx.config.TestConfig; import cn.ycx.service.DateRemote; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=TestConfig.class) public class Test { @Autowired DateRemote dateRemote; @Before public void setUp() throws Exception { } @org.junit.Test public void test() { System.out.println(dateRemote.now()); assertNotNull(dateRemote); } }
发布服务是指定Host待续...