Как динамически создать несколько TcpOutboundGateways с помощью Spring Integration? - PullRequest
2 голосов
/ 14 июня 2019

У меня есть сценарий, когда мне нужно одно клиентское приложение, чтобы иметь возможность динамически создавать TCP-соединения с переменным числом уникальных комбинаций хост / порт при запуске приложения.Я пытаюсь сделать это с помощью Spring Integration TcpOutboundGateway, но не смог найти решение.Я хочу, чтобы каждая комбинация хост / порт имела свой собственный выделенный TcpOutboundGateway.Мои исследования TcpOutboundGateway до этого момента привели меня к следующему, единому шлюзу, решению…

@MessageGateway(defaultRequestChannel=“sendMessage”)
public interface myMessageGateway {
    byte[] sendMessage(String message);
}

@Bean
@ServiceActivator(inputChannel=“sendMessage”)
public MessageHandler tcpOutboundGateway(AbstractClientConnectionFactory factory) {
    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(factory);
    return gateway;
}

@Bean
public AbstractClientConnectionFactory clientConnectionFactory() {
    return new TcpNetClientConnectionFactory(“123.456.789.0”, 5555);
}

Где я понимаю, что вызов функции sendMessage поместит сообщение запроса в канал «sendMessage»,Затем этот канал передаст его активатору службы tcpOutboundGateway, который будет обрабатывать отправку сообщения и в конечном итоге будет возвращать ответ сервера как возвращение функции sendMessage.Это решение отлично сработало для меня в сценариях единственного предварительно определенного подключения к серверу.

Мой вопрос заключается в том, как я могу динамически создавать новые шлюзы сообщений и активаторы служб таким образом, чтобы поддерживать переменный набор уникальных хостов /порты?Более конкретно, что аннотации @MessageGateway и @ServiceActivator делают для нас в фоновом режиме и что мне нужно сделать, чтобы реплицировать эту функциональность?

РЕДАКТИРОВАТЬ:

Итак, после некоторых экспериментов я нашел это решение, которое, похоже, решает проблему ...

// Define the Message Gateway without any annotations
public interface MyMessageGateway {
    byte[] sendMessage(String message);
}

...

// Use the GatewayProxyFactoryBean to replicate the functionality of the @MessageGateway annotation
// context is my instance of a ConfigurableApplicationContext
GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean(SenderGateway.class);
gpfb.setDefaultRequestChannel(“sendMessage”);
context.getBeanFactory().registerSingleton(“MyMessageGateway”, gpfb);
context.getBeanFactory().initializeBean(gpfb, “MyMessageGateway”);

// Create and register the ClientConnectionFactory Bean within the Application Context
AbstractClientConnectionFactory clientConnectionFactory = new TcpNetClientConnectionFactory(“123.456.789.0”, 5000);
context.getBeanFactory().registerSingleton(“ClientConnectionFactory”, clientConnectionFactory);
context.getBeanFactory().initializeBean(clientConnectionFactory, “ClientConnectionFactory”);

// Create and register the TcpOutboundGateway Bean within the Application Context
TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(clientConnectionFactory);
context.getBeanFactory().registerSingleton(“TcpOutboundGateway”, tcpOutboundGateway);
context.getBeanFactory().initializeBean(tcpOutboundGateway, “TcpOutboundGateway”);

// Create and register the Request Channel to connect the Message Gateway and the TCP Outbound Gateway
// This should replicate the functionality of the @ServiceActivator annotation
DirectChannel sendMessage = new DirectChannel();
sendMessage.setBeanName(“sendMessage”);
context.getBeanFactory().registerSingleton(“sendMessage”, sendMessage);
context.getBeanFactory().initializeBean(sendMessage, “sendMessage”);

// Subscribe the TCP Outbound Gateway to the new Message Channel (sendMessage)
// This should replicate the functionality of the @ServiceActivator annotation
sendMessage.subscribe(tcpOutboundGateway);

// Start the ClientConnectionFactory
// This seems to be getting done automatically in the non-dynamic implementation above
clientConnectionFactory.start();

Эта реализация позволяет отправлять сообщения через шлюз сообщений и исходящий шлюз TCP так же, каканнотированная реализация выше (с использованием функции sendMessage, определенной для интерфейса MyMessageGateway).Я обнаружил, что для того, чтобы использовать этот подход для более чем одной комбинации хост / порт, вам необходимо получить нужный шлюз сообщений через context.getBeanFactory.getBean ().

Мне любопытно, есть лиНедостатки в этом подходе / реализации?

1 Ответ

1 голос
/ 14 июня 2019

Единственный простой способ сделать это - рассмотреть возможность использования динамических IntegrationFlow s с Java DSL, предоставляемых Spring Integration: https://docs.spring.io/spring-integration/docs/current/reference/html/#java-dsl-runtime-flows

У нас также есть исчерпывающий пример точно для аналогичных динамический TCP-клиент сценарий использования: https://github.com/spring-projects/spring-integration-samples/tree/master/advanced/dynamic-tcp-client

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...