java - 如何在 Dropwizard 中使用 Quartz 调度程序进行 REST 调用?
问题描述
我想使用 Dropwizard 后端发出定期 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));
}
我的 EveryTestJob 类实现如下
@Every("1s")
public class EveryTestJob extends Job {
@Override
public void doJob(JobExecutionContext context) throws JobExecutionException {
// logic run every time and time again
}
}
我不确定如何组织它。
解决方案
我一直在尝试解决这个问题,这就是我发现的:
- JobBundle 在任何 Resources 之前添加,因此 JobExecutionContext 将不包括客户端(https://www.dropwizard.io/0.9.2/docs/manual/internals.html)
- 尝试使用注射器但也没有工作(https://github.com/HubSpot/dropwizard-guice)
最后我偶然发现了Jersey 2.0: Create repeating job,它展示了如何将客户端添加到上下文中!
这是我的解决方案:
在资源类中,
@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
}
}
}
不确定您是否可以访问 ExternalServiceResource,但我希望这会有所帮助!
推荐阅读
- jquery - Jquery过滤选择框div
- c++ - 如何修改 Dijkstra 算法以适应 C++ 中的 A* 搜索算法
- apache-spark - /work/app-xxxxxxx/{0, 1, 2, ...} 中的 spark worker 目录的用途和定期清理
- c++ - 明确定义方法后出现“标识符未定义”错误
- date - 如何在 Instant 中删除日期并仅保留日期?
- python - 如果尚未创建“作者”,我如何发布新项目?
- javascript - javascript 是否保证对象的顺序是确定性的?
- c++ - 如何使用 get() 读取文本文件?
- c# - 我需要在 Visual Studio Code 中创建一个新的 c# 文件
- python - PyCharm 无法访问 /usr/lib/ 和 /usr/bin/ 中的文件