经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 其他 » 职业生涯 » 查看文章
Springboot进行Http接口交互实现邮件告警
来源:cnblogs  作者:大耳根图图  时间:2021/4/6 9:38:57  对本文有异议

本项目采用idea编辑器,依赖maven环境,相关搭建请自行百度

一、引入相关依赖
    本文Http接口交互使用hutool工具类与阿里FastJson解析报文。

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-test</artifactId>
  13. <scope>test</scope>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.projectlombok</groupId>
  17. <artifactId>lombok</artifactId>
  18. <version>RELEASE</version>
  19. <scope>compile</scope>
  20. </dependency>
  21. <!-- json -->
  22. <dependency>
  23. <groupId>com.alibaba</groupId>
  24. <artifactId>fastjson</artifactId>
  25. <version>1.2.75</version>
  26. </dependency>
  27. <!-- hutool工具类-->
  28. <dependency>
  29. <groupId>cn.hutool</groupId>
  30. <artifactId>hutool-all</artifactId>
  31. <version>5.3.8</version>
  32. </dependency>
  33. <!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
  34. <dependency>
  35. <groupId>com.sun.mail</groupId>
  36. <artifactId>javax.mail</artifactId>
  37. <version>1.6.2</version>
  38. </dependency>
  39. </dependencies>

二、编写相关配置
#本文使用163邮箱演示,邮箱需要开启IMAP/SMTP服务

 

 

 #在yml文件中配置相关参数

  1. server:
  2. port: 8080
  3. spring:
  4. mail:
  5. host: smtp.163.com
  6. port: 465
  7. username: @163.com
  8. password:
  9. properties:
  10. mail:
  11. smtp:
  12. auth: true
  13. starttls:
  14. enable: true
  15. required: true
  16. scripturl:
  17. url[0]:
  18. sort: 0
  19. url: https://gitee.com/login
  20. type: post
  21. params:
  22. account: 123456
  23. password: 123456
  24. emailParams: @163.com

