I have a Web Socket Server Endpoint deployed in tomcat as follows:
@ServerEndpoint(value="/alerts/{username}/{sessionId}/{token}",
decoders = AlertDTODecoder.class,
encoders = AlertDTOEncoder.class )
public class AlertWebSocketEndpoint {
@OnOpen
public void onOpen(Session session,
@PathParam("username") String username,
@PathParam("sessionId") String sessionId,
@PathParam("token") String token) throws IOException {
String origToken = TokenCacheServiceImpl.getInstance().getToken(username, sessionId);
if ( origToken == null || !origToken.equals(token)) {
session.close();
}else {
AlertSession.getInstance().addUserSession(username, session);
}
}
@OnClose
public void onClose(Session session, @PathParam("username") String username) throws Exception {
AlertSession.getInstance().removeUserSession(username, session);
session.close();
}
}
AlertSession is a singleton class where I maintain a cache of the sessions.
TokenCacheServiceImpl uses to cache Token corresponding to each user in REDIS.
I can't store Session in REDIS since it is a Non-Serializable object and hence have to maintain it in local memory. I am looking to avoid this since I don't want to lose data if server is restarted or if I want to do load balancing.
How can this be acheived?
You won't be able to store arbitrary, non-serializable
objects without a ton of work.
But if you know what kind of objects you are already storing, then you can certainly write your own serializer. There's nothing that says the data must be binary. You can use XML, JSON, or some made-up storage system.
Can you restrict your application so that is only stored certain types of objects? If you, for example, only store primitives (well, their boxed flavors) and collections or those things, you could do this with very little code. If not, be prepared to write more code.
It might be easier to change the code of your session objects to be Serializable
and then just use Java serialization to get the job done.
Note that the future of Java serialization is uncertain. A very old JEP was filed to remove serialization, but it was withdrawn. More recent security concerns have prompted some to support the removal of serialization from future Java versions. That second article specifically mentions that "[r]emoving serialization is a long-term goal and is part of Project Amber", but I don't see anything in Project Amber that deals with Serialization at all.
Also, certain existing Java specifications (parts of Java EE, including the Servlet spec) pretty much require the support for Serialization, so... even if it's deprecated, I don't see it going anywhere anytime soon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With