简体   繁体   中英

Keep Spring Boot application alive with websocket connection

My Spring Boot application is quite small and has one job: Act as a client by opening a websocket connection to a third-party website and listen for messages.

The problem is that after my javax.websocket.Endpoint implementation has been initialised and the connection has been created, my Spring boot application closes.

I would have thought that any open websocket connection would keep my application up and running?

I don't need an embedded servlet container so I have specifically set web-environment: false in application.yaml.

Is there a way to remedy this without adding a servlet container I will never use?

I fixed this by using OkHttpClient and initialising it with a @PostConstruct in my @Configuration . I annotated the listener with @Component and it now stays alive without needing the embedded servlet container.

@PostConstruct
void handleRequest() {
    Runnable runnable = () -> {
        while (true) {
            try {
                JSONObject requestBody = getRequestBodyFromInput(serverSocket.accept());
                requestHandler.handleRequest(requestBody);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    };
    new Thread(runnable).start();
}

I started a new thread on while socket would keep listening and I am not letting that new thread die by looping it over within while loop.

您只是可以永远循环下去。

while (true) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM