Spring定时任务使用及如何使用邮件监控服务器

 更新时间:2019年07月23日 14:45:10   作者:挑战者V  
这篇文章主要介绍了Spring定时任务使用及如何使用邮件监控服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Spring相关的依赖导入进去,即可使用spring的定时任务!

<!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.13.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.13.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.13.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.13.RELEASE</version>
    </dependency>

定时任务是开发中常用的,比如订单查询,一位客人订购的某个东西,但是尚未支付,超过订单时效期自动失效,那么又是怎么样知道订单的时效性过呢?定时任务,可以每分钟或者每秒钟进行查询。

定时任务的应用是非常广的,下面应用下监控服务器,虽然说现在开源监控软件挺多的,什么zabbix,nagios或者其他等等。下面我将使用代码监控服务器:

首先准备邮件的依赖:

<!-- 发邮件 -->      
    <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.5.2</version>
      <scope>provided</scope>
    </dependency>

邮件工具类:

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {

  public static void sendMail(String email, String emailMsg)
      throws AddressException, MessagingException {
    // 1.创建一个程序与邮件服务器会话对象 Session

    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "SMTP");
    props.setProperty("mail.host", "smtp.163.com");
    props.setProperty("mail.smtp.auth", "true");// 指定验证为true

    // 创建验证器
    Authenticator auth = new Authenticator() {
      public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("123@163.com", "123");
      }
    };

    Session session = Session.getInstance(props, auth);

    // 2.创建一个Message,它相当于是邮件内容
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress("123@163.com")); // 设置发送者

    message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者

    message.setSubject("邮件告警");

    message.setContent(emailMsg, "text/html;charset=utf-8");

    // 3.创建 Transport用于将邮件发送

    Transport.send(message);
    
  }
  
  
}

监控服务器类:

package cn.pms.monitor; 
 
import java.io.InputStream; 
import java.net.URL; 
import java.net.URLConnection;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import cn.pms.util.MailUtils; 
 
public class MonitorUrl { 
 

   
  public static void testUrlWithTimeOut2016(String urlString,int timeOutMillSeconds){ 
    long lo = System.currentTimeMillis(); 
    URL url;  
    try {  
       url = new URL(urlString);  
       URLConnection co = url.openConnection(); 
       co.setConnectTimeout(timeOutMillSeconds); 
       co.connect(); 
       System.out.println("连接可用");  
    } catch (Exception e1) {  
       System.out.println("连接打不开!");  
       url = null;  
       emailMonitor2016();
    }  
    System.out.println(System.currentTimeMillis()-lo); 
  } 
  
  public static void testUrlWithTimeOut2018(String urlString,int timeOutMillSeconds){ 
    long lo = System.currentTimeMillis(); 
    URL url;  
    try {  
       url = new URL(urlString);  
       URLConnection co = url.openConnection(); 
       co.setConnectTimeout(timeOutMillSeconds); 
       co.connect(); 
       System.out.println("连接可用");  
    } catch (Exception e1) {  
       System.out.println("连接打不开!");  
       url = null;  
       emailMonitor2018();
    }  
    System.out.println(System.currentTimeMillis()-lo); 
  } 
  
  public static void testUrlWithTimeOut1818(String urlString,int timeOutMillSeconds){ 
    long lo = System.currentTimeMillis(); 
    URL url;  
    try {  
       url = new URL(urlString);  
       URLConnection co = url.openConnection(); 
       co.setConnectTimeout(timeOutMillSeconds); 
       co.connect(); 
       System.out.println("连接可用");  
    } catch (Exception e1) {  
       System.out.println("连接打不开!");  
       url = null;  
       emailMonitor1818();;
    }  
    System.out.println(System.currentTimeMillis()-lo); 
  } 
  
  public static void testUrlWithTimeOut1616(String urlString,int timeOutMillSeconds){ 
    long lo = System.currentTimeMillis(); 
    URL url;  
    try {  
       url = new URL(urlString);  
       URLConnection co = url.openConnection(); 
       co.setConnectTimeout(timeOutMillSeconds); 
       co.connect(); 
       System.out.println("连接可用");  
    } catch (Exception e1) {  
       System.out.println("连接打不开!");  
       url = null;  
       emailMonitor1616();
    }  
    System.out.println(System.currentTimeMillis()-lo); 
  } 

  
  public static void emailMonitor2016() {
    try {
      MailUtils.sendMail("123@qq.com", "tomcat服务器端口为2016宕机了");
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  public static void emailMonitor2018() {
    try {
      MailUtils.sendMail("123@qq.com", "tomcat服务器端口为2018宕机了");
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  public static void emailMonitor1818() {
    try {
      MailUtils.sendMail("1236@qq.com", "tomcat服务器端口为1818宕机了");
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  public static void emailMonitor1616() {
    try {
      MailUtils.sendMail("123@qq.com", "tomcat服务器端口为1616宕机了");
    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

具体定时任务类:

@Component
public class QuartzJob {
  
private static Logger logger = Logger.getLogger(QuartzJob.class);
  

  
  @Scheduled(cron = "0 0/1 * * * ? ")
  public void test() {
    MonitorUrl.testUrlWithTimeOut2018("http://www.yc520.com:2018/", 2000);

    MonitorUrl.testUrlWithTimeOut1616("http://www.yc520.com:1616/", 2000);
    logger.info("每分钟执行" + System.currentTimeMillis());
  }
  
  @Scheduled(cron = "0 10 0 * * ?")
  public void monitorServerTest() {
    
    System.out.println("每10分钟监控一次2018服务器和1616服务器");
    MonitorUrl.testUrlWithTimeOut2018("http://www.yc520.com:2018/", 2000);
    MonitorUrl.testUrlWithTimeOut1616("http://www.yc520.com:1616/", 2000);
  }
  
  @Scheduled(cron="0 30 0 * * ?")
  public void monitorServer() {
    System.out.println("每30分钟监控一次1818测试服务器");
    MonitorUrl.testUrlWithTimeOut1818("http://www.yc520:1818/", 2000);
  }

}

由此就可以达到监控服务器的目的,当然这只是小试牛刀,而且也不够全面,当然也存在问题,如果是每分钟定时任务检测,突然一台服务器挂了,那么将会源源不断的发送邮件,163邮件是有限的,而且频繁的可能会被当成垃圾邮件,我只需要知道一条信息,某某服务器宕机了,一遍就可以,最后给我发三十遍,如此的话,大量的无效邮件很浪费资源,而且浪费时间。

所以说,本文只是一个服务器监控小示例,实际开发中,切勿直接拿来用,最好要有相关的判断和逻辑。这样才能比较高效,达到预期期望。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java实现飞机大战游戏

    java实现飞机大战游戏

    这篇文章主要为大家详细介绍了java实现飞机大战游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-03-03
  • 简单谈谈JVM、JRE和JDK的区别与联系

    简单谈谈JVM、JRE和JDK的区别与联系

    简单的说JDK是用于开发的而JRE是用于运行Java程序的。JDK和JRE都包含了JVM,从而使得我们可以运行Java程序。JVM是Java编程语言的核心并且具有平台独立性。
    2016-05-05
  • Java实现Dijkstra输出最短路径的实例

    Java实现Dijkstra输出最短路径的实例

    这篇文章主要介绍了Java实现Dijkstra输出最短路径的实例的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下
    2017-09-09
  • 详解在Spring MVC或Spring Boot中使用Filter打印请求参数问题

    详解在Spring MVC或Spring Boot中使用Filter打印请求参数问题

    这篇文章主要介绍了详解在Spring MVC或Spring Boot中使用Filter打印请求参数问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Spring使用注解存储Bean对象的方法详解

    Spring使用注解存储Bean对象的方法详解

    在使用学习使用 Spring过程中,当我们要实现一个功能的时候,先应该考虑的是有没有相应的注解是实现对应功能的,Spring 中很多功能的配置都是可以依靠注解实现的,而本篇中介绍的是使用注解来存储 Bean 对象
    2023-07-07
  • 重新实现hashCode()方法

    重新实现hashCode()方法

    hashCode()是Java中的一个重要方法,用于计算对象的哈希码。本文介绍了如何重新实现hashCode()方法,包括使用对象的属性计算哈希码、使用字符串拼接计算哈希码、使用随机数计算哈希码等方法。同时,还介绍了如何避免哈希冲突,提高哈希表的效率。
    2023-04-04
  • Java注解Annotation与自定义注解详解

    Java注解Annotation与自定义注解详解

    本文全面讲述了Java注解Annotation与Java自定义注解及相关内容,大家可以认真看看
    2018-03-03
  • 阿里的一道Java并发面试题详解

    阿里的一道Java并发面试题详解

    这篇文章主要介绍了阿里的一道Java并发面试题详解,网络、并发相关的知识,相对其他一些编程知识点更难一些,主要是不好调试并且涉及内容太多 !,需要的朋友可以参考下
    2019-06-06
  • IntelliJ IDEA(2020.2)的下载、安装步骤详细教程

    IntelliJ IDEA(2020.2)的下载、安装步骤详细教程

    这篇文章主要介绍了IntelliJ IDEA(2020.2)的下载、安装步骤详细教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • Java代理模式之静态代理与动态代理的区别及优缺点

    Java代理模式之静态代理与动态代理的区别及优缺点

    代理模式是一种常用的设计模式,它允许通过引入一个代理对象来控制对目标对象的访问,在Java中,代理模式被广泛应用,它可以提供额外的功能,如权限检查、缓存、日志记录等,本文将介绍静态代理与动态代理的区别及优缺点,需要的朋友可以参考下
    2023-06-06

最新评论