2017-10-20 23 views
1

是否有可能调用服务器上的服务方法,从客户端,如:春天,如何决定客户端应该服务哪个用户?

someServiceHolder.getService(MyService.class).runMethodOnServerWithConsumer("myConsumerService#consumerA") 

当时的方法:

public void runMethodOnServerWithConsumer(String consumerMethodName) { 
Consumer<Object> consumerA = somehowGetConsumerInstance(consumerMethodName); 
    consumerA.accept(doSomething()); 
} 

它也许不是仅仅涉及到春天。也许更一般地说,如何解决序列化方法的不可能性?

回答

1

是的,您可以使用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找到更多的细节

相关问题