Stephane Grenier
Stephane Grenier

Reputation: 15925

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?

Upvotes: 6

Views: 5996

Answers (3)

Vincent Cantin
Vincent Cantin

Reputation: 17302

I pass information from one handler to the next ones by using dedicated instances to compose the pipeline for each channel, and by having the handlers reference each others within each pipeline.

The passing of information is made the old way, very simply, without any problem.

Upvotes: 0

Ryan Shelley
Ryan Shelley

Reputation: 187

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...

Upvotes: 2

Norman Maurer
Norman Maurer

Reputation: 23567

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.

Upvotes: 2

Related Questions