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

💗wei_shuo的个人主页

💫wei_shuo的学习社区

🌐Hello World !


任务

异步任务

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

  • service/AsyncService.java
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
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启动类配置注解
java 复制代码
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);
    }
    
}

邮件任务

  • 导入依赖
xml 复制代码
     <!--javax.mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • application.properties
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测试
java 复制代码
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
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
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,你被执行了......");
    }
}

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


相关推荐
野犬寒鸦30 分钟前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode
ytadpole1 小时前
揭秘设计模式:工厂模式的五级进化之路
java·设计模式
计算机毕业设计木哥1 小时前
计算机毕设选题:基于Python+Django的B站数据分析系统的设计与实现【源码+文档+调试】
java·开发语言·后端·python·spark·django·课程设计
失散131 小时前
分布式专题——1.2 Redis7核心数据结构
java·数据结构·redis·分布式·架构
用户3721574261352 小时前
Python 实现 HTML 转 Word 和 PDF
java
a587692 小时前
Java核心概念精讲:TCP与UDP的区别、Java NIO的几个核心组件与HTTP和HTTPS的区别等(46-50)
java·面试·nio
渣哥2 小时前
ConcurrentHashMap 的 get 要不要加锁?一次“多此一举”的心路历程
java
愿你天黑有灯下雨有伞2 小时前
一种基于注解与AOP的Spring Boot接口限流防刷方案
java·spring boot·后端
MuMuMu#2 小时前
JAVA NIO学习笔记基础强化学习总结
java·学习·nio
拾忆,想起2 小时前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化