二十三、 SpringBoot之任务(异步、定时、邮件)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29479041/article/details/83384185

一、异步任务

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

两个注解:@EnableAysnc、@Aysnc

  • Service
@Service
public class AsyncService {
    //告诉Spring这是一个异步方法
    @Async
    public void hello(){
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据处理中。。。。");
    }
}
  • Controller
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "success";
    }
}
  • Application
@EnableAsync  //开启异步注解功能
@SpringBootApplication
public class SpringBootTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTaskApplication.class, args);
    }
}

二、定时任务

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

两个注解:@EnableScheduling、@Scheduled

  • cron表达式

字段

允许值

允许的特殊字符

0-59

,-*/

0-59

,-*/

小时

0-23

,-*/

日期

1-31

,-*?/LWC

月份

1-12

,-*/

星期

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

,-*?/LC#

  • 特殊字符

特殊字符

代表含义

,

枚举

-

区间

*

任意

/

步长

?

日/星期冲突匹配

L

最后

W

工作日

C

和calendar联系后计算过的值

#

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

  • service
@Service
public class ScheduledService {
    /**
     * 定时任务
     * cron 指定定时任务的cron表达式
     * second(秒),minute(分),hour(时),day of month(日),month(月),day of week(周几)
     * 0 * * * * MON-FRI (周一到周五每一分钟整分钟的时候运行一次)
     */
    //@Scheduled(cron = "0 * * * * MON-FRI")
    //@Scheduled(cron = "0,1,2,3,4 * * * * MON-FRI")  //0,1,2,3,4枚举
    //@Scheduled(cron = "0-4 * * * * MON-FRI")    //0-4秒区间
    //@Scheduled(cron = "0/4 * * * * MON-FRI")    //每4秒一次
    //@Scheduled(cron = "0 0/5 14,18 * * ?")    //每天14点整和18点整,每隔5分钟执行一次
    //@Scheduled(cron = "0 15 10 ? * 1-6")  //每个月点周一至周六10:15分执行一次
    //@Scheduled(cron = "0 0 2 ? * 6L")  //每个月的最后一个周六凌晨2点执行一次
    //@Scheduled(cron = "0 0 2 LW * ?")  //每个月的最后一个工作日凌晨两点执行一次
    @Scheduled(cron = "0 0 2-4 ? * 1#1")  //每个月的第一个周一凌晨2点到4点期间每个整点都执行一次
    public void hello() {
        System.out.println("hello...");
    }
}
  • Application
@EnableScheduling  //开启基于注解的定时任务
@SpringBootApplication
public class SpringBootTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTaskApplication.class, args);
    }
}

三、邮件任务

1、步骤:

  • 邮件发送需要引入spring-boot-starter-mail
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 定义MailProperties内容,配置在application.yml中
[email protected]
spring.mail.password=mpduxmuivewdigjf
spring.mail.host=smtp.qq.com
  • 测试邮件发送
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTaskApplicationTests {
    //注入邮件发送器
    @Autowired
    JavaMailSenderImpl javaMailSender;

    //测试简单邮件
    @Test
    public void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件设置
        message.setSubject("通知:今晚开会");
        message.setText("今晚7:30开会");
        message.setTo("[email protected]");
        message.setFrom("[email protected]");
        javaMailSender.send(message);
    }


    //测试复杂邮件
    @Test
    public void test() throws MessagingException {
        //1、创建一个复杂消息邮件
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);//multipart 是否上传文件
        //邮件设置
        helper.setSubject("通知:今晚开会");
        helper.setText("<b style='color:red'>今晚7:30开会</b>", true);
        helper.setTo("[email protected]");
        helper.setFrom("[email protected]");

        //上传附件
        helper.addAttachment("1.jpg", new File("/Users/Amy/Downloads/1.jpg"));
        helper.addAttachment("2.jpg", new File("/Users/Amy/Downloads/2.jpg"));
        javaMailSender.send(message);
    }
}

2、原理:

  • Spring Boot 自动配置MailSenderAutoConfiguration
//邮件自动配置类
@Configuration
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class)
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {
//邮件发送属性
@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {
  • 自动装配JavaMailSender
@Configuration
@ConditionalOnClass(Session.class)
@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
@ConditionalOnJndi
class MailSenderJndiConfiguration {

	private final MailProperties properties;

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

	@Bean //发送邮件的组件
	public JavaMailSenderImpl mailSender(Session session) {
		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		sender.setDefaultEncoding(this.properties.getDefaultEncoding().name());
		sender.setSession(session);
		return sender;
	}

猜你喜欢

转载自blog.csdn.net/qq_29479041/article/details/83384185