Design question / getting reference to another handler - best practice

Trustin Lee (이희승) trustin at gmail.com
Mon Oct 26 05:23:11 EDT 2009


On Mon, Oct 26, 2009 at 2:56 AM, Robert Wahlstedt <rob at isketch.net> wrote:
>
> On Oct 25, 2009, at 18:30 , Peter Thomas wrote:
>
>> I have a client pipeline for e.g. (towards server): A --> B (assume
>> they handle both upstream / downstream)
>>
>> B encodes / decodes using a "chunk size" that can be changed by a
>> server message.
>>
>> But the business logic of unpacking a "chunk size change" message is
>> responsibility of A.
>>
>> I guess I have the following options of getting a reference to B and
>> calling a setter.
>>
>> - initialize the pipeline so that A has a reference to B
>> - invent a new "internal" message and send it from A to B  (but
>> extra message clutter, downcast / if-then)
>> - call methods on ChannelPipeline to get a reference to B
>> - use a ChannelLocal or attachment (but seems to be handler specific)
>>
>> Any advice on which of the above would be recommended / discouraged,
>> would be greatly appreciated, maybe there are more ways I have missed.
>
> I had a similar issue where I needed different handlers to have access
> to a "User" object.
>
> I solved it by subclassing DefaultChannelPipeline and putting the User
> variable there. That way all of my handlers can access it by
> ChannelHandlerContext.getPipeline()
>
> Not sure if this is the optimal way to deal with it, but it has been
> working for me. I'm interested in other suggestions as well.

It's a great idea that I have never thought about so far.  I love it.

Alternatively, you can also set up such a variable using ChannelLocal
utility class:

    ChannelLocal<User> user = new ChannelLocal<User>() {
        protected User initialValue(Channel ch) {
            return new User(...);
        }
    };
    ...
    User u = user.get(channel);

HTH,
Trustin

— Trustin Lee, http://gleamynode.net/



More information about the netty-users mailing list