Search code examples
javaspringspring-boottcpspring-integration

Spring Integration - Restrict Number of Connections on Server Connection Factory


We have a Spring boot application which acts as a TCP server for clients. We want to restrict the number of connections clients can open on this server and port. The current configuration allows them to open un-limited number of connections. See configuration below. Any configuration at a connection factory / gateway level that can help us achieve this ? We also want these connections to be indefinitely open as the client will implement pooling on the available connections

@Bean
    public AbstractServerConnectionFactory serverConnectionFactory() {
        CustomStxHeaderLengthSerializer serializer = new CustomStxHeaderLengthSerializer();
        
        TcpNioServerConnectionFactory serverConnectionFactory = new TcpNioServerConnectionFactory(6666);
    
        
        serverConnectionFactory.setHost("localhost");
        serverConnectionFactory.setDeserializer(serializer);
        serverConnectionFactory.setSerializer(serializer);
        
        serverConnectionFactory.setSingleUse(false);
        serverConnectionFactory.setBacklog(5000);
    
        
        return serverConnectionFactory;
        
    }

Solution

  • There are a couple of options.

    1. Add a custom TcpSocketSupport to the connection factory. In postProcessSocket(Socket socket) you could keep track of how many sockets have been opened and immediately close one that exceeds the limit. You would also need some hooks to reduce the open count when a socket is closed, this can be done by adding an event listener for TcpConnectionCloseEvents.

    2. Use an event listener to receive both TcpConnectionOpenEvents and TcpConnectionCloseEvents to keep track of the number of open connections. You can close() the connection immediately when the limit is exceeded (cast event.getSource() to a TcpConnection.

    https://docs.spring.io/spring-integration/docs/current/reference/html/ip.html#tcp-events