Netty 4(A1) - 具有多个处理程序的AttributeMap

时间:2012-08-20 15:10:38

标签: netty

我正在尝试使用ChannelContext.attr()方法将对象从一个处理程序传递到另一个处理程序:

private class TCPInitializer extends ChannelInitializer<SocketChannel>
{
    @Override
    public void initChannel(final SocketChannel ch) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new ReadTimeoutHandler(mIdleTimeout));
        pipeline.addLast(new HostMappingHandler<SyslogHandler>(mRegisteredClients,
                                                               mChannels));
        pipeline.addLast(new DelimiterBasedFrameDecoder(MAX_FRAME_SIZE,
                         Delimiters.lineDelimiter()));
        pipeline.addLast(new Dispatcher());
    }
}

HostMappingHandler是一个将主机映射到数据的模板类:

public class HostMappingHandler<T> extends ChannelStateHandlerAdapter
{

    public static final AttributeKey<HostMappedObject> HOST_MAPPING =
        new AttributeKey<HostMappedObject>("HostMappingHandler.attr");


    private final ChannelGroup mChannels;
    private final Map<String, T> mMap;


    public HostMappingHandler(Map<String, T> registrations,
                              ChannelGroup channelGroup)
    {
        mChannels = channelGroup;
        mMap = registrations;
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception
    {
        SocketAddress addr = ctx.channel().remoteAddress();
        T mappedObj = null;

        if (addr instanceof InetSocketAddress)
        {
            String host = ((InetSocketAddress) addr).getHostName().toLowerCase();
            mappedObj = mMap.get(host);
        }

        if (mappedObj != null)
        {
            // Add the channel to the list so it can be easily removed if unregistered
            mChannels.add(ctx.channel());

            // Attach the host-mapped object
            ctx.attr(HOST_MAPPING).set(new HostMappedObject<T>(mappedObj));
        }
        else
        {
            log.debug("Bad host [" + addr + "]; aborting connection request");
            ctx.channel().close();
        }
        super.channelRegistered(ctx);
    }

    @Override
    public void inboundBufferUpdated(ChannelHandlerContext ctx) throws Exception
    {
        // Find the parser for this host. If the host is no longer registered,
        // disconnect the client.
        if (ctx.channel().remoteAddress() instanceof InetSocketAddress)
        {
            InetSocketAddress addr = (InetSocketAddress) ctx.channel().remoteAddress();
            T handler = mMap.get(addr.getHostName().toLowerCase());

            if (handler == null)
            {
                log.debug("Host no longer registered");
                ctx.channel().close();
            }
            else
            {
                log.debug("Sanity Check: " + ctx.attr(HostMappingHandler.HOST_MAPPING).get());
            }
        }
        super.inboundBufferUpdated(ctx);
    }

    // ==================================================

    public static class HostMappedObject<C>
    {
        private final C mObj;

        public HostMappedObject(final C in)
        {
            mObj = in;
        }

        public C get()
        {
            return mObj;
        }
    }
}

调度员目前非常简单:

private static class Dispatcher extends ChannelInboundMessageHandlerAdapter<Object>
{
    @Override
    public void messageReceived(final ChannelHandlerContext ctx,
                                final Object msg)
            throws Exception
    {
        HostMappingHandler.HostMappedObject wrapper =
                ctx.attr(HostMappingHandler.HOST_MAPPING).get();

        log.debug("Received: " + wrapper);
    }
}

顺便提一下,初始化程序和调度程序是“服务器”对象的私有类。但是,当我运行一个注册localhost并尝试连接到它的单元测试时,它会失败并且我的调试输出显示:

HostMappingHandler.inboundBufferUpdated: Sanity Check: test.comms.netty.HostMappingHandler$HostMappedObject@eb017e
Dispatcher.messageReceived: Received: null

因此,在HostMapper类中通道注册和接收入站消息之间肯定保留了映射,并且在调试器中进一步调查显示Dispatcher中的上下文的属性映射确实有一个条目 - 问题在于value为NULL而不是对象。

我错过了一些明显的东西,还是只是一个alpha bug?

编辑:

我现在通过将数据附加到Dispatcher的上下文来解决这个问题,方法是让HostMappingHandler也接受一个类附加。该错误似乎是在处理程序的ChannelHandlerContext中设置属性会导致该属性出现在具有正确键但具有NULL值的另一个处理程序中。如果不知道所需的工作流程,那么错误就是密钥根本不应该出现,或者值不应该为空。

public HostMappingHandler(final Map<String, T> registrations,
                          final ChannelGroup channelGroup,
                          final Class<? extends ChannelHandler> channelHandler)
{
    mChannels = channelGroup;
    mMap = registrations;
    mHandler = channelHandler;
}

//...

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception
{
    //...
    // Attach the host-mapped object
     ctx.pipeline().context(mHandler).attr(HOST_MAPPING).set(new HostMappedObject<T>(mappedObj));
    //...
}

1 个答案:

答案 0 :(得分:10)

AttributeMap中的

ChannelHandlerContext绑定到上下文,这就是您在一个上下文中设置的属性在其他上下文中不可见的原因。

请注意,Channel也会实施AttributeMap。您只需使用绑定到频道的属性映射:

ctx.channel().attr(...) ...;