簡體   English   中英

java-如何使用JAX-RS每兩分鍾發送一次Http POST請求?

[英]java - How to send Http POST request at every two minutes using JAX-RS?

我正在開發服務器端Web服務代碼。 我正在使用JAX-RS作為開發框架。

到目前為止,我已經創建了模型類和資源類,以將請求的數據響應給客戶端。

樣本資源方法...

@GET
@Path("/{userId}")
@Produces(MediaType.APPLICATION_JSON)
public User getUserDetails(@PathParam("userId") long id) {
    ..
    // some code here //
    ..
}

基本上,服務器響應數據或執行某些操作取決於客戶端調用的URI。

我想在服務器啟動后每兩分鍾向第三方服務器發出Http POST請求。 但是我不知道應該在哪里編寫該代碼(如我所說,方法的執行取決於被調用的URI)。

因此,我應該在哪里編寫在服務器啟動時開始執行並在服務器停止時結束的代碼。

如何每兩分鍾發送一次Http請求?

您應該能夠結合使用Quartz和ServletContextListener來做到這一點。

您將需要創建一個作業,觸發器和調度程序以使您的代碼每兩分鍾運行一次,並且需要一個實現ServletContextListener接口的偵聽器類。

您的代碼如下所示:

職位類別:

 package com.example;

    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;

    public class ExampleJob implements Job
    {
        public void execute(JobExecutionContext context) throws JobExecutionException {
                // Code to make POST call here
    }

ServletContextListener

package com.example;

public class ExampleListener implements javax.servlet.ServletContextListener {

   public void contextInitialized(ServletContext context) {
      JobDetail job = JobBuilder.newJob(ExampleJob.class)
            .withIdentity("exampleJob", "group").build();
      // Trigger
      Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("exampleTrigger", "group")
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(120).repeatForever())
            .build();
      // Scheduler
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);

   }
}

並將其添加到web.xml中:

<listener>
    <listener-class>com.example.ExampleListener</listener-class>
</listener>

或者,如果您使用的是Servlet容器3.x,則可以通過使用@WebListener注釋偵聽器類來跳過web.xml修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM