向微服务发送异步消息

时间:2021-06-13 22:46:14

标签: spring spring-boot spring-cloud spring-cloud-feign feign

我有一个 BE 服务 A,它使用 Feign 客户端向微服务 B 发送 Rest JSON 消息:

import pandas as pd
d=pd.read_csv('data.csv',usecols=['time','velocity','dis'])

端点:

@FeignClient(name = "mail-service")
@LoadBalancerClient(name = "mail-service", configuration = LoadBalancerConfiguration.class)
public interface EmailClient {

    @RequestMapping(method = RequestMethod.POST, value = "/engine/emails/register")
    void setUserRegistration(CreateUserDTO createUserDTO);
}

Rest Endpoint 正在向 AWS Ses 邮件或其他邮件提供商发送邮件。

问题是来自 Feign 的第一个呼叫可能需要 5 秒或更长时间。我需要将其设为异步,以便 FE 客户端不等待发送邮件。

如何使从 Feign Async 发出的 Rest 调用没有等待 http 响应 OK 的等待时间?有没有更好的解决方案来实现这一点?

1 个答案:

答案 0 :(得分:1)

AFAIK,Feign 不允许非阻塞 IO,它是一个 work in progress

但是您可以实现您的 EmailRestService 异步。考虑以下代码(我不知道 processCreateUserMessage 是否也负责发送电子邮件,但建议的解决方案在必要时应该可以扩展到该功能):

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

//...

@Service
public class EmailRestServiceImpl implements EmailRestService {
  //...
  
  @Async
  public void processCreateUserMessage(CreateUserDTO createUserDTO) {
    // Implementation of service to send mail to AWS SES
    // ...
  }

}

请注意 @Async 注释定义。

要启用 Spring 异步处理,您需要在主配置或特定配置中定义 @EnableAsync 注释:

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync
public class AsyncConfiguration {

}

无需更改您的 Controller,但如果您愿意,可以返回更方便的 HTTP 状态代码:

@RestController
@RequestMapping("/emails")
public class EmailController {

    @RequestMapping(method = RequestMethod.POST, value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> register(@Valid @RequestBody CreateUserDTO createUserDTO) {
        // Will be executed asynchronously and return immediately
        emailRestService.processCreateUserMessage(createUserDTO);
        return new ResponseEntity<>(HttpStatus.ACCEPTED);
    }
}