3

作为背景,我正在 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();
  }
4

1 回答 1

4

Guice 提供了一个实用程序类来做到这一点:ServletScopes

如果您使用的是 Java 7+:

void ProcessInput(Input myInput) {
    RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
    try ( RequestScoper.CloseableScope ignored = scope.open() ) {
        doWork();
    }
}
于 2017-03-30T05:55:38.343 回答