SpringBoot篇——异步任务、邮件任务和定时任务,超详细!超细节!

异步任务

常规情况下,我们模拟一个线程休眠,延时3秒,那么前端获取到信息也会延时3秒,这是很影响用户体验的,因此,异步任务的出现,有效的解决了这个问题
一异步任务:即便是出现线程休眠,也会让前端立即获取到显示数据,后台按照原定的休眠状态加载即可,不影响用户体验

springboot中实现异步任务的方法:
1、首先先写一个异步的业务,在有延时的方法上面加上一个注解@Asyn,声明这是一个异步的任务

@Service
public class AsyncService {
    //这个注解功能是告诉spring这是一个异步的任务
    @Async
    public void hello() throws InterruptedException {
        //线程休眠3秒
        Thread.sleep(Long.parseLong("3000"));
        System.out.println("数据正在加载!");
    }
}

2、编写ciontroller控制类

@RestController
public class AsyncController {
    //调用业务层,将业务层的类装配进来
    @Autowired
    private AsyncService asyncService;

    //调用业务层的方法
    @RequestMapping("/hello")
    public String getHello() throws InterruptedException {
        asyncService.hello();//调用这个方法,会延时3秒,会造成前台的数据显示延时3秒
        return "hello出来了";
    }
}

3、启动主程序,在主程序上开启异步任务的功能,用到注解@EnableAsync (拓展:凡是在SpringBoot中开启某个功能都用Enable)

@EnableAsync //开启异步注解功能
@SpringBootApplication
public class SpringbootTestApplication {

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

效果和总结:
当我们访问这个接口,页面会立即显示出”hello出来了“,而后端会延时3秒执行hello方法

邮件任务

一、SpringBoot实现邮件任务,先导入启动器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>3.0.4</version>
</dependency>

二、在application.properties配置文件中配置邮件发送
当前是以QQ邮箱为例子

#配置发件人邮箱用户名和授权码
spring.mail.username=24456299@qq.com
#这是QQ邮箱专门生成的,为了隐藏密码
spring.mail.password=lbmqgldutvloecae
#配置发送的服务器
spring.mail.host=smtp.qq.com
#开启QQ邮箱的SSL加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

三、首先要了解到SpringBoot给我们提供了一个JavaMailSenderImpl实现类可以操作邮件发送等功能

四、直接进测试类测试
1、简单的邮件

@SpringBootTest
class SpringbootTestApplicationTests {
    //想要在某个类中实现邮件发送的功能,首先需要将java中提供的实现类使用@Autowired注解注入进当前的类中
    @Autowired
     JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        //一个简单的邮件发送功能
        SimpleMailMessage message = new SimpleMailMessage();
        //收件的标题
        message.setSubject("北京欢迎你!");
        //邮件内容
        message.setText("你好,我亲爱的朋友!");
        //指明邮件的发件人和接收人
        message.setTo("2445629679@qq.com");
        message.setFrom("2445629679@qq.com");

        mailSender.send(message);
    }
}

2、较复杂的邮件

@SpringBootTest
class SpringbootTestApplicationTests {
    //想要在某个类中实现邮件发送的功能,首先需要将java中提供的实现类使用@Autowired注解注入进当前的类中
    @Autowired
     JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() throws MessagingException {
        //一个复杂的邮件发送功能
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        //正文
        helper.setSubject("你好呀,我是标题!");
        //正文部分可以选择直接解析html
        helper.setText("<p style='color:red'>北京欢迎你</p>",true);

        //添加附件
        helper.addAttachment("1.jpg",new File("C:\\XXX"));

        //指明邮件的发件人和接收人
        helper.setTo("2445629679@qq.com");
        helper.setFrom("2445629679@qq.com");

        mailSender.send(mimeMessage);
    }
}

定时任务

一、了解定时任务涉及的两个接口和注解
1、Spring帮我们封装好的两个接口
TaskScheduler:任务调度者
TaskExecutor:任务执行者

2、注解
(1)@EnableXXX 一般是放在启动程序上

@EnableScheduling //开启定时任务的注解

(2)@Scheduled:用在方法上,表示该方法多久执行一次

@Scheduled(cron = "0 52 15 * * ? ") //表示每天的15点52分0秒执行这个方法

二、具体的使用方法

//定时任务的业务
@Service
public class ScheduledService {

    //在特定的时间执行这个方法,用到这个@Scheduled注解
    //需要传一个cron(计划任务,在约定好的时间执行已经计划好的工作)表达式
    //秒 分 时 日 月 周几(周一~周日)
    @Scheduled(cron = "0 52 15 * * ? ") //表示每天的15点52分0秒执行这个方法
    public void hello() {
        System.out.println("Hello,你被执行了!!!");
    }
}

三、想要去了解cron表达式,直接可以百度,知道怎么使用即可

至此,关于SpringBoot中的各种任务你已经完全的掌握了,后续还会持续更新,敬请期待!

Spring Boot中,@EnableScheduling注解用于开启定时任务功能。它可以被用于配置类中,通常与@Configuration一起使用。该注解会自动扫描带有@Scheduled注解的方法,并将其设置为定时任务。通过在启动类上添加@EnableScheduling注解,我们可以启用定时任务功能。例如,在启动类MainApplication中添加@EnableScheduling注解,就可以开启定时任务功能。同时,我们还可以自定义线程池以及使用@Async@EnableAsync注解来实现多线程间的异步调用。有关Spring Boot定时任务的更多信息,可以参考SpringBoot的官方文档或者相关的技术文章。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Spring 中 @EnableScheduling 实现 定时任务](https://blog.youkuaiyun.com/liuming690452074/article/details/124764904)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [SpringBoot 注解@EnableScheduling定时任务详解](https://blog.youkuaiyun.com/qq_43649223/article/details/120437949)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java多线程之定时任务 以及 SpringBoot多线程实现定时任务——异步任务](https://download.youkuaiyun.com/download/suixinfeixiangfei/84560169)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Be explorer

若认可笔者文章,手头富裕望支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值