# AlertEmailService.java

    package cloud.wconnect.workperformance.service;

    import cloud.wconnect.commonlib.service.MailInternalService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Service;

    import java.util.Arrays;
    import java.util.concurrent.TimeUnit;

    /**
     * 亚马逊消息队列出现异常时发送alertEmail
     *
     * @author lichen
     * @date 2023/6/8
     */
    @Service
    @Slf4j
    public class AlertEmailService {

        public static final String SQS_ALERT_KEY = "workperformance.sqs.exception.";

        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private RedisTemplate<String, String> redisTemplate;

        /**
         * 根据异常发送邮件
         *
         * @param exception 异常
         * @param queueUrl  队列url
         * @author zc
         * @date 2024/3/15
         */
        public void sendEmail4SqsException(Exception exception, String queueUrl) {
            try {
                // 获取异常类名称
                String exceptionClassName = exception.getClass().getSimpleName();
                // 拼接缓存key
                String cacheKey = SQS_ALERT_KEY + exceptionClassName;
                // 若当天已发送过邮件，则忽略，否则发送邮件
                if (Boolean.TRUE.equals(redisTemplate.opsForValue()
                        .setIfAbsent(cacheKey, "1", 1, TimeUnit.DAYS))) {
                    // 邮件主题
                    String subject = "work-performance SQS " + exceptionClassName;
                    // 邮件内容
                    String content = "<p><br>queueUrl: " +
                            queueUrl +
                            "<br><br>Exception: " +
                            Arrays.asList(exception.getStackTrace()) +
                            "<br></p>";
                    mailInternalService.sendAlertEmail(subject, content);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

    }