没有servlet的Guice请求范围注入(在RPC服务器中)

时间:2017-03-26 04:35:31

标签: java guice thrift requestscope

对于后台,我正在Thrift服务中处理RPC请求(尽管我的问题不是特定于Thrift)。我想要的似乎应该很简单,但我找不到任何例子:如何重用com.google.inject.servlet.RequestScoped绑定而无需从头开始?

显然,我可以按照创建自定义范围的说明进行操作。但这似乎过于复杂。我想做的事情:处理传入(Thrift)RPC时,为每个传入呼叫创建一个新的RequestContext;然后,在处理它时使用标准的RequestScoped注入。

基本上,我的代码看起来应该像(松散地)这样:

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();
  }

1 个答案:

答案 0 :(得分:3)

Guice提供了一个实用程序类来执行此操作:ServletScopes

如果您使用的是Java 7 +:

void ProcessInput(Input myInput) {
    RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
    try ( RequestScoper.CloseableScope ignored = scope.open() ) {
        doWork();
    }
}