# AlertEmailService.java

    package cloud.wconnect.frontoffice.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 = "frontoffice.sqs.exception.";

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

        /**
         * 根据异常发送邮件
         *
         * @param exception 异常
         * @param queueUrl  队列url
         * @return void
         * @author lichen
         * @date 2023/6/8
         */
        public void sendEmail4SqsException(Exception exception, String queueUrl) {
            try {
                //获取异常类名称
                String exceptionClassName = exception.getClass().getSimpleName();
                //拼接缓存key
                String cacheKey = SQS_ALERT_KEY + exceptionClassName;
                //判断是否可以发送邮件
                if (redisTemplate.opsForValue().setIfAbsent(cacheKey, "1", 1, TimeUnit.DAYS)) {
                    //邮件主题
                    String subject = "FrontOffice SQS " + exceptionClassName;
                    //邮件内容
                    StringBuilder content = new StringBuilder("<p>");

                    //队列url
                    content.append("<br>queueUrl: ");
                    content.append(queueUrl);
                    content.append("<br>");

                    //异常信息
                    content.append("<br>Exception: ");
                    content.append(Arrays.asList(exception.getStackTrace()));
                    content.append("<br>");

                    content.append("</p>");
                    mailInternalService.sendAlertEmail(subject, content.toString());
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

    }