Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netty - How to pass information between handlers in the same pipeline

I would like to create a pipeline of handlers such as:

public ChannelPipeline getPipeline() throws Exception 
{
    return Channels.pipeline(
            new ObjectEncoder(),
            new ObjectDecoder(),
            new AuthenticationServerHandler(),
            new BusinessLogicServerHandler());
}

The key here is that I'd like the AuthenticationServerHandler to be able to pass the login information to the BusinessLogicServerHandler.

I do understand that you can use an Attachment, however that only stores the information for that handler, the other handlers in the pipeline cannot access it. I also noticed there was something called ChannelLocal which might do the trick, however I cannot find any real information on how to use it. All I've seen is people create a static instance to it, but how do you retrieve and access the info in another handler? Assuming that's the correct method.

My question is: how you do pass information between handlers in the same pipeline. In the example above, how do I pass the login credentials from the AuthenticationServerHandler to the BusinessLogicServerHandler?

like image 680
Stephane Grenier Avatar asked Jan 23 '12 18:01

Stephane Grenier


2 Answers

ChannelLocal is the way to go atm. Just create an static instance somewhere and then access it from within your handlers by pass the Channel to the set/get method. This way you can share stuff between your channels.

like image 132
Norman Maurer Avatar answered Nov 01 '22 17:11

Norman Maurer


I wasn't a fan of the ChannelLocal implementation with the lack of an internal static map, so what I ended up doing was putting my object on the Channel's attachment for now:

ctx.getChannel().setAttachment(myobj);

Then I make "myobj" basically a context POJO that contains all the information gathered about the request so far.

public class RequestContext {
    private String foo = "";

    public String getFoo(){
        return foo;
    }
    public void setFoo(String foo){
        this.foo = foo;
    }

}

RequestContext reqCtx = new RequestContext();
reqCtx.setFoo("Bar");

ctx.getChannel().setAttachment(reqCtx);
reqCtx = (RequestContext)ctx.getChannel().getAttachment(); 

It's not elegant, but it works...

like image 38
Ryan Shelley Avatar answered Nov 01 '22 19:11

Ryan Shelley