2017-10-20 7 views
1

Est-il possible d'appeler la méthode de service sur le serveur du client comme:Printemps, comment décider sur le client quel consommateur devrait servir l'utilisation?

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

la méthode alors:

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

Il est peut-être pas lié seulement au printemps. Peut-être plus généralement, comment contourner l'impossibilité de sérialiser les méthodes?

Répondre

1

Oui, vous pouvez utiliser RMI (Remote Method Invocation). L'invocation de méthode à distance Java permet d'appeler un objet résidant dans une machine virtuelle Java différente. Spring Remoting permet de tirer parti de RMI d'une manière plus facile et plus propre.

Vous devez avoir le code suivant sur le serveur

@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; 
} 

Ensuite, vous devez ajouter le code suivant à votre client:

@Bean 
public RmiProxyFactoryBean service() { 
    RmiProxyFactoryBean rmiProxyFactory = new RmiProxyFactoryBean(); 
    rmiProxyFactory.setServiceUrl("rmi://localhost:1099/MyService"); 
    rmiProxyFactory.setServiceInterface(MyService.class); 
    return rmiProxyFactory; 
} 

Après cela, vous pouvez appeler des méthodes que vous avez besoin sur l'application client :

SpringApplication.run(App.class, args).getBean(MyService.class); 
service.method("test"); 

Vous pouvez trouver plus d'informations sur https://docs.spring.io/spring/docs/2.0.x/reference/remoting.html