2011-12-04 46 views
2

有没有办法保持频道的状态。我正在写一个聊天服务器,我想保留一个频道所属用户的信息。我在想,Channel可能会提供一种方法来存储用户对象,但我看不到一个。有没有办法做到这一点,而不需要像地图一样?在Netty频道上保持状态

回答

6

1)您可以在channelHandlerContext中设置状态信息,如下所示,稍后使用。

channelHandlerContext.setAttachment(yourObj); 

    Object yourObj2 = channelHandlerContext.getAttachment(); 

2)创建的信道的本地和存储状态信息存在(通道本地就像一个线程本地到特定的信道)

import org.jboss.netty.channel.ChannelLocal; 

import java.util.Map; 

public class UserInfoHolder { 
    public final static ChannelLocal<Map<String, String>> USER_INFO = new  ChannelLocal<Map<String, String>>(); 
} 


//if you have the channel reference, you can store and retrieve information like this 
Map<String,String> userMap = .... 

//store 
UserInfoHolder.USER_INFO.set(channel, userMap); 

//retrive 
Map<String,String> userMap2 = UserInfoHolder.USER_INFO.get(channel); 
+0

在Netty的4.0 ChannelHandlerContext不具有setAttachment()方法。所以我猜这些信息只是过时了? – Michael

+1

@Michael'setAttachment()'不再使用,'attr()'是你正在寻找的方法。请参阅http://netty.io/4.0/api/io/netty/util/AttributeMap.html –