SpringBoot 学习日志10.异步、定时、邮件任务(使用IDEA)

参考博客

简介

在工作中,常常会用到异步处理任务,比如在网站上发送邮件,后台发送邮件需要时间,期间前台会有响应不动的情况,直到邮件发送完毕,响应才会成功。一般会采用多线程的方式去处理这些任务。还有一些定时任务,比如需要在每天00:00的时候,分析一次前一天的日志信息。还有就是邮件的发送,微信的前身也是邮件服务。SpringBoot都提供了对应的支持,上手使用十分的简单,只需要开启一些注解支持,配置一些配置文件即可!

异步任务

  1、在业务层编写方法,假装正在处理数据,使用线程设置一些延时(Sleep),模拟同步等待的情况。然后给方法添加@Async注解,SpringBoot就会自己开一个线程池,进行调用!但是要让这个注解生效,我们还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能。

@Service
public class AsyncService {


    //告诉spring这是一个异步的方法
    @Async
    public void hello() throws InterruptedException {

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理");

    }

}

2、编写AsyncController类

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello() throws InterruptedException {
        asyncService.hello();
        return "ok";
    }

}

3、测试,注意一定要加上@EnableAsync注解!!!

//开启异步功能的注解
@EnableAsync
//开启定时任务功能的 注解
@EnableScheduling
@SpringBootApplication
public class Springboot09TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }

}

定时任务

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨的时候,分析一次前一天的日志信息,Spring为我们提供了异步执行任务调度的方式,提供了两个接口。

  • TaskExecutor接口

  • TaskScheduler接口

两个注解:

  • @EnableScheduling

  • @Scheduled

cron表达式:

图片

图片

1、编写一个业务方法

@Service
public class ScheduledService {

    //在特定时间执行这个方法
    //cron表达式~
    //秒 分 时 日 月 星期

    /**
     *  30 5 22 * * ? 每天22:5:30执行
     *  30 5 22,15 * * ? 每天22:5:30/15:5:30执行
     *  30 0/5 22,15 * * ? 每天22|15每隔5分钟执行
     *  0 15 10 ? * 1-6 每个月的周一到周六的10:15:0
     */
    @Scheduled(cron = "30 5 22 * * 0-7")
    public void hello(){
        System.out.println("hello,定时任务被执行了~");
    }

}

2、在主程序上增加@EnableScheduling 开启定时任务功能

//开启异步功能的注解
@EnableAsync
//开启定时任务功能的 注解
@EnableScheduling
@SpringBootApplication
public class Springboot09TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot09TestApplication.class, args);
    }

}

cron表达式详解

网址:http://www.bejson.com/othertools/cron/

(1)0/2 * * * * ?   表示每2秒 执行任务
(1)0 0/2 * * * ?   表示每2分钟 执行任务
(1)0 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务
(2)0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
(3)0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(4)0 0 10,14,16 * * ?   每天上午10点,下午2点,4点
(5)0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
(6)0 0 12 ? * WED   表示每个星期三中午12点
(7)0 0 12 * * ?   每天中午12点触发
(8)0 15 10 ? * *   每天上午10:15触发
(9)0 15 10 * * ?     每天上午10:15触发
(10)0 15 10 * * ?   每天上午10:15触发
(11)0 15 10 * * ? 2005   2005年的每天上午10:15触发
(12)0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
(13)0 0/5 14 * * ?   在每天下午2点到下午2:55期间的每5分钟触发
(14)0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(15)0 0-5 14 * * ?   在每天下午2点到下午2:05期间的每1分钟触发
(16)0 10,44 14 ? 3 WED   每年三月的星期三的下午2:10和2:44触发
(17)0 15 10 ? * MON-FRI   周一至周五的上午10:15触发
(18)0 15 10 15 * ?   每月15日上午10:15触发
(19)0 15 10 L * ?   每月最后一日的上午10:15触发
(20)0 15 10 ? * 6L   每月的最后一个星期五上午10:15触发
(21)0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
(22)0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

邮件任务

步骤:

  • 邮件发送需要导入spring-boot-start-mail依赖

  • SpringBoot 自动配置MailSenderAutoConfiguration

  • 定义MailProperties内容,在application.yml中配置

  • 自动装配JavaMailSender

  • 测试邮件发送

