Preface (crazy God)
In our work, we often use asynchronous processing tasks. For example, when we send mail on the website, the background will send mail. At this time, the foreground will make the response motionless, and the response will not succeed until the mail is sent. Therefore, we generally use multithreading to process these tasks. There are also some scheduled tasks. For example, it is necessary to analyze the log information of the previous day in the early morning of each day. There is also the sending of e-mail. The predecessor of wechat is also an e-mail service? How do these things come true? In fact, SpringBoot provides us with corresponding support. It's very easy for us to use. We just need to open some annotation support and configure some configuration files! Let's have a look~
Asynchronous task
1. Create a service package
2. Create a class AsyncService
Asynchronous processing is still very common. For example, when we send mail on the website, the background will send mail. At this time, the foreground will make the response motionless. The response will not succeed until the mail is sent, so we generally use multithreading to process these tasks.
Writing method, pretending to be processing data, using threads to set some delays to simulate synchronous waiting;
@Service public class AsyncService { public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Business in progress...."); } }
3. Write controller package
4. Writing the AsyncController class
Let's write a Controller and test it
@RestController public class AsyncController { @Autowired AsyncService asyncService; @GetMapping("/hello") public String hello(){ asyncService.hello(); return "success"; } }
5. Visit http://localhost:8080/hello After the test, success appears after 3 seconds, which is the condition of synchronous waiting.
Problem: if we want users to get messages directly, we can use multithreading in the background, but it's too troublesome to manually write the multithreading implementation every time. We just need to use a simple method and add a simple annotation to our method, as follows:
6. Add @ Async annotation to hello method;
//Tell Spring that this is an asynchronous method @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Business in progress...."); }
SpringBoot will open a thread pool and call it! But to make this annotation effective, we also need to add an annotation @ EnableAsync on the main program to enable the asynchronous annotation function;
@EnableAsync //Enable asynchronous annotation @SpringBootApplication public class SpringbootTaskApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTaskApplication.class, args); } }
7. Restart the test, the web page responds instantly, and the background code is still executed!
Scheduled task
In project development, we often need to perform some scheduled tasks. For example, we need to analyze the log information of the previous day in the early morning of each day. Spring provides us with a way of asynchronous task scheduling and two interfaces.
-
TaskExecutor interface
-
TaskScheduler interface
Two notes:
-
@EnableScheduling
-
@Scheduled
cron expression:
Test steps:
1. Create a ScheduledService
There is a hello method in us. It needs to be executed regularly. How to deal with it?
@Service public class ScheduledService { //Second minute hour day month week //0 * * * * MON-FRI //Pay attention to the usage of cron expression; @Scheduled(cron = "0 * * * * 0-7") public void hello(){ System.out.println("hello....."); } }
2. After writing the scheduled task here, we need to add @ enableshcheduling to the main program to enable the scheduled task function
@EnableAsync //Enable asynchronous annotation @EnableScheduling //Enable annotation based scheduled tasks @SpringBootApplication public class SpringbootTaskApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTaskApplication.class, args); } }
3. Let's learn more about the cron expression;
http://www.bejson.com/othertools/cron/
4. Common expressions
(1)0/2 * * * * ? Indicates that the task is executed every 2 seconds (1)0 0/2 * * * ? Indicates that the task is executed every 2 minutes (1)0 0 2 1 * ? Indicates that the task is adjusted at 2 a.m. on the first day of each month (2)0 15 10 ? * MON-FRI It means 10 a.m. every day from Monday to Friday:15 Execute job (3)0 15 10 ? 6L 2002-2006 Indicates 2002-2006 10 a.m. on the last Friday of each month in:15 Executive work (4)0 0 10,14,16 * * ? Every day at 10 a.m., 2 p.m. and 4 p.m (5)0 0/30 9-17 * * ? Every half an hour during nine to five working hours (6)0 0 12 ? * WED It means 12 noon every Wednesday (7)0 0 12 * * ? Triggered at 12 noon every day (8)0 15 10 ? * * 10 a.m. every day:15 trigger (9)0 15 10 * * ? 10 a.m. every day:15 trigger (10)0 15 10 * * ? 10 a.m. every day:15 trigger (11)0 15 10 * * ? 2005 2005 10 a.m. every day in:15 trigger (12)0 * 14 * * ? Every day from 2 p.m. to 2 p.m:59 Triggered every 1 minute during (13)0 0/5 14 * * ? Every day from 2 p.m. to 2 p.m:55 Triggered every 5 minutes during (14)0 0/5 14,18 * * ? Every day from 2 p.m. to 2 p.m:55 During and from 6 p.m. to 6 p.m:55 Triggered every 5 minutes during (15)0 0-5 14 * * ? Every day from 2 p.m. to 2 p.m:05 Triggered every 1 minute during (16)0 10,44 14 ? 3 WED Every Wednesday in March at 2 p.m:10 And 2:44 trigger (17)0 15 10 ? * MON-FRI Monday to Friday at 10 a.m:15 trigger (18)0 15 10 15 * ? 10 a.m. on the 15th of each month:15 trigger (19)0 15 10 L * ? 10 a.m. on the last day of each month:15 trigger (20)0 15 10 ? * 6L 10 a.m. on the last Friday of each month:15 trigger (21)0 15 10 ? * 6L 2002-2005 2002 10 a.m. on the last Friday of each month from 2005 to 2005:15 trigger (22)0 15 10 ? * 6#3 triggered at 10:15 a.m. on the third Friday of each month
Mail task
Email sending is also very much in our daily development, and Springboot also supports us
Spring boot start mail needs to be introduced for mail sending
SpringBoot auto configuration MailSenderAutoConfiguration
Define the MailProperties content and configure it in application In YML
Auto assemble JavaMailSender
Test email sending
Test:
1. Introducing pom dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
Looking at the dependencies it introduces, you can see Jakarta mail
<dependency> <groupId>com.sun.mail</groupId> <artifactId>jakarta.mail</artifactId> <version>1.6.4</version> <scope>compile</scope> </dependency>
2. View auto configuration class: MailSenderAutoConfiguration
There are bean s in this class, JavaMailSenderImpl
Then let's look at the configuration file
@ConfigurationProperties( prefix = "spring.mail" ) public class MailProperties { private static final Charset DEFAULT_CHARSET; private String host; private Integer port; private String username; private String password; private String protocol = "smtp"; private Charset defaultEncoding; private Map<String, String> properties; private String jndiName; }
3. Profile:
spring.mail.username=24736743@qq.com spring.mail.password=Yours qq Authorization code spring.mail.host=smtp.qq.com
qq requires ssl configuration
spring.mail.properties.mail.smtp.ssl.enable=true
Get authorization code: set in QQ email - > account - > start pop3 and smtp services
4. Spring unit test
@Autowired JavaMailSenderImpl mailSender; @Test public void contextLoads() { //Mail setting 1: a simple mail SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("notice-Come to crazy God's class tomorrow"); message.setText("Tonight 7:30 attend a meeting"); message.setTo("24736743@qq.com"); message.setFrom("24736743@qq.com"); mailSender.send(message); } @Test public void contextLoads2() throws MessagingException { //Mail setup 2: a complex mail MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject("notice-Come to crazy God's class tomorrow"); helper.setText("<b style='color:red'>Today 7:30 Come to the meeting</b>",true); //Send attachments helper.addAttachment("1.jpg",new File("")); helper.addAttachment("2.jpg",new File("")); helper.setTo("24736743@qq.com"); helper.setFrom("24736743@qq.com"); mailSender.send(mimeMessage); }