1

我正在尝试了解如何最好地添加 Jest to Play 之类的内容。

在 Play 的 2.5.x 依赖注入文档中,他们展示了如何添加单例,然后可以在需要时通过构造函数注入进行注入。

虽然这对我编写的类非常有意义,但我并不真正了解如何注入像 Jest 这样的东西,它是通过工厂实例化的:

 JestClientFactory factory = new JestClientFactory();
 factory.setHttpClientConfig(new HttpClientConfig
                        .Builder("http://localhost:9200")
                        .multiThreaded(true)
            //Per default this implementation will create no more than 2 concurrent connections per given route
            .defaultMaxTotalConnectionPerRoute(<YOUR_DESIRED_LEVEL_OF_CONCURRENCY_PER_ROUTE>)
            // and no more 20 connections in total
            .maxTotalConnection(<YOUR_DESIRED_LEVEL_OF_CONCURRENCY_TOTAL>)
                        .build());
 JestClient client = factory.getObject();

在我的控制器中,我应该如何正确注入 Jest?我是否创建一个 jest 工厂包装器,然后在构造函数调用中getObject()?这似乎根本不是一个理想的解决方案。

JestFactoryWrapper.java

@Singleton
class JestFactoryWrapper {

    private JestFactory jestFactory;

    JestFactoryWrapper() {
        this.jestFactory = ...
    }

    public JestFactory getObject() {
        return this.jestFactory.getObject()
    }
}

ApiController.java

@Inject
ApiController(JestFactoryWrapper jestFactory) {
    this.jestClient = factory.getObject();
}
4

1 回答 1

1

从文档:

JestClient设计为单例,不要为每个请求都构造它!

https://github.com/searchbox-io/Jest/tree/master/jest

所以注入工厂并不是一个好的选择。

我想最好JestClient由工厂创建一个并将类绑定到实例:

例子

模块:

public class Module extends AbstractModule {

  @Override
  protected void configure() {
    ...
    bind(JestClient.class).toInstance(jestFactory.getObject());
    ...
  }
}

用法:

@Inject
ApiController(JestClient jestClient) {
    this.jestClient = jestClient;
}

提供者绑定

创建一个提供者单例。

@Singleton
public class JestClientProvider implements Provider<JestClient> {

    private final JestClient client;

    @Inject
    public JestClientProvider(final Configuration configuration, final ApplicationLifecycle lifecycle) {
        // Read the configuration.
        // Do things on the start of the application.

        ...

        client = jestFactory.getObject();

        lifecycle.addStopHook(() -> {
            // Do things on the stop of the application.
            // Close the connections and so on. 
        })
    }

    @Override
    public JestClient get() {
        return client;
    }
}

在模块中绑定它:

bind(JestClient.class).toProvider(JestClientProvider.class).asEagerSingleton();

用它:

@Inject
ApiController(JestClient jestClient) {
    this.jestClient = jestClient;
}
于 2017-05-03T08:28:22.650 回答