1、导入依赖

        <!--javax.mail:配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2、查看自动配置类:MailSenderAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class)
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {

	/**
	 * Condition to trigger the creation of a {@link MailSender}. This kicks in if either
	 * the host or jndi name property is set.
	 */
	static class MailSenderCondition extends AnyNestedCondition {

		MailSenderCondition() {
			super(ConfigurationPhase.PARSE_CONFIGURATION);
		}

		@ConditionalOnProperty(prefix = "spring.mail", name = "host")
		static class HostProperty {

		}

		@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
		static class JndiNameProperty {

		}

	}

}

发现该类中并没有注册Bean,去他Import的类查看。

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Session.class)
@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
@ConditionalOnJndi
class MailSenderJndiConfiguration {

	private final MailProperties properties;

	MailSenderJndiConfiguration(MailProperties properties) {
		this.properties = properties;
	}

	@Bean
	JavaMailSenderImpl mailSender(Session session) {
		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		sender.setDefaultEncoding(this.properties.getDefaultEncoding().name());
		sender.setSession(session);
		return sender;
	}

	@Bean
	@ConditionalOnMissingBean
	Session session() {
		String jndiName = this.properties.getJndiName();
		try {
			return JndiLocatorDelegate.createDefaultResourceRefLocator().lookup(jndiName, Session.class);
		}
		catch (NamingException ex) {
			throw new IllegalStateException(String.format("Unable to find Session in JNDI location %s", jndiName), ex);
		}
	}

}

发现注册的Bean:JavaMailSenderImpl,接着查看Properties文件。

@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

	/**
	 * SMTP server host. For instance, `smtp.example.com`.
	 */
	private String host;

	/**
	 * SMTP server port.
	 */
	private Integer port;

	/**
	 * Login user of the SMTP server.
	 */
	private String username;

	/**
	 * Login password of the SMTP server.
	 */
	private String password;

	/**
	 * Protocol used by the SMTP server.
	 */
	private String protocol = "smtp";

	/**
	 * Default MimeMessage encoding.
	 */
	private Charset defaultEncoding = DEFAULT_CHARSET;

	/**
	 * Additional JavaMail Session properties.
	 */
	private Map<String, String> properties = new HashMap<>();

	/**
	 * Session JNDI name. When set, takes precedence over other Session settings.
	 */
	private String jndiName;
....

}

3、在配置文件中进行配置

spring.mail.username=1715532274@qq.com
spring.mail.password=koygokiqlbufdhbf
spring.mail.host=smtp.qq.com
# 开启加密授权验证
spring.mail.properties.mail.smtp.ssl.enable=true

获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务

测试应用

简单邮件(SMTP)以及复杂邮件(MIME)和邮件工具方法!

@SpringBootTest
class Springboot09TestApplicationTests {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {

        //一个简单的邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("你好");
        mailMessage.setText("谢谢你");

        mailMessage.setTo("1715532274@qq.com");
        mailMessage.setFrom("1715532274@qq.com");

        mailSender.send(mailMessage);

    }

    @Test
    void contextLoads1() throws MessagingException {

        //一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装MimeMessage
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");

        //正文
        helper.setSubject("你好!Mime");
        helper.setText("<p style='color:red;'>Hello</p>",true);

        //附件
        helper.addAttachment("1.jpg",new File("C:\\Users\\lenovo\\Desktop\\1.jpg"));
        helper.addAttachment("2.jpg",new File("C:\\Users\\lenovo\\Desktop\\1.jpg"));

        //发件人/收件人
        helper.setTo("1715532274@qq.com");
        helper.setFrom("1715532274@qq.com");

        mailSender.send(mimeMessage);
    }

    /**
     * 发送邮件
     * @param supMultipart boolean 是否支持多文件上传
     * @param encoding String 编码格式
     * @param subject String 邮件标题
     * @param text String 邮件内容
     * @param html boolean 邮件内容是否支持html标签
     * @param attachFilename String [] 附件名字
     * @param filepath String [] 附件路径
     * @param sender String 发送者邮箱
     * @param receiver String 接受者邮箱
     * @throws MessagingException
     * @Author Qingo
     */
    public void sendMail(Boolean supMultipart,
                         String encoding,
                         String subject,
                         String text,
                         Boolean html,
                         String [] attachFilename,
                         String [] filepath,
                         String sender,
                         String receiver) throws MessagingException {

        //一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装MimeMessage
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,supMultipart,encoding);

        //正文
        helper.setSubject(subject);
        helper.setText(text,html);

        //附件
        int length = attachFilename.length;
        for(int i=0;i<length;i++){
            helper.addAttachment(attachFilename[i],new File(filepath[i]));
        }

        //发件人/收件人
        helper.setTo(sender);
        helper.setFrom(receiver);

        mailSender.send(mimeMessage);

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值