【问题标题】:when user posts email, I want to send mail only if more than 1 minute passed before same users send email request. how can I do that?当用户发布电子邮件时,我只想在同一用户发送电子邮件请求之前超过 1 分钟才发送邮件。我怎样才能做到这一点?
【发布时间】:2021-11-25 16:40:24
【问题描述】:
@RequestMapping( value = "/resendMail", method = RequestMethod.POST)
public ApiException sendMail(@Valid @RequestBody EmailRequest emailRequest) {
    ApiException response = null;
    User user = userRepository.findByEmail(emailRequest.getEmail());
    if( user!=null) {
        // If 1 minute passed do this.
        userService.sendVerificationEmail(user, user.getEmail());
        response = new ApiException("Link sent to this email,", null, HttpStatus.OK);
    }
}

这是我的服务。如果用户在 60 秒内没有发送请求,我想这样做:

SimpleMailMessage simpleMailMessage =new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content+"http://localhost:8080/confirm-email?id="+ user.getId());
try {
    mailSender.send(simpleMailMessage);
} catch (MailException mailException) {

}

【问题讨论】:

  • 您是否需要在同一个请求中执行此操作,异步或添加特定队列以供其他应用读取?您可以使用代理模式,并在简单的static var new ConcurrentHashMap<LocalDateTime,ObjectToResendEmail>(); 中管理您的逻辑,或者您可以使用 Spring Boot 中的 @Async 注释来并行化您的流程,或者使用事件驱动的队列、bacth、其他应用程序( sugeested in a large scalabitity )

标签: java spring spring-boot time spring-data-jpa


【解决方案1】:

您可以简单地将 lastEmailSentDate 存储在 UserEntity 类中作为 LocalDateTime。

还为此创建存储库并实现邮件发送:

UserServiceImpl:

public boolean sendVerificationEmvail(UserEntity user){
    LocalDateTime last = user.getLastEmailSentDate();
    if(Objects.isNull(last) || !last.minusMinutes(1L).before(LocalDateTime.now())){
        return false;
    }

    user.setLastEmailSentDate(LocalDateTime.now());

    //Mail sending logic here

    userRepository.save(user);

    return true;
}

控制器:

@RequestMapping( value = "/resendMail", method = RequestMethod.POST)
public ApiException sendMail(@Valid @RequestBody EmailRequest emailRequest) {
    ApiException response = null;
    User user = userRepository.findByEmail(emailRequest.getEmail());
    if( user!=null) {
        if(userService.sendVerificationEmail(user)){
            response = new ApiException("Link sent to this email,", null, HttpStatus.OK);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 2021-08-24
    • 1970-01-01
    • 2014-06-23
    • 2019-02-28
    • 2018-09-15
    • 2022-01-13
    • 2012-02-04
    相关资源
    最近更新 更多