gpt4 book ai didi

java - 正确地将 Jest 添加到 Java Play 2.5.x

转载 作者:行者123 更新时间:2023-11-30 06:45:28 26 4
gpt4 key购买 nike

我正在尝试了解如何最好地添加像 Jest 这样的东西来玩。

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

虽然这对于我编写的类来说非常有意义,但我真的不明白如何注入(inject)像 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();

在我的 Controller 中,我应该如何正确注入(inject) 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();
}

最佳答案

来自文档:

JestClient is designed to be singleton, don't construct it for each request!

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

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

我认为最好通过工厂创建一个 JestClient 并将类绑定(bind)到实例:

示例

模块:

public class Module extends AbstractModule {

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

用法:

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

<强> Provider Bindings

创建一个提供者单例。

@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):

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

使用它:

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

关于java - 正确地将 Jest 添加到 Java Play 2.5.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com