如何使用spring-integration设置套接字客户端?

时间:2017-05-16 10:30:44

标签: java spring sockets spring-integration

我正在使用基于spring 4注释的配置,并希望设置一个简单的telnet / socket客户端。

这是我到目前为止所做的:

@MessageEndpoint
public class MySocket {
    @Bean
    public TcpConnectionFactoryFactoryBean clientFactory() {
        TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean();
        fact.setType("client");
        fact.setHost(host);
        fact.setPort(port);
        fact.setUsingNio(true);
        fact.setSingleUse(true);
        fact.setSoTimeout(timeout);
        return fact;
    }

    @Bean
    public MessageChannel clientChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = "clientChannel")
    public TcpOutboundGateway outGateway(TcpNioClientConnectionFactory factory, 
            @Qualifier("clientChannel") MessageChannel clientChannel) throws Exception {
        TcpOutboundGateway gate = new TcpOutboundGateway();
        gate.setConnectionFactory(factory);
        gate.setReplyChannel(clientChannel);
        return gate;
    }
}

@Component
public class MyMessageService {
  @Autowired
  @Qualifier("clientChannel")
  private MessageChannel clientChannel;

  public void run() {
    Message<String> msg = MessageBuilder.withPayload("test").build();
    Message<?> rsp = new MessagingTemplate(clientChannel).sendAndReceive(msg);
  }
}

结果:org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers

我在这里错过了通过套接字发送消息并收到回复的信息吗?

1 个答案:

答案 0 :(得分:1)

您不需要@MessageEndpoint注释,但您需要频道上的消费者...

@ServiceActivator(inputChannel = "clientChannel")
@Bean
public TcpOutboundGateway outGateway(AbstractClientConnectionFactory scf) {
    ...
}

网关需要对连接工厂的引用。由于您使用的是工厂bean,因此最简单的方法是将其作为参数添加到bean的工厂方法中。