java - 当从 Quartz 调度程序调用函数时,如何将 Http 请求/响应作为参数传递给函数?

标签 java rest spring-boot quartz-scheduler

我正在运行 spring-boot 应用程序,我已经实现了quartz调度程序作为应用程序的一部分。

之前我有一个休息 Controller ,其端点例如 http://localhost:8080/GoogleMail/ {id} 触发如下所示的函数,并接受 HttpServletRequest/Response 作为参数以及我传递的 Pathvariable。

@PostMapping(value = "/GoogleMail/{id}", consumes = "application/json", produces = "application/json")
    public String sendMail(HttpServletRequest request, HttpServletResponse response, @Valid @PathVariable(value = "id") String id,
            @Valid @RequestBody MailMessage mailMsg) throws Exception {
        if(id == null || id.isEmpty()) {
            ResponseEntity.badRequest().build();
        }
        this.userId = id;

        return GoogleMailIntegrationService.sendUserMails(request, response, id, mailMsg,
                m -> !StringUtils.isBlank(mailMsg.getTo())
                && !StringUtils.isBlank(mailMsg.getSubject())
                && !StringUtils.isBlank(mailMsg.getBody()));
    }

现在,我需要使用 Quartz 调度程序每 1 小时发布一次 JSON 正文来调用此函数,而不是进行 REST 调用。可能如下图

if (context.getJobDetail().getKey().getName().equalsIgnoreCase(JobName.READRESPONSE.toString())) {
           // emailService.readMail();
            try {
              sendMail(Request, Response, id);
            } catch (IOException e) {
                e.printStackTrace();
            }

我的问题:有没有办法使用 Scheduler 进行 REST 调用,或者是否可以通过直接传递请求/响应参数来进行 sendMail() 调用。

我不确定如何执行此操作,我花了大部分时间在发布之前浏览解决方案。

最佳答案

您可以使用RestTemplate通过以下方式对某些 Controller 端点进行请求调用:

if (context.getJobDetail().getKey().getName().equalsIgnoreCase(JobName.READRESPONSE.toString())) {
     // emailService.readMail();
     try {
         RestTemplate restTemplate = new RestTemplate();
         HttpEntity<MailMessage > request = new HttpEntity<>(mailMsg, new HttpHeaders());

         ResponseEntity<String> responseEntityStr = 
             restTemplate.postForEntity(
             String.format("http://localhost:7777/GoogleMail/%s", id), 
             request, String.class);

     } catch (IOException e) {
            e.printStackTrace();
     }

关于java - 当从 Quartz 调度程序调用函数时,如何将 Http 请求/响应作为参数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381589/

相关文章:

java - JRootPane.getName() 返回 Null?

java - 使用 Jersey 在正文请求中 POST JSON

java - 如何仅在某个配置文件处于 Activity 状态时验证配置属性?

java - 如何在 JPA 中填充 @Transient 字段?

java - 编译后的java程序没有输出

java - 微服务: Without Service Discovery With Spring API Gateway

c# - 将 WCF 服务转换为 RESTful 应用程序?

ajax - emberjs - RESTful 资源处理

java - 如何指定正确的返回类型?

java - 我可以将接口(interface)传递给 Fragment 包吗?