本專案采用idea編輯器,依賴maven環境,相關搭建請自行百度
一、引入相關依賴
本文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檔案中配置相關引數
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
三、撰寫工具類
#撰寫發送郵件工具類SendEmailUtils
#郵件發送方法最好使用異步方式,這樣可以保證呼叫方法執行后及時回饋
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: 發送郵件 * @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中配置的發件郵箱 */ @Value(value = "${spring.mail.username}") private String userName; /** yml中配置的發件郵箱密碼 */ @Value(value = "${spring.mail.password}") private String passWord; /** * 使用加密的方式,利用465埠進行傳輸郵件,開啟ssl * @param to 為收件人郵箱 * @param message 發送的訊息 */ @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"; //設定郵件會話引數 Properties props = new Properties(); //郵箱的發送服務器地址 props.setProperty("mail.smtp.host", host); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); //郵箱發送服務器埠,這里設定為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; //獲取到郵箱會話,利用匿名內部類的方式,將發送者郵箱用戶名和密碼授權給jvm Session session = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); //通過會話,得到一個郵件,用于發送 Message msg = new MimeMessage(session); //設定發件人 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); //設定發送的日期 msg.setSentDate(new Date()); //呼叫Transport的send方法去發送郵件 Transport.send(msg); } catch (Exception e) { e.printStackTrace(); } } }
四、業務代碼實作
#撰寫介面接收類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; /** 請求引數*/ 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; } }
#撰寫引數注入類
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: 腳本檢查介面引數注入類 * @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 { /** * 定時任務每隔一分鐘執行驗證介面服務是否正常 */ public void autoCrontab(); }
#撰寫介面實作類
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: 定時任務配置實作類 * @version: 1.0 */ @Slf4j @Component public class QuazrtAutoServiceImpl implements QuazrtAutoService { @Value(value = "${emailParams:}") private String[] emailParams; @Resource private ScriptUrlEnum scriptUrlEnum; @Resource private SendEmailUtils sendEmailUtils; /** * 定時任務每隔一分鐘執行驗證介面服務是否正常 */ @Override @Scheduled(cron = "0 */1 * * * ?") public void autoCrontab() { try{ //讀取配置介面引數 List<ScriptUrl> url = scriptUrlEnum.getUrl(); //回圈測驗介面 for (ScriptUrl scriptUrl: url) { String urlStr = scriptUrl.getUrl(); String type = scriptUrl.getType(); //驗證引數非空 if(StrUtil.hasEmpty(urlStr, type)){ throw new RuntimeException("介面路徑、請求型別不能為空,回傳結果為空"); } log.info("============================本次測驗介面【" + urlStr +"】=================="); //引數轉json字串 String paramsStr = JSONObject.toJSONString(scriptUrl.getParams()); String jsonStr = null; //驗證請求型別 if(type.equals("post")){ //進行介面互動 jsonStr = HttpUtil.post(scriptUrl.getUrl(), paramsStr); }else{ //驗證引數是否為空 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){ //發送郵件 sendEmail(e.getMessage()); //控制臺輸出 log.info(e.toString()); } } /** * 封裝郵件引數方法 * @param msg --- 發送文本 */ public void sendEmail(String msg){ //回圈待發送郵件集合 for (String email: emailParams ) { //非空情況再執行 if(StrUtil.isNotEmpty(email)){ sendEmailUtils.sendEmil(email, "介面測驗告警郵件", msg); } } } }
五、啟動類配置
#在啟動類添加相關配置
# @EnableScheduling --- 開啟對定時任務支持
# @EnableAsync --- 開啟異步注解支持
/** * @Description: 定時任務實作自動執行介面測驗專案啟動類 * @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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/271856.html
標籤:其他
