Springboot進行Http接口交互實現(xiàn)郵件告警
一個努力中的公眾號
長的好看的人都關注了

本項目采用idea編輯器,依賴maven環(huán)境,相關搭建請自行百度
一、引入相關依賴
本文Http接口交互使用hutool工具類與阿里FastJson解析報文。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<!-- hutool工具類-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
二、編寫相關配置
#本文使用163郵箱演示,郵箱需要開啟IMAP/SMTP服務
#在yml文件中配置相關參數(shù)
server:
port: 8080
spring:
mail:
host: smtp.163.com
port: 465
username: @163.com
password:
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
scripturl:
url[0]:
sort: 0
url: https://gitee.com/login
type: post
params:
account: 123456
password: 123456
emailParams: @163.com
三、編寫工具類
#編寫發(fā)送郵件工具類SendEmailUtils
#郵件發(fā)送方法最好使用異步方式,這樣可以保證調用方法執(zhí)行后及時回饋
package com.auto.script.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
/**
* @Description: 發(fā)送郵件
* @Author: bigearchart
* @Date: 2021/4/2
* @return
*/
@Service
public class SendEmailUtils {
/** yml中配置的地址 */
@Value(value = "${spring.mail.host}")
private String host;
/** yml中配置的端口 */
@Value(value = "${spring.mail.port}")
private String port;
/** yml中配置的發(fā)件郵箱 */
@Value(value = "${spring.mail.username}")
private String userName;
/** yml中配置的發(fā)件郵箱密碼 */
@Value(value = "${spring.mail.password}")
private String passWord;
/**
* 使用加密的方式,利用465端口進行傳輸郵件,開啟ssl
* @param to 為收件人郵箱
* @param message 發(fā)送的消息
*/
@Async
public void sendEmil(String to,String subject, String message) {
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//設置郵件會話參數(shù)
Properties props = new Properties();
//郵箱的發(fā)送服務器地址
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//郵箱發(fā)送服務器端口,這里設置為465端口
props.setProperty("mail.smtp.port", port);
props.setProperty("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.auth", "true");
final String username = userName;
final String password = passWord;
//獲取到郵箱會話,利用匿名內部類的方式,將發(fā)送者郵箱用戶名和密碼授權給jvm
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
//通過會話,得到一個郵件,用于發(fā)送
Message msg = new MimeMessage(session);
//設置發(fā)件人
msg.setFrom(new InternetAddress(userName));
//設置收件人
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
//設置郵件消息
msg.setContent(message, "text/html; charset=utf-8");
//設置郵件標題
msg.setSubject(subject);
//設置發(fā)送的日期
msg.setSentDate(new Date());
//調用Transport的send方法去發(fā)送郵件
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、業(yè)務代碼實現(xiàn)
#編寫接口接收類ScriptUrl 需要注意字段名與yml中配置的字段名必須一致,不然會
#自動解析失敗
package com.auto.script.entity;
import java.util.Map;
/**
* @author :bigearchart
* @date :Created in 2021/4/1 16:31
* @description:腳本檢查接口類
* @version: 1.0
*/
public class ScriptUrl {
/** 排序字段*/
public int sort;
/** 請求路徑*/
public String url;
/** 請求類型*/
public String type;
/** 請求參數(shù)*/
public Map<String, Object> params;
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
}
#編寫參數(shù)注入類
package com.auto.script.util;
import com.auto.script.entity.ScriptUrl;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @Description: 腳本檢查接口參數(shù)注入類
* @Author: bigearchart
* @Date: 2021/4/1
* @return
*/
@Configuration
@ConfigurationProperties(prefix = "scripturl")
@EnableConfigurationProperties(ScriptUrlEnum.class)
public class ScriptUrlEnum {
private List<ScriptUrl> url;
public List<ScriptUrl> getUrl() {
return url;
}
public void setUrl(List<ScriptUrl> url) {
this.url = url;
}
}
#定義接口
package com.auto.script.service;
/**
* @author :bigearchart
* @date :Created in 2021/4/1 15:53
* @description:定時任務配置類
* @version: 1.0
*/
public interface QuazrtAutoService {
/**
* 定時任務每隔一分鐘執(zhí)行驗證接口服務是否正常
*/
public void autoCrontab();
}
#編寫接口實現(xiàn)類
package com.auto.script.service.impl;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.auto.script.entity.ScriptUrl;
import com.auto.script.service.QuazrtAutoService;
import com.auto.script.util.ScriptUrlEnum;
import com.auto.script.util.SendEmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
* @author :bigearchart
* @date :Created in 2021/4/1 15:53
* @description:定時任務配置實現(xiàn)類
* @version: 1.0
*/
@Slf4j
@Component
public class QuazrtAutoServiceImpl implements QuazrtAutoService {
@Value(value = "${emailParams:}")
private String[] emailParams;
@Resource
private ScriptUrlEnum scriptUrlEnum;
@Resource
private SendEmailUtils sendEmailUtils;
/**
* 定時任務每隔一分鐘執(zhí)行驗證接口服務是否正常
*/
@Override
@Scheduled(cron = "0 */1 * * * ?")
public void autoCrontab() {
try{
//讀取配置接口參數(shù)
List<ScriptUrl> url = scriptUrlEnum.getUrl();
//循環(huán)測試接口
for (ScriptUrl scriptUrl: url) {
String urlStr = scriptUrl.getUrl();
String type = scriptUrl.getType();
//驗證參數(shù)非空
if(StrUtil.hasEmpty(urlStr, type)){
throw new RuntimeException("接口路徑、請求類型不能為空,返回結果為空");
}
log.info("============================本次測試接口【" + urlStr +"】==================");
//參數(shù)轉json字符串
String paramsStr = JSONObject.toJSONString(scriptUrl.getParams());
String jsonStr = null;
//驗證請求類型
if(type.equals("post")){
//進行接口交互
jsonStr = HttpUtil.post(scriptUrl.getUrl(), paramsStr);
}else{
//驗證參數(shù)是否為空
if(scriptUrl.getParams().isEmpty() || scriptUrl.getParams().size() <= 0){
//進行接口交互
jsonStr = HttpUtil.get(scriptUrl.getUrl()).toString();
}else {
//進行接口交互
jsonStr = HttpUtil.get(scriptUrl.getUrl(), scriptUrl.getParams());
}
}
log.info("=============================接口返回結果為:" );
log.info(jsonStr);
//驗證返回結果是否為空
if(StrUtil.isEmpty(jsonStr)){
throw new RuntimeException("接口路徑為【" + urlStr + "】的接口,返回結果為空");
}
//解析返回結果
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
//獲取響應碼
String code = jsonObject.get("code").toString();
//判斷響應碼是否正確
if(StrUtil.isEmpty(code) || ! code.equals("200")){
throw new RuntimeException("接口路徑為【" + urlStr + "】的接口請求錯誤,接口返回結果為:" + jsonStr);
}
}
}catch (Exception e){
//發(fā)送郵件
sendEmail(e.getMessage());
//控制臺輸出
log.info(e.toString());
}
}
/**
* 封裝郵件參數(shù)方法
* @param msg --- 發(fā)送文本
*/
public void sendEmail(String msg){
//循環(huán)待發(fā)送郵件集合
for (String email: emailParams ) {
//非空情況再執(zhí)行
if(StrUtil.isNotEmpty(email)){
sendEmailUtils.sendEmil(email, "接口測試告警郵件", msg);
}
}
}
}
五、啟動類配置
#在啟動類添加相關配置
# @EnableScheduling --- 開啟對定時任務支持
# @EnableAsync --- 開啟異步注解支持
package com.auto.script;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @Description: 定時任務實現(xiàn)自動執(zhí)行接口測試項目啟動類
* @Author: bigearchart
* @Date: 2021/4/1
* @return
*/
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ScriptApplication {
public static void main(String[] args) {
SpringApplication.run(ScriptApplication.class, args);
}
}
六、啟動項目
#項目啟動后,查看控制臺輸出結果
#靜等一分鐘就可以看到接口請求的輸出信息
#然后查看郵箱會收到一封告警郵件
項目源碼地址:
https://gitee.com/bigearchart_admin/script.git
本次的學習到這里就結束了,會根據(jù)實際使用更新文章。
如果對您有幫助 請點個關注,萬分感謝
(QQ招聘群 710566091
微信招聘群 請加圖圖微信)
評論
圖片
表情
