[英]Persisting data in TCP server while client channel is connected
I'm building a TCP Server using Netty. 我正在使用Netty构建TCP服务器。 Is there any way to persist the connected client's session data while its channel exists?
在通道存在的情况下,是否有任何方法可以持久保存连接的客户端的会话数据?
for example, when a client connect to the server, I need to create its class instance and reuse in different ways when he send messages. 例如,当客户端连接到服务器时,我需要创建其类实例,并在他发送消息时以不同的方式重用。 something like the code below:
类似于以下代码:
// this is called when the client connect to the server
public void channelActive(final ChannelHandlerContext ctx) {
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
new GenericFutureListener<Future<Channel>>() {
public void operationComplete(Future<Channel> future) throws Exception {
// I need to create the class instance when the
// client connects to the server
ClientData clientData = new ClientData(ctx.channel());
channels.add(ctx.channel());
}
}
);
}
// this is called when the server receives a message from the connected client
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
if("update".equals(msg)){
// then I need the retrieve the data created
// in the ChannelActive method.
clientData().update();
}
}
While browsing for solutions, I found a few examples where the developer used a cache service (like memcache or redis) to store and retrieve the data related to the connected client. 浏览解决方案时,我发现了一些示例,其中开发人员使用缓存服务(例如memcache或redis)来存储和检索与连接的客户端有关的数据。
But I wish to solve this without depending on a external process. 但我希望在不依赖外部流程的情况下解决此问题。 Is there any way to achieve this?
有什么办法可以做到这一点? Any advice on the subject would be appreciated.
关于这个问题的任何建议,将不胜感激。
Thank you 谢谢
You should use AttributeMap.attr(AttributeKey key) , which is inherited by ChannelHandlerContext
: 您应该使用AttributeMap.attr(AttributeKey key) ,该属性由
ChannelHandlerContext
继承:
Storing stateful information
存储状态信息
AttributeMap.attr(AttributeKey)
allow you to store and access stateful information that is related with a handler and its context.AttributeMap.attr(AttributeKey)
允许您存储和访问与处理程序及其上下文相关的有状态信息。 Please refer to ChannelHandler to learn various recommended ways to manage stateful information.请参考ChannelHandler来学习各种推荐的管理状态信息的方法。 [1]
[1]
[1][ http://netty.io/4.0/api/io/netty/channel/ChannelHandlerContext.html] [1] [ http://netty.io/4.0/api/io/netty/channel/ChannelHandlerContext.html]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.