Netty学习笔记15 Netty Attribute使用

Attribute 用来在channel上记录数据。

操作

写示例

AttributeKey<byte[]> srcdataAttrKey = AttributeKey.valueOf("srcdata");
byte[] mydata=new byte[msg.readableBytes()];
Attribute<byte[]> srcdataAttr = ctx.channel().attr(CloudConstants.srcdataAttrKey);
srcdataAttr.set(mydata);

读示例

AttributeKey<String> nameAttrKey = AttributeKey.valueOf("nameattr");

Attribute<String> attr = ctx.channel().attr(nameAttrKey);
String name= attr.get();

通过attr查找channel

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelMatcher;
import io.netty.util.Attribute;

public class MatcherByName  implements ChannelMatcher{
    private String name;

    public MatcherByName(String name){
        this.name = name;
    }
    /**
     * 查找某个channel,找自己所在channel,不是找peer
     * 
     * */
    @Override
    public boolean matches(Channel ch) {

        Attribute nameAttr= ch.attr(ChannelConstants.ChannelAttribute);
        String name = nameAttr.get();
        if(name==null)return false;

        if(this.name.equals(name))
            return true;
        else
            return false;

    }

}
    /**
     * 通过matcher找channel list
     * @param matcher
     * @return
     */
    public static List getChannelsFromMatcher(ChannelMatcher matcher){
        Object[] channels =NettyService.allChannels.toArray();
        List list = new ArrayList();
        Channel channel = null;
        for(Object ch : channels) {
            if(matcher.matches((Channel)ch)) {
                channel = (Channel)ch;
                list.add(channel);
            }
        }
        return list;
    }

    public static Channel getChannelByName(String name){
         MatcherByName matcher=new MatcherByName(name);
         List list= getChannelsFromMatcher(matcher);
        if(list!=null && list.size()>0)
            return list.get(0);
        else
            return null;
    }

你可能感兴趣的:(#,Java-Netty专栏)