我想使用Dropwizard Backend发出定期的REST请求。更具体地说,我想每分钟向外部 REST API 发出一个 GET 请求并处理结果。
我在这里使用了石英,现在我尝试使用泽西客户端发出 REST 请求。我使用 guice 作为我的依赖注入。
我的应用程序类有以下方法
@Override
public void initialize(final Bootstrap<DockerwizardConfiguration> bootstrap) {
Job everyJob = new EveryTestJob();
bootstrap.addBundle(new JobsBundle(everyJob));
}
@Override
public void run(final DockerwizardConfiguration configuration,
final Environment environment) {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(HelloWorldParameter.class)
.annotatedWith(Names.named("helloWorldParameter"))
.toInstance(configuration.getHelloWorldParameter());
}
});
JerseyClientConfiguration conf = configuration.getJerseyClientConfiguration();
conf.setChunkedEncodingEnabled(false);
final Client client = new JerseyClientBuilder(environment).using(conf).build(getName());
environment.jersey().register(new ExternalServiceResource(client)); // How should that be implented with guice
environment.jersey().register(injector.getInstance(HelloWorldResource.class));
}
我的每个测试工作类实现如下
@Every("1s")
public class EveryTestJob extends Job {
@Override
public void doJob(JobExecutionContext context) throws JobExecutionException {
// logic run every time and time again
}
}
我不确定如何组织它。
我一直在试图弄清楚这一点,这就是我发现的:
JobBundle 将- 添加到任何资源之前,因此 JobExecutionContext 将不包含客户端 (https://www.dropwizard.io/0.9.2/docs/manual/internals.html(
- 尝试使用注射器,但也没有工作(https://github.com/HubSpot/dropwizard-guice(
最后,我偶然发现了泽西岛 2.0:创建重复作业,它展示了如何将客户端添加到上下文中!
这是我的解决方案:
在资源类中,
@Path("/myPath")
public class myResource {
@Inject
public myResource() {
try {
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.getContext().put"myResource", this); // Inserts myResource into the context
} catch (SchedulerException e) {
// Handle exception
}
}
// Other stuff for api
}
然后在作业类中(我使用的是 Dropwizard-jobs 2.0.1,其中 doJobs 不接受任何参数,所以我使用了 execute 代替(,
@Every("10s")
public class myJob extends Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
myResource res = (myResource) context.getScheduler().getContext().get("myResource");
// Do stuff with your resource
} catch (SchedulerException e) {
// Handle exception
}
}
}
不确定您是否可以访问外部服务资源,但我希望这有所帮助!