SpringBoot原理分析 | 任务:异步、邮件、定时

简介: SpringBoot原理分析 | 任务:异步、邮件、定时


任务

异步任务

Java异步指的是在程序执行过程中,某些任务可以在后台进行,而不会阻塞程序的执行。通常情况下,Java异步使用线程池来实现,将任务放入线程池中,等待线程池中的线程执行这些任务。Java异步可以提高程序的性能和并发能力,尤其是在处理IO密集型任务时,可以大大减少等待时间,提高程序的响应速度。常见的Java异步实现方式包括Future、CompletableFuture、RxJava等

  • service/AsyncService.java
package com.wei.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
 * @ClassName AsyncService
 * @Description TODO
 * @Author wei_shuo
 * @Date 2023/5/9 18:30
 * @Version 1.0
 */
@Service
public class AsyncService {
    //告诉Spring这是异步方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理……");
    }
}
  • controller/AsyncController.java
package com.wei.controller;
import com.wei.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @ClassName AsyncController
 * @Description TODO
 * @Author wei_shuo
 * @Date 2023/5/9 18:33
 * @Version 1.0
 */
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;
    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "OK";
    }
}
  • SpringbootTestApplication启动类配置注解
package com.wei;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
//开启异步注解功能
@EnableAsync
public class SpringbootTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootTestApplication.class, args);
    }
}

邮件任务

  • 导入依赖
<!--javax.mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • application.properties
spring.mail.username=1096075493@qq.com
spring.mail.password=cjkglgqynqwabaed
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
  • Test测试
package com.wei;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootTestApplicationTests {
    @Autowired(required=false)
    JavaMailSenderImpl javaMailSender;
    //简单邮件
    @Test
    void contextLoads() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //主题
        mailMessage.setSubject("wei_shuo");
        //内容
        mailMessage.setText("Hello,World!");
        mailMessage.setFrom("1096075493@qq.com");
        mailMessage.setTo("1096075493@qq.com");
        javaMailSender.send(mailMessage);
    }
    //复杂邮件
    @Test
    void contextLoads2() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setSubject("wei_shuo-plus");
        helper.setText("<p style='color:red'>Hello,World-Plus</p>",true);
        //附件
        helper.addAttachment("1.jpg",new File("C:\\Users\\ws199\\Desktop"));
        helper.setFrom("1096075493@qq.com");
        helper.setTo("1096075493@qq.com");
        javaMailSender.send(mimeMessage);
    }
    /**
     *
     * @param html
     * @param subject
     * @param text
     * @throws MessagingException
     */
    //封装方法
    public void sendMail(Boolean html,String subject,String text) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,html);
        helper.setSubject(subject);
        helper.setText(text,true);
        //附件
        helper.addAttachment("1.jpg",new File("C:\\Users\\ws199\\Desktop"));
        helper.setFrom("1096075493@qq.com");
        helper.setTo("1096075493@qq.com");
        javaMailSender.send(mimeMessage);
    }
}

定时任务

  • SpringbootTestApplication.java
package com.wei;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
//开启异步注解功能
@EnableAsync
//开启定时功能的注解
@EnableScheduling
public class SpringbootTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootTestApplication.class, args);
    }
}
  • ScheduledService.java
package com.wei.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
 * @ClassName ScheduledService
 * @Description TODO
 * @Author wei_shuo
 * @Date 2023/5/10 18:23
 * @Version 1.0
 */
@Service
public class ScheduledService {
    //固定时间,执行代码
    @Scheduled(cron = "0/2 * * * * *")
    public void hello(){
        System.out.println("Hello,你被执行了……");
    }
}

🌼 结语:创作不易,如果觉得博主的文章赏心悦目,还请——点赞👍收藏⭐️评论📝


目录
相关文章
|
1月前
|
Java 应用服务中间件 开发者
Java面试题:解释Spring Boot的优势及其自动配置原理
Java面试题:解释Spring Boot的优势及其自动配置原理
87 0
|
22天前
|
Java Spring 容器
Spring Boot 启动源码解析结合Spring Bean生命周期分析
Spring Boot 启动源码解析结合Spring Bean生命周期分析
59 11
|
22天前
|
Java Spring 容器
Spring boot 自定义ThreadPoolTaskExecutor 线程池并进行异步操作
Spring boot 自定义ThreadPoolTaskExecutor 线程池并进行异步操作
46 3
|
22天前
|
SQL Java 数据库连接
springboot~mybatis-pagehelper原理与使用
【7月更文挑战第15天】MyBatis-PageHelper是用于MyBatis的分页插件,基于MyBatis的拦截器机制实现。它通过在SQL执行前动态修改SQL语句添加LIMIT子句以支持分页。使用时需在`pom.xml`添加依赖并配置方言等参数。示例代码: PageHelper.startPage(2, 10); List&lt;User&gt; users = userMapper.getAllUsers(); PageInfo&lt;User&gt; pageInfo = new PageInfo&lt;&gt;(users); 这使得分页查询变得简单且能获取总记录数等信息。
|
5天前
|
Java 数据安全/隐私保护
SpringBoot 自定义初始化任务 Runner
SpringBoot 自定义初始化任务 Runner
4 0
|
1月前
|
SQL Java 调度
实时计算 Flink版产品使用问题之使用Spring Boot启动Flink处理任务时,使用Spring Boot的@Scheduled注解进行定时任务调度,出现内存占用过高,该怎么办
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
|
1月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的邮件过滤系统的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的邮件过滤系统的详细设计和实现(源码+lw+部署文档+讲解等)
|
22天前
|
前端开发 Java 应用服务中间件
SpringBoot异步接口怎么实现?
### 前言 Servlet 3.0以前,每个HTTP请求由单一线程全程处理;3.0版本引入异步处理,允许提前释放容器线程,提升系统吞吐量。
|
1月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的邮件过滤系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的邮件过滤系统附带文章源码部署视频讲解等
22 0
|
1月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue的高质量升学分析系统的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue的高质量升学分析系统的详细设计和实现(源码+lw+部署文档+讲解等)
22 0