如何使用 ServletScopes.scopeRequest() 和 ServletScopes.continueRequest()?

2024-01-31

  1. 应该如何使用ServletScopes.scopeRequest() http://google-guice.googlecode.com/git/javadoc/com/google/inject/servlet/ServletScopes.html#scopeRequest%28java.util.concurrent.Callable%3CT%3E,%20java.util.Map%3Ccom.google.inject.Key%3C?%3E,%20java.lang.Object%3E%29?
  2. 我如何获得对@RequestScopedCallable 中的对象?
  3. 有什么意义seedMap?它是否意味着覆盖默认绑定?
  4. 这个方法和有什么区别ServletScopes.continueRequest() http://google-guice.googlecode.com/git/javadoc/com/google/inject/servlet/ServletScopes.html#continueRequest%28java.util.concurrent.Callable%3CT%3E,%20java.util.Map%3Ccom.google.inject.Key%3C?%3E,%20java.lang.Object%3E%29?

回答我自己的问题:

  1. ServletScopes.scopeRequest() http://google-guice.googlecode.com/git/javadoc/com/google/inject/servlet/ServletScopes.html#scopeRequest%28java.util.concurrent.Callable%3CT%3E,%20java.util.Map%3Ccom.google.inject.Key%3C?%3E,%20java.lang.Object%3E%29在 a 中运行 Callablenew请求范围。请注意不要跨不同范围引用对象,否则最终会遇到线程问题,例如尝试使用已被另一个请求关闭的数据库连接。static或顶级课程是您在这里的朋友。
  2. 你注入Callable在将其传递到之前ServletScopes.scopeRequest() http://google-guice.googlecode.com/git/javadoc/com/google/inject/servlet/ServletScopes.html#scopeRequest%28java.util.concurrent.Callable%3CT%3E,%20java.util.Map%3Ccom.google.inject.Key%3C?%3E,%20java.lang.Object%3E%29。因此,您必须小心您的领域Callable包含。下面详细介绍这一点。
  3. seedMap允许你注入非范围的对象进入范围。这很危险,所以要小心注射的东西。
  4. ServletScopes.continueRequest() http://google-guice.googlecode.com/git/javadoc/com/google/inject/servlet/ServletScopes.html#continueRequest%28java.util.concurrent.Callable%3CT%3E,%20java.util.Map%3Ccom.google.inject.Key%3C?%3E,%20java.lang.Object%3E%29类似,只是它在一个内部运行existing请求范围。它获取当前 HTTP 范围的快照并将其包装在 Callable 中。原始 HTTP 请求完成(您从服务器返回一些响应),但随后在单独的线程中异步完成实际操作。当稍后调用 Callable 时(在该单独的线程中),它将可以访问原始 HttpServletRequest,但不能访问 HTTP 响应或会话。

那么,最好的方法是什么?

如果您不需要将用户对象传递到Callable:注入Callable超出请求范围,并将其传递到ServletScopes.scopeRequest() http://google-guice.googlecode.com/git/javadoc/com/google/inject/servlet/ServletScopes.html#scopeRequest%28java.util.concurrent.Callable%3CT%3E,%20java.util.Map%3Ccom.google.inject.Key%3C?%3E,%20java.lang.Object%3E%29. The Callable只能参考Provider<Foo>代替Foo,否则您最终会得到在请求范围之外注入的实例。

如果您需要将用户对象传递到Callable,继续阅读。

假设您有一个将名称插入数据库的方法。我们有两种方法将名称传递给Callable.

方法一:使用子模块传递用户对象:

  1. Define InsertName, a Callable插入数据库:

    @RequestScoped
    private static class InsertName implements Callable<Boolean>
    {
      private final String name;
      private final Connection connection;
    
      @Inject
      public InsertName(@Named("name") String name, Connection connection)
      {
        this.name = name;
        this.connection = connection;
      }
    
      @Override
      public Boolean call()
      {
        try
        {
          boolean nameAlreadyExists = ...;
          if (!nameAlreadyExists)
          {
            // insert the name
            return true;
          }
          return false;
        }
        finally
        {
          connection.close();
        }
      }
    }
    
  2. 绑定子模块中的所有用户对象并使用 RequestInjector.scopeRequest() 确定可调用范围:

    requestInjector.scopeRequest(InsertName.class, new AbstractModule()
    {
      @Override
      protected void configure()
      {
        bind(String.class).annotatedWith(Names.named("name")).toInstance("John");
      }
    })
    
  3. 我们实例化一个RequestInjector在请求之外,它又注入第二个Callable inside的请求。第二Callable可以参考Foo直接(不需要提供者),因为它被注入到请求范围内。

import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.servlet.ServletScopes;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Injects a Callable into a non-HTTP request scope.
 * <p/>
 * @author Gili Tzabari
 */
public final class RequestInjector
{
    private final Map<Key<?>, Object> seedMap = Collections.emptyMap();
    private final Injector injector;

    /**
     * Creates a new RequestInjector.
     */
    @Inject
    private RequestInjector(Injector injector)
    {
        this.injector = injector;
    }

    /**
     * Scopes a Callable in a non-HTTP request scope.
     * <p/>
     * @param <V> the type of object returned by the Callable
     * @param callable the class to inject and execute in the request scope
     * @param modules additional modules to install into the request scope
     * @return a wrapper that invokes delegate in the request scope
     */
    public <V> Callable<V> scopeRequest(final Class<? extends Callable<V>> callable,
        final Module... modules)
    {
        Preconditions.checkNotNull(callable, "callable may not be null");

        return ServletScopes.scopeRequest(new Callable<V>()
        {
            @Override
            public V call() throws Exception
            {
                return injector.createChildInjector(modules).getInstance(callable).call();
            }
        }, seedMap);
    }
}

方法2:注入一个Callable在引用的请求之外Provider<Foo>. The call()然后方法可以get()请求范围内的实际值。 object对象通过a的方式传入seedMap(我个人认为这种方法违反直觉):

  1. Define InsertName, a Callable插入数据库。请注意,与方法 1 不同,我们必须使用Providers:

    @RequestScoped
    private static class InsertName implements Callable<Boolean>
    {
      private final Provider<String> name;
      private final Provider<Connection> connection;
    
      @Inject
      public InsertName(@Named("name") Provider<String> name, Provider<Connection> connection)
      {
        this.name = name;
        this.connection = connection;
      }
    
      @Override
      public Boolean call()
      {
        try
        {
          boolean nameAlreadyExists = ...;
          if (!nameAlreadyExists)
          {
            // insert the name
            return true;
          }
          return false;
        }
        finally
        {
          connection.close();
        }
      }
    }
    
  2. 为您想要传入的类型创建虚假绑定。如果不这样做,您将得到:No implementation for String annotated with @com.google.inject.name.Named(value=name) was bound. https://stackoverflow.com/a/9014552/14731 https://stackoverflow.com/a/9014552/14731解释了为什么需要这样做。

  3. 用所需的值填充 seedMap:

    ImmutableMap<Key<?>, Object> seedMap = ImmutableMap.<Key<?>, Object>of(Key.get(String.class, Names.named("name")), "john");
    
  4. Invoke ServletScopes.scopeRequest():

    ServletScopes.scopeRequest(injector.getInstance(InsertName.class), seedMap);
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ServletScopes.scopeRequest() 和 ServletScopes.continueRequest()? 的相关文章

随机推荐