当用户发布电子邮件时,我只想在同一用户发送电子邮件请求之前超过 1 分钟后才发送邮件。我怎样才能做到这一点?

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?

@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) {

}

您可以简单地将 UserEntity class 中的 lastEmailSentDate 存储为 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);
        }
    }
}