Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice Request-scoped injection without a servlet (in an RPC server)

For background, I'm processing RPC requests in a Thrift service (though my question isn't Thrift-specific). What I want seems like it should be simple, but I can find no examples: how do I reuse com.google.inject.servlet.RequestScoped bindings without starting from scratch?

Clearly I could follow the instructions for creating a custom Scope. But that seems overly complicated. What I want to do: when processing an incoming (Thrift) RPC, create a new RequestContext for each incoming call; then, use standard RequestScoped injection while processing it.

Basically, it seems my code should look (loosely) like this:

void main() {
// Configure appropriate bindings, create injector
Injector injector = Guice.createInjector(new ServerHandlerModule()); 

ThriftServer server = new ThriftServer.ThriftServerBuilder("MyService", port).withThreadCount(threads).build();`  
server.start(new MyService.Processor(new MyHandler()));

// For each incoming request, Thrift will call the appropriate method on the (singleton) instance of MyHandler.  
// Let's say MyHandler exposes a method void ProcessInput()
}

class MyHandler {

@Override
void ProcessInput(Input myInput) {  // myInput was constructed by Thrift
  // I want the following instance of RequestContext to be injected
  // (provided by Guice) as (say) a constructor arg to any constructor 
  // needing one when that construction happens in this thread.
  RequestContext rc = new RequestContext(myInput); 
  doWork();
  }
like image 956
Paul N Avatar asked Oct 24 '25 18:10

Paul N


1 Answers

Guice provides a utility class for doing just that: ServletScopes.

If you are using Java 7+:

void ProcessInput(Input myInput) {
    RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
    try ( RequestScoper.CloseableScope ignored = scope.open() ) {
        doWork();
    }
}
like image 176
sargue Avatar answered Oct 26 '25 08:10

sargue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!