转换为多个客户端服务器连接

时间:2016-09-03 06:57:11

标签: spring spring-integration

使我之前的问题更具可读性,以下是我的代码,适用于单服务器单客户端连接,但我希望我的客户端动态连接2个或更多服务器,

     public class ClientCall {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext ctx = new AnnotationConfigApplicationContext(GatewayConfig.class);
        GatewayService gatewayService = ctx.getBean(GatewayService.class);
        //int i=0;
        Message message = new Message();        
        /*while(i<4)
        {*/
            message.setPayload("It's working");
            gatewayService.sendMessage(message);
        /*  i++;            
        }*/

    }
}

public class Message {

    private String payload;
  // getter setter
}

@EnableIntegration
@IntegrationComponentScan
@Configuration
@ComponentScan(basePackages = "com.gateway.service")
public class GatewayConfig {

    // @Value("${listen.port:6788}")
    private int port = 6785;

    @Autowired
    private GatewayService<Message> gatewayService;

    @MessagingGateway(defaultRequestChannel = "sendMessageChannel")
    public interface Gateway {
        void viaTcp(String payload);
    }

    @Bean
    public AbstractClientConnectionFactory clientCF() {
        TcpNetClientConnectionFactory clientConnectionFactory = new TcpNetClientConnectionFactory("localhost",
                this.port);
        clientConnectionFactory.setSingleUse(false);
        return clientConnectionFactory;
    }

    @Bean
    @ServiceActivator(inputChannel = "sendMessageChannel")
    public MessageHandler tcpOutGateway(AbstractClientConnectionFactory connectionFactory) {
        TcpOutboundGateway outGateway = new TcpOutboundGateway();
        outGateway.setConnectionFactory(connectionFactory);
        // outGateway.setAsync(true);
        outGateway.setOutputChannel(receiveMessageChannel());
        outGateway.setRequiresReply(true);
        outGateway.setReplyChannel(receiveMessageChannel());
        return outGateway;
    }

    @Bean
    public MessageChannel sendMessageChannel() {
        DirectChannel channel = new DirectChannel();
        return channel;
    }


    @Bean
    public MessageChannel receiveMessageChannel() {
        DirectChannel channel = new DirectChannel();
        return channel;
    }

    @Transformer(inputChannel = "receiveMessageChannel", outputChannel = "processMessageChannel")
    public String convert(byte[] bytes) {
        return new String(bytes);
    }

    @ServiceActivator(inputChannel = "processMessageChannel")
    public void upCase(String response) {
        gatewayService.receiveMessage(response);
    }

    @Transformer(inputChannel = "errorChannel", outputChannel = "processMessageChannel")
    public void convertError(byte[] bytes) {
        String str = new String(bytes);
        System.out.println("Error: " + str);
    }

}


public interface GatewayService<T> {

    public void sendMessage(final T payload);

    public void receiveMessage(String response);

}


@Service
public class GatewayServiceImpl implements GatewayService<Message> {

    @Autowired
    private Gateway gateway;

    @Autowired
    private GatewayContextManger<String, Object> gatewayContextManger;

    @Override
    public void sendMessage(final Message message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                gateway.viaTcp(message.getPayload());
            }
        }).start();
    }

    @Override
    public void receiveMessage(final String response) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                Message message = new Message();
                message.setPayload(response);
                Object obj = gatewayContextManger.get(message.getPayload());
                synchronized (obj) {
                    obj.notify();
                }
            }
        }).start();
    }

}

以下是服务器代码,类似于另一个服务器具有不同的端口和IP,然后如何连接到这些服务器?

class TCPServer
{
   public static void main(String argv[]) throws Exception
      {
         String clientSentence;
         String capitalizedSentence;
         ServerSocket welcomeSocket = new ServerSocket(6785);

         while(true)
         {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient =
               new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println("Received: " + clientSentence);
            capitalizedSentence = clientSentence + "\r\n";
            outToClient.writeBytes(capitalizedSentence);
         }
      }
}

1 个答案:

答案 0 :(得分:0)

一些评论。

  1. 使用sendMessageChannel只需将ExecutorChannel设为ThreadPoolTaskExecutor,而不是启动线程来发送消息 - 它会更高效,让您无法管理线程
  2. 如果您只有2台服务器要连接,而不是提出动态方案,只需定义2个TCP适配器并在@Router之后添加sendMessageChannel
  3. 您可以通过设置标题告诉路由器将服务器发送给哪个服务器。

    @MessagingGateway(defaultRequestChannel =“sendMessageChannel”) 公共接口网关{     void viaTcp(String payload @Header(“which”)String target); }

  4. 使用HeaderValueRouter在标题which上进行路由。

    请参阅参考手册中的Message Routing