发送服务异常提醒邮件

导入jar包



    org.springframework.boot
    spring-boot-starter-mail
    2.7.6

邮件工具类用于生成session,定义发送邮件方法

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public final class JavaMailUntil {
    private JavaMailUntil() {}

    public static Session createSession() {
        //	账号信息
        String username = "[email protected]";//	邮箱发送账号
        String password = "在qq邮箱中获取";//	邮箱授权码
        //	创建一个配置文件,并保存
        Properties props = new Properties();
        //	SMTP服务器连接信息
        //  126——smtp.126.com
        //  163——smtp.163.com
        //    qq——smtp.qq.com
        props.put("mail.smtp.host", "smtp.qq.com");//	SMTP主机名
        //  126——25
        //  163——645
        props.put("mail.smtp.port", "25");//	主机端口号
        props.put("mail.smtp.auth", "true");//	是否需要用户认证
        props.put("mail.smtp.starttls.enale", "true");//	启用TlS加密

        Session session = Session.getInstance(props,new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);
            }
        });

        //控制台打印调试信息
        session.setDebug(false);
        return session;
    }

    public static void sendMsg(Session session,String subject,String text, String to) {
        //	创建邮件对象
        MimeMessage message = new MimeMessage(session);
        try {
            message.setSubject(subject);
            message.setText(text);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
            //	发送
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

RabbitMQMessageSender发送消息给mq,如何发送异常就会调用catch中发送邮件代码

import com.meteorological.pojo.MQMessage;
import com.meteorological.utils.dataConverter.JsonConverter;
import com.meteorological.utils.mail.JavaMailUntil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.Session;
import java.util.ArrayList;
import java.util.List;

@Component
public class RabbitMQMessageSender  implements MQMessageSender, RabbitTemplate.ConfirmCallback{
  private final RabbitTemplate rabbitTemplate;
  private boolean sendSuccessful = true;
  Log log = LogFactory.getLog(RabbitMQMessageSender.class);
  @Autowired
  public RabbitMQMessageSender(RabbitTemplate rabbitTemplate) {
    this.rabbitTemplate = rabbitTemplate;
  }

  @PostConstruct
  public void init(){
    rabbitTemplate.setConfirmCallback(this);
  }

  @Override
  public void confirm(CorrelationData correlationData, boolean ack, String cause) {
    if(!ack){
      log.error("消息接收失败" + cause);
      // 我们这里要做一些消息补发的措施
      System.out.println("id="+correlationData.getId());
    }
  }

  public void send(String routingKey, MQMessage msg) {
    String jsonString = JsonConverter.bean2Json(msg);
    if (jsonString != null) {
      try {
        rabbitTemplate.convertAndSend(routingKey, jsonString);
        sendSuccessful = true;
      } catch (Exception e) {
        // 连接异常,发送日志
        log.error("Failed to send message to rabbitmq部署的server RabbitMQ Exception: " + e.getMessage());
        if(sendSuccessful){
          Session session = JavaMailUntil.createSession();
          List toMail = new ArrayList<>();
          toMail.add("[email protected]");
          toMail.add("[email protected]");
          toMail.add("[email protected]");
          // 发送邮件给每个收件人
          for (String to : toMail) {
            JavaMailUntil.sendMsg(session,"rabbitmq部署的server mq连接异常","Failed to send message to rabbitmq部署的server RabbitMQ Exception: " + e.getMessage(), to);
          }
          sendSuccessful = false;
        }
      }
    }
  }
}

发布定时任务,每小时的第20分钟调用远程服务器色斑图服务,查看是否成功生成新的色斑图,如果返回null就发邮件

import com.meteorological.utils.mail.JavaMailUntil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.mail.Session;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 通过调用远程服务器上色斑图服务,获取生成色斑图是否正常,如果不正常发邮件
 */
@Component
public class TConfirm {
    Log log = LogFactory.getLog(TConfirm.class);
    private final RestTemplate restTemplate;
    @Autowired
    public TConfirm(RestTemplate  restTemplate) {
        this.restTemplate = restTemplate;
    }
    @PostConstruct
    @Scheduled(cron = "0 20 * * * *")
    public void Task1() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        Date dt = new Date();
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.HOUR_OF_DAY, -8);
        String startTime = sdf.format(rightNow.getTime()) + "0000";

        // 定义API的URL
        String apiUrl = "http://远程服务器/api/gis/colorFigure/getSurfColorFigure?adminCode=610000&time="+ startTime +"&element=TEM_Max&stationLevel=gjz";

        // 发送GET请求
        ResponseEntity response = restTemplate.getForEntity(apiUrl, String.class);

        // 获取响应体
        String responseBody = response.getBody();

        if(StringUtils.isEmpty(responseBody)){
            log.error("远程服务器 getSurfColorFigure interface get empty response by "+startTime);
            Session session = JavaMailUntil.createSession();
            List toMail = new ArrayList<>();
            toMail.add("[email protected]");
            toMail.add("[email protected]");
            for (String to : toMail) {
                JavaMailUntil.sendMsg(session,"色斑图异常","远程服务器 getSurfColorFigure interface get empty response by "+startTime, to);
            }
        }
    }
}

你可能感兴趣的:(Java基础,java)