2017-10-20 21 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找到更多的細節

相關問題