2017-03-26 12 views
2

백그라운드에서 Thrift 서비스의 RPC 요청을 처리하고 있습니다. (제 질문은 저조 적이 아니지만). 내가 원하는 것은 간단해야하지만 아무런 예도 찾을 수 없다. 처음부터 시작하지 않고 com.google.inject.servlet.RequestScoped 바인딩을 재사용하려면 어떻게해야 할까?(RPC 서버의) 서블릿이없는 Guice 요청 범위 주입

분명히 사용자 지정 범위를 만드는 지침을 따를 수 있습니다. 그러나 그것은 지나치게 복잡하게 보인다. 내가 원했던 일 : 들어오는 (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(); 
    } 

답변

2

Guice는 그 일을위한 유틸리티 클래스를 제공합니다 : ServletScopes은.

당신은 7 + 자바를 사용하는 경우 :

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