三、编写工具类
#编写发送邮件工具类SendEmailUtils
#邮件发送方法最好使用异步方式,这样可以保证调用方法执行后及时回馈

  1. package com.auto.script.util;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.scheduling.annotation.Async;
  4. import org.springframework.stereotype.Service;
  5. import javax.mail.*;
  6. import javax.mail.internet.InternetAddress;
  7. import javax.mail.internet.MimeMessage;
  8. import java.security.Security;
  9. import java.util.Date;
  10. import java.util.Properties;
  11. /**
  12. * @Description: 发送邮件
  13. * @Author: bigearchart
  14. * @Date: 2021/4/2
  15. * @return
  16. */
  17. @Service
  18. public class SendEmailUtils {
  19. /** yml中配置的地址 */
  20. @Value(value = "${spring.mail.host}")
  21. private String host;
  22. /** yml中配置的端口 */
  23. @Value(value = "${spring.mail.port}")
  24. private String port;
  25. /** yml中配置的发件邮箱 */
  26. @Value(value = "${spring.mail.username}")
  27. private String userName;
  28. /** yml中配置的发件邮箱密码 */
  29. @Value(value = "${spring.mail.password}")
  30. private String passWord;
  31. /**
  32. * 使用加密的方式,利用465端口进行传输邮件,开启ssl
  33. * @param to 为收件人邮箱
  34. * @param message 发送的消息
  35. */
  36. @Async
  37. public void sendEmil(String to,String subject, String message) {
  38. try {
  39. Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  40. final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  41. //设置邮件会话参数
  42. Properties props = new Properties();
  43. //邮箱的发送服务器地址
  44. props.setProperty("mail.smtp.host", host);
  45. props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
  46. props.setProperty("mail.smtp.socketFactory.fallback", "false");
  47. //邮箱发送服务器端口,这里设置为465端口
  48. props.setProperty("mail.smtp.port", port);
  49. props.setProperty("mail.smtp.socketFactory.port", port);
  50. props.put("mail.smtp.auth", "true");
  51. final String username = userName;
  52. final String password = passWord;
  53. //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
  54. Session session = Session.getDefaultInstance(props, new Authenticator() {
  55. @Override
  56. protected PasswordAuthentication getPasswordAuthentication() {
  57. return new PasswordAuthentication(username, password);
  58. }
  59. });
  60. //通过会话,得到一个邮件,用于发送
  61. Message msg = new MimeMessage(session);
  62. //设置发件人
  63. msg.setFrom(new InternetAddress(userName));
  64. //设置收件人
  65. msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
  66. //设置邮件消息
  67. msg.setContent(message, "text/html; charset=utf-8");
  68. //设置邮件标题
  69. msg.setSubject(subject);
  70. //设置发送的日期
  71. msg.setSentDate(new Date());
  72. //调用Transport的send方法去发送邮件
  73. Transport.send(msg);
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. }

四、业务代码实现
#编写接口接收类ScriptUrl 需要注意字段名与yml中配置的字段名必须一致,不然会
#自动解析失败

  1. package com.auto.script.entity;
  2. import java.util.Map;
  3. /**
  4. * @author :bigearchart
  5. * @date :Created in 2021/4/1 16:31
  6. * @description: 脚本检查接口类
  7. * @version: 1.0
  8. */
  9. public class ScriptUrl {
  10. /** 排序字段*/
  11. public int sort;
  12. /** 请求路径*/
  13. public String url;
  14. /** 请求类型*/
  15. public String type;
  16. /** 请求参数*/
  17. public Map<String, Object> params;
  18. public int getSort() {
  19. return sort;
  20. }
  21. public void setSort(int sort) {
  22. this.sort = sort;
  23. }
  24. public String getUrl() {
  25. return url;
  26. }
  27. public void setUrl(String url) {
  28. this.url = url;
  29. }
  30. public String getType() {
  31. return type;
  32. }
  33. public void setType(String type) {
  34. this.type = type;
  35. }
  36. public Map<String, Object> getParams() {
  37. return params;
  38. }
  39. public void setParams(Map<String, Object> params) {
  40. this.params = params;
  41. }
  42. }

#编写参数注入类

  1. package com.auto.script.util;
  2. import com.auto.script.entity.ScriptUrl;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  5. import org.springframework.context.annotation.Configuration;
  6. import java.util.List;
  7. /**
  8. * @Description: 脚本检查接口参数注入类
  9. * @Author: bigearchart
  10. * @Date: 2021/4/1
  11. * @return
  12. */
  13. @Configuration
  14. @ConfigurationProperties(prefix = "scripturl")
  15. @EnableConfigurationProperties(ScriptUrlEnum.class)
  16. public class ScriptUrlEnum {
  17. private List<ScriptUrl> url;
  18. public List<ScriptUrl> getUrl() {
  19. return url;
  20. }
  21. public void setUrl(List<ScriptUrl> url) {
  22. this.url = url;
  23. }
  24. }

#定义接口

  1. package com.auto.script.service;
  2. /**
  3. * @author :bigearchart
  4. * @date :Created in 2021/4/1 15:53
  5. * @description: 定时任务配置类
  6. * @version: 1.0
  7. */
  8. public interface QuazrtAutoService {
  9. /**
  10. * 定时任务每隔一分钟执行验证接口服务是否正常
  11. */
  12. public void autoCrontab();
  13. }

#编写接口实现类

  1. package com.auto.script.service.impl;
  2. import cn.hutool.core.util.StrUtil;
  3. import cn.hutool.http.HttpUtil;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.auto.script.entity.ScriptUrl;
  6. import com.auto.script.service.QuazrtAutoService;
  7. import com.auto.script.util.ScriptUrlEnum;
  8. import com.auto.script.util.SendEmailUtils;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Value;
  11. import org.springframework.scheduling.annotation.Scheduled;
  12. import org.springframework.stereotype.Component;
  13. import javax.annotation.Resource;
  14. import java.util.List;
  15. /**
  16. * @author :bigearchart
  17. * @date :Created in 2021/4/1 15:53
  18. * @description: 定时任务配置实现类
  19. * @version: 1.0
  20. */
  21. @Slf4j
  22. @Component
  23. public class QuazrtAutoServiceImpl implements QuazrtAutoService {
  24. @Value(value = "${emailParams:}")
  25. private String[] emailParams;
  26. @Resource
  27. private ScriptUrlEnum scriptUrlEnum;
  28. @Resource
  29. private SendEmailUtils sendEmailUtils;
  30. /**
  31. * 定时任务每隔一分钟执行验证接口服务是否正常
  32. */
  33. @Override
  34. @Scheduled(cron = "0 */1 * * * ?")
  35. public void autoCrontab() {
  36. try{
  37. //读取配置接口参数
  38. List<ScriptUrl> url = scriptUrlEnum.getUrl();
  39. //循环测试接口
  40. for (ScriptUrl scriptUrl: url) {
  41. String urlStr = scriptUrl.getUrl();
  42. String type = scriptUrl.getType();
  43. //验证参数非空
  44. if(StrUtil.hasEmpty(urlStr, type)){
  45. throw new RuntimeException("接口路径、请求类型不能为空,返回结果为空");
  46. }
  47. log.info("============================本次测试接口【" + urlStr +"】==================");
  48. //参数转json字符串
  49. String paramsStr = JSONObject.toJSONString(scriptUrl.getParams());
  50. String jsonStr = null;
  51. //验证请求类型
  52. if(type.equals("post")){
  53. //进行接口交互
  54. jsonStr = HttpUtil.post(scriptUrl.getUrl(), paramsStr);
  55. }else{
  56. //验证参数是否为空
  57. if(scriptUrl.getParams().isEmpty() || scriptUrl.getParams().size() <= 0){
  58. //进行接口交互
  59. jsonStr = HttpUtil.get(scriptUrl.getUrl()).toString();
  60. }else {
  61. //进行接口交互
  62. jsonStr = HttpUtil.get(scriptUrl.getUrl(), scriptUrl.getParams());
  63. }
  64. }
  65. log.info("=============================接口返回结果为:" );
  66. log.info(jsonStr);
  67. //验证返回结果是否为空
  68. if(StrUtil.isEmpty(jsonStr)){
  69. throw new RuntimeException("接口路径为【" + urlStr + "】的接口,返回结果为空");
  70. }
  71. //解析返回结果
  72. JSONObject jsonObject = JSONObject.parseObject(jsonStr);
  73. //获取响应码
  74. String code = jsonObject.get("code").toString();
  75. //判断响应码是否正确
  76. if(StrUtil.isEmpty(code) || ! code.equals("200")){
  77. throw new RuntimeException("接口路径为【" + urlStr + "】的接口请求错误,接口返回结果为:" + jsonStr);
  78. }
  79. }
  80. }catch (Exception e){
  81. //发送邮件
  82. sendEmail(e.getMessage());
  83. //控制台输出
  84. log.info(e.toString());
  85. }
  86. }
  87. /**
  88. * 封装邮件参数方法
  89. * @param msg --- 发送文本
  90. */
  91. public void sendEmail(String msg){
  92. //循环待发送邮件集合
  93. for (String email: emailParams ) {
  94. //非空情况再执行
  95. if(StrUtil.isNotEmpty(email)){
  96. sendEmailUtils.sendEmil(email, "接口测试告警邮件", msg);
  97. }
  98. }
  99. }
  100. }

五、启动类配置
#在启动类添加相关配置
# @EnableScheduling --- 开启对定时任务支持
# @EnableAsync --- 开启异步注解支持

  1. /**
  2. * @Description: 定时任务实现自动执行接口测试项目启动类
  3. * @Author: bigearchart
  4. * @Date: 2021/4/1
  5. * @return
  6. */
  7. @SpringBootApplication
  8. @EnableScheduling
  9. @EnableAsync
  10. public class ScriptApplication {
  11. public static void main(String[] args) {
  12. SpringApplication.run(ScriptApplication.class, args);
  13. }
  14. }

六、启动项目
#项目启动后,查看控制台输出结果

#静等一分钟就可以看到接口请求的输出信息

#然后查看邮箱会收到一封告警邮件

 

 

本次的学习到这里就结束了,会根据实际使用更新文章。

如果对您有帮助 请点个关注,万分感谢
项目源码地址:
https://gitee.com/bigearchart_admin/script.git



原文链接:http://www.cnblogs.com/bigearchart/p/14610549.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号