是否有可能从客户端调用服务器上的服务方法,例如:
someServiceHolder.getService(MyService.class).runMethodOnServerWithConsumer("myConsumerService#consumerA")
然后该方法:
public void runMethodOnServerWithConsumer(String consumerMethodName) {
Consumer<Object> consumerA = somehowGetConsumerInstance(consumerMethodName);
consumerA.accept(doSomething());
}
可能与Spring无关。也许更一般地说,如何解决序列化方法的不可能?
最佳答案
是的,您可以使用RMI(远程方法调用)。
Java远程方法调用允许调用驻留在其他Java虚拟机中的对象。 Spring Remoting允许以更简单,更简洁的方式利用RMI。
您需要在服务器上有以下代码
@Bean
public RmiServiceExporter exporter(MyService implementation) {
Class<MyService> serviceInterface = MyService.class;
RmiServiceExporter exporter = new RmiServiceExporter();
exporter.setServiceInterface(serviceInterface);
exporter.setService(implementation);
exporter.setServiceName(serviceInterface.getSimpleName());
exporter.setRegistryPort(1099);
return exporter;
}
然后,应将以下代码添加到客户端:
@Bean
public RmiProxyFactoryBean service() {
RmiProxyFactoryBean rmiProxyFactory = new RmiProxyFactoryBean();
rmiProxyFactory.setServiceUrl("rmi://localhost:1099/MyService");
rmiProxyFactory.setServiceInterface(MyService.class);
return rmiProxyFactory;
}
之后,您可以在客户端应用程序上调用所需的方法:
SpringApplication.run(App.class, args).getBean(MyService.class);
service.method("test");
您可以在https://docs.spring.io/spring/docs/2.0.x/reference/remoting.html上找到更多详细信息