SpringBoot(十七)——————异步任务、定时任务、邮件任务

源码地址:https://github.com/877148107/springboot_integrate/tree/master/springboot-integrate-task

 

目录

异步任务

定时任务

1、cron表达式

 邮件任务

1、引入发送邮件的starter

2、自动配置类MailSenderAutoConfiguration 

3、邮件发送的组件JavaMailSenderImpl

4、邮件发送的属性配置MailProperties

5、测试邮件发送


 

  • 异步任务

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。

两个注解:

@EnableAysnc:开启异步处理

@EnableAsync
@SpringBootApplication
public class SpringbootIntegrateTaskApplication {

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

}

@Aysnc:标识为异步进行

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String sayHello(){
        asyncService.sayHello();
        return LocalDateTime.now()+"hello AsyncService。。。。。。";
    }
}
  • 定时任务

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

两个注解:

@EnableScheduling:开启定时任务

@EnableScheduling
@SpringBootApplication
public class SpringbootIntegrateTaskApplication {

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

}

@Scheduled:定时任务执行

@Service
public class ScheduledService {
    /**
     * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
     * 0 * * * * MON-FRI
     *  【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
     *  【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
     *  【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
     *  【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
     *  【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
     */
    // @Scheduled(cron = "0 * * * * MON-SAT")
    //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
    // @Scheduled(cron = "0-4 * * * * MON-SAT")
    @Scheduled(cron = "0/4 * * * * 0-7")  //每4秒执行一次
    public void hello(){
        System.out.println("hello ... ");
    }
}

1、cron表达式

字段

允许值

允许的特殊字符

 

特殊字符

代表含义

0-59

, - * /

 

,

枚举

0-59

, - * /

 

-

区间

小时

0-23

, - * /

 

*

任意

日期

1-31

, - * ? / L W C

 

/

步长

月份

1-12

, - * /

 

?

日/星期冲突匹配

星期

0-7或SUN-SAT 0,7是SUN

, - * ? / L C #

 

L

最后

    

W

工作日

    

C

和calendar联系后计算过的值

    

#

星期,4#2,第2个星期四

 

 

 

 

 

 

 

 

 

 

  •  邮件任务

1、引入发送邮件的starter

<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 {

3、邮件发送的组件JavaMailSenderImpl

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.mail", name = "host")
class MailSenderPropertiesConfiguration {

	@Bean
	@ConditionalOnMissingBean(JavaMailSender.class)
	JavaMailSenderImpl mailSender(MailProperties properties) {
		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		applyProperties(properties, sender);
		return sender;
	}

4、邮件发送的属性配置MailProperties

@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;
#配置邮箱地址
spring.mail.username=123456@qq.com
#配置邮箱密码
spring.mail.password=123456
#配置邮箱的host
spring.mail.host=smtp.qq.com

5、测试邮件发送

@SpringBootTest
class SpringbootIntegrateTaskApplicationTests {

    @Autowired
    JavaMailSender mailSender;

    /**
     * 测试发送邮件
     */
    @Test
    void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        //主题
        message.setSubject("放假通知");
        //内容
        message.setText("4月4、5、6放假三天");

        //发送给谁
        message.setTo("123456@126.com");
        //从谁发送
        message.setFrom("123456@qq.com");

        mailSender.send(message);
    }


    /**
     * 测试发送复杂邮件
     */
    @Test
    public void testSendEmail() throws Exception{
        //创建一个复杂的消息邮件
        MimeMessage mailMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mailMessage,true);


        //主题
        helper.setSubject("放假通知");
        //内容
        helper.setText("<h1 style='color:red'>4月4、5、6放假三天</h1>",true);

        //发送给谁
        helper.setTo("123456@126.com");
        //从谁发送
        helper.setFrom("123456@qq.com");

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

        mailSender.send(mailMessage);
    }

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值