簡體   English   中英

沒有servlet的Guice請求作用域注入(在RPC服務器中)

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

對於背景,我正在Thrift服務中處理RPC請求(盡管我的問題不是特定於Thrift的)。 我想要的東西看起來應該很簡單,但是我找不到任何示例:如何在不從頭開始的情況下重用com.google.inject.servlet.RequestScoped綁定?

顯然,我可以按照說明創建自定義范圍。 但這似乎過於復雜。 我想做的是:處理傳入的(節儉的)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();
  }

Guice為此提供了一個實用程序類: ServletScopes

如果您使用的是Java 7+:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM