K
K
kernelconf2017-01-28 14:14:08
Java
kernelconf, 2017-01-28 14:14:08

Websocket Endpoint via annotation - where to place initialization code?

I am writing a simple application, its essence is as follows: on the server side, the PostgreSQL message queue listens (Listen), if the client is subscribed to receive payload from this message, he needs to send it.
I planned to do it like this:
1. The client connects, sends updates to json, what he needs to receive.
2. The server in onOpen adds the session to the list.
3. The server in onMessage associates the client's subscription with its parameters in json
4. Upon arrival of the asynchronous application from the base, the list is iterated and if the message matches the config, it is sent to the client.

@ServerEndpoint(value = "/test", decoders = {ClientConfigurationDecoder.class})
public class SmartSocketsEndpoint {
  private final Logger logger = LoggerFactory.getLogger(SmartSocketsEndpoint.class);
  private static final ConcurrentHashMap<Session, ClientConfiguration> clients = new ConcurrentHashMap<>();

  @OnOpen
  public void onOpen(Session session) {
    clients.putIfAbsent(session, new ClientConfiguration());
  }

  @OnClose
  public void onClose(Session session, CloseReason reason) {
    logger.info("Session #{} closed. Reason #{}", session.getId(), reason.getReasonPhrase());
    clients.remove(session);
  }

  @OnMessage
  public void onMessage(ClientConfiguration configuration, Session session) {
    logger.info("Got configuration #{}", configuration.toString());
    clients.put(session, configuration);
  }
  public static void dispatchMessage(String payload) {
// код для итерации сессий и отправки сообщения
  }
}

In general, code taken from any textbook. It is enough to pack it in a war and deploy it anywhere (in my case - glassfish).
What is not written in the textbooks - where to declare the code related to working with the database, ie. connection pool initialization (I use HikariCP), listener setup, etc. This code must be run at application startup. Or is there no such thing as an application start in this case, and you need to place the initialization in the form of a singleton in onOpen() ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question