[英]Persisting data in TCP server while client channel is connected
我正在使用Netty构建TCP服务器。 在通道存在的情况下,是否有任何方法可以持久保存连接的客户端的会话数据?
例如,当客户端连接到服务器时,我需要创建其类实例,并在他发送消息时以不同的方式重用。 类似于以下代码:
// 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();
}
}
浏览解决方案时,我发现了一些示例,其中开发人员使用缓存服务(例如memcache或redis)来存储和检索与连接的客户端有关的数据。
但我希望在不依赖外部流程的情况下解决此问题。 有什么办法可以做到这一点? 关于这个问题的任何建议,将不胜感激。
谢谢
您应该使用AttributeMap.attr(AttributeKey key) ,该属性由ChannelHandlerContext
继承:
存储状态信息
AttributeMap.attr(AttributeKey)
允许您存储和访问与处理程序及其上下文相关的有状态信息。 请参考ChannelHandler来学习各种推荐的管理状态信息的方法。 [1]
[1] [ http://netty.io/4.0/api/io/netty/channel/ChannelHandlerContext.html]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.