SpringBoot邮件报警

SpringBoot邮件报警

一、介绍

邮件报警,大体思路就是收集服务器发生的异常发送到邮箱,做到服务器出问题第一时间知道,当然要是不关注邮箱当我没说

(1)、引入依赖

    <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-mail</artifactid>
        </dependency>

二、配置邮箱

(1)、注册两个邮箱账号(一个用来发送,一个用来接收)

(2)、找到邮箱设置打开协议

SpringBoot邮件报警

三、配置yml

非阿里云下方的配置文件需要授权码(不了解可以百度xx邮箱怎么获取授权码)

spring:
  mail:
    host:  #发送邮件服务器
    username:  #发送邮件的邮箱地址
    password:    #(如果是阿里云)阿里云邮箱没有qq邮箱所谓的授权码,所以此处填的是阿里云的登陆密码
    from:   # 发送邮件的地址,和上面username一致
    to:     # 接受邮件的地址
    properties.mail.smtp.starttls.enable: true
    properties.mail.smtp.starttls.required: true
    properties.mail.smtp.ssl.enable: true
    default-encoding: utf-8

四、编写代码

(1)、编写发送邮件工具类(EmailUtils)

package cn.zz.practice.util;

import cn.zz.practice.config.MailProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class EmailUtils {

    @Resource
    private JavaMailSender sender;
    @Resource
    private MailProperties mailProperties;

    @Value("${spring.mail.from}")
    private String from;
//    @Value("${spring.profiles.active}")
//    private String active;
    @Value("${spring.mail.to}")
    private String to;

    /**
     * 发送纯文本的简单邮件
     *
     * @param content 发送的文本内容
     */
    public void sendSimpleMail(String content) {
//        //如果是开发环境,直接返回,不发送邮件
//        if (StringUtils.equals(active,"dev")) {
//            return;
//        }
        //邮件主题
        String subject = "~~~~~~~~~未知异常~~~~~~~~~";
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人邮箱
        message.setFrom(this.mailProperties.getFrom());
        //要发送的邮箱
        message.setTo(this.mailProperties.getTo());
        message.setSubject(subject);
        message.setText(content);
        try {
            sender.send(message);
            log.info("简单邮件已经发送。");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常!", e);
        }
    }
}

(2)、拦截所有异常并发送邮件

package cn.zz.practice.aop;

import cn.zz.practice.util.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

@Slf4j
@RestControllerAdvice
public class WebRestControllerAdvice {

    @Resource
    private EmailUtils mailUtil;

    @ExceptionHandler(Exception.class)
    public String handleRuntimeException(Exception runtimeException, HttpServletRequest req) {
        log.error(runtimeException.getMessage());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        runtimeException.printStackTrace(pw);
        String body = this.readBody(req);
        String content = String.format("url:%s\n请求参数:%s\n请求body:%s\n栈信息:%s", req.getRequestURL(), JSONObject.toJSONString(req.getParameterMap()), body, sw.toString());
        this.mailUtil.sendSimpleMail(content);
        return "服务器错误";
    }

    public String readBody(HttpServletRequest request) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            log.error("[严重异常]读取请求body异常", e);
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

}

ExceptionHandler 的使用场景就是在 Controller 中捕获异常,全局统一处理,而不是在每个 handler 中都进行繁琐的异常捕获操作,优点就是代码整洁。
ExceptionHandler 异常处理过程大体为:执行 handler 方法如果抛出了异常,就根据异常类型查找到对应的异常处理方法,然后执行对应的方法

(3)、编写测试crontroller写个异常

@RestController
@RequestMapping("/demoController")
public class DemoController {
    @GetMapping
    public void sb(){
        int i= 1/0;
    }
}

然后就会接到邮件

SpringBoot邮件报警

迷途者寻影而行

Original: https://www.cnblogs.com/pkkyh/p/14631405.html
Author: 迷途者寻影而行
Title: SpringBoot邮件报警

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/575762/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球