一尘不染

如何在Spring Boot中从Java设置TCPConnectionFactory或SSLServerSocketFactory

spring-boot

我是Spring Boot的新手,但我的工作要求我使用Spring Boot实施小型Web服务。

Web服务需要 接受SSL TCP连接 (外部系统将使用自定义协议-NOT
HTTP连接到我的Web服务)。另外,我想在一个后台任务(或多个后台任务)中处理这些连接。

在查看了官方文档(http://docs.spring.io/spring-
integration/reference/html/ip.html)之后,我还是不明白(我将所有XML放在哪里)。当我在SO上询问该XML的放置位置时,我被回答说这是一种非常古老的配置方法,不再应使用。

这样做的“最新”方式是什么?


阅读 625

收藏
2020-05-30

共1个答案

一尘不染

@SpringBootApplication
public class So43983296Application implements CommandLineRunner {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(So43983296Application.class, args);
        Thread.sleep(10_000);
        context.close();
    }

    @Autowired
    private DefaultTcpNetSSLSocketFactorySupport ssl;

    @Override
    public void run(String... args) throws Exception {
        Socket socket = ssl.getSocketFactory().createSocket("localhost", 1234);
        socket.getOutputStream().write("foo\r\n".getBytes());
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String result = br.readLine();
        System.out.println(result);
        br.close();
        socket.close();
    }

    @Bean
    public TcpNetServerConnectionFactory scf() {
        TcpNetServerConnectionFactory scf = new TcpNetServerConnectionFactory(1234);
        DefaultTcpNetSSLSocketFactorySupport tcpSocketFactorySupport = tcpSocketFactorySupport();
        scf.setTcpSocketFactorySupport(tcpSocketFactorySupport);
        // Add custom serializer/deserializer here; default is ByteArrayCrLfSerializer
        return scf;
    }

    @Bean
    public DefaultTcpNetSSLSocketFactorySupport tcpSocketFactorySupport() {
        TcpSSLContextSupport sslContextSupport = new DefaultTcpSSLContextSupport("classpath:test.ks",
                "classpath:test.truststore.ks", "secret", "secret");
        DefaultTcpNetSSLSocketFactorySupport tcpSocketFactorySupport =
                new DefaultTcpNetSSLSocketFactorySupport(sslContextSupport);
        return tcpSocketFactorySupport;
    }

    @Bean
    public TcpInboundGateway inGate() {
        TcpInboundGateway inGate = new TcpInboundGateway();
        inGate.setConnectionFactory(scf());
        inGate.setRequestChannelName("upperCase");
        return inGate;
    }

    @ServiceActivator(inputChannel = "upperCase")
    public String upCase(byte[] in) {
        return new String(in).toUpperCase();
    }

}

如果您更喜欢Spring Integration的XML配置,请将其添加到spring配置xml文件中并@ImportResource("my- context.xml")在类上使用。

2020-05-30