有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当从Quartz调度器调用函数时,如何将HttpRequest/Response作为参数传递给函数?

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

早些时候,我有一个rest控制器,其端点为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()));
    }

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

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

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

我不知道如何做到这一点,我花了我的大部分时间浏览解决方案之前张贴


共 (1) 个答案

  1. # 1 楼答案

    您可以使用RestTemplate通过以下方式对某个控制器端点进行请求调用:

    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();
         }