首页 > 解决方案 > 如何在 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
  }
}

我不确定如何组织它。

标签: javajerseyquartz-schedulerguicedropwizard

解决方案


我一直在尝试解决这个问题,这就是我发现的:

最后我偶然发现了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,但我希望这会有所帮助!


推荐阅读