当前位置:网站首页>Trois tâches principales: asynchrone, courrier et timing
Trois tâches principales: asynchrone, courrier et timing
2022-07-03 01:05:00 【Wangmu Sir en fuite】
Tâches asynchrones
Création
serviceSac,Créer une classe sous elleAsyncServiceLa contrefaçon traite des données,Cause thread Delay,Attente de synchronisation analogique.
package com.hxl.service; import org.springframework.stereotype.Service; @Service public class AsyncService { public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Traitement des données...."); } }Création
controllerSac,Créer une classe sous elleAsyncControllerpackage com.hxl.controller; import com.hxl.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AsyncController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello(){ asyncService.hello(); return "Pas de problème."; } }Test d'accès
http://localhost:8080/hello, La page Web attend maintenant 3 Apparaît dans quelques secondesPas de problème.Les mots de. C'est le cas de l'attente synchrone .Pour que l'expérience utilisateur soit bonne , Laissez d'abord l'utilisateur obtenir le message , Ensuite, l'arrière - plan traite les résultats en Multithreading . Il nous faut une note ,Voilà.,Springboot Il y aura un pool de Threads ,Faire un appel.
//Dis - le.SpringC'est une approche asynchrone @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Traitement des données...."); }Une annotation doit également être ajoutée au programme de démarrage principal , Activer l'annotation asynchrone
@EnableAsync //Activer la fonction d'annotation asynchrone @SpringBootApplication public class SpringbootAsyncApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAsyncApplication.class, args); } }À ce stade, le test a révélé que, La page Web s'ouvrira instantanément , Mais les données de fond continuent ,Jusqu'à la fin du traitement des données.
Tâches de courrier
Introduire des dépendances
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>Où vous pouvez voir les dépendances d'envoi de courrier associées

Voir
JavaMailSenderImplAprès avoir trouvé, Regardez le profil, c'est - à - direpropertiesEn bas, Nous pouvons voir la configuration pertinenteOui.QQ Service ouvert dans la boîte aux lettres ,Nous utilisonsIMAP/SMTPServices

Profil
[email protected] spring.mail.password=Le sien.QQCode d'autorisation spring.mail.host=smtp.qq.com spring.mail.properties.mail.smtp.ssl.enable=trueTests
package com.hxl; 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 SpringbootAsyncApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { //Un simple e - mail SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("Demain, c'est les vacances."); message.setText("Direct10De longues vacances"); message.setTo("[email protected]"); message.setFrom("[email protected]"); mailSender.send(message); } @Test public void contextLoads2() throws MessagingException { //Un message complexe MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject("Demain, c'est les vacances."); helper.setText("<b style='color:red'>À quoi penses - tu?</b>",true); //Envoyer les pièces jointes helper.addAttachment("1.jpg",new File("Chemin du fichier")); helper.addAttachment("2.jpg",new File("Par exemple,:D:\\2.jpg")); helper.setTo("[email protected]"); helper.setFrom("[email protected]"); mailSender.send(mimeMessage); } }Et vous verrez que notre email a été envoyé avec succès .
Tâches programmées
TaskExecutorInterface
TaskSchedulerInterface
Deux notes:
- @EnableScheduling //Note pour activer la fonction de synchronisation, Dans la classe de démarrage principale
- @Scheduled //Quand est - ce que
Tests
Création
ServiceSac,Créer une classeScheduledServicepackage com.hxl.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class ScheduledService { //Exécuter cette méthode à un moment donné //cronExpression //Secondes Points Heure Jour Mois Le jour de la semaine // Voici la phrase du lundi au dimanche ,De0Secondes @Scheduled(cron = "0 * * * * 0-7") public void hello(){ System.out.println("hello,Tu as été exécuté."); } }Ajouter au programme principal @EnableScheduling Activer la fonction de tâche programmée
package com.hxl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @EnableAsync //Activer la fonction d'annotation asynchrone @EnableScheduling //Note pour activer la fonction de synchronisation @SpringBootApplication public class SpringbootAsyncApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAsyncApplication.class, args); } }Et ça ira.
cronExpression
cron:https://baike.baidu.com/item/cron/10952601?fr=aladdin
cronGénération de:https://www.bejson.com/othertools/cron/
边栏推荐
- 1038 Recover the Smallest Number
- [AUTOSAR twelve mode management]
- 瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
- [flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
- [C language] branch and loop statements (Part 1)
- 用Go+绘制爱心给心爱的她表白
- leetcode-2280:表示一个折线图的最少线段数
- leetcode:701. 二叉搜索树中的插入操作【bst的插入】
- How to find out the currently running version of Solr- How do I find out version of currently running Solr?
- 递归处理组织的几种情况
猜你喜欢

Linear programming of mathematical modeling (including Matlab code)

Infrared thermography temperature detection system based on arm rk3568

【案例分享】让新时代教育发展与“数”俱进

指针初阶(基础)

tail -f 、tail -F、tailf的区别

1696C. Fishingprince Plays With Array【思维题 + 中间状态 + 优化存储】

excel IF公式判断两列是否相同

【AutoSAR 八 OS】

Leetcode-849: maximum distance to the nearest person
![[shutter] image component (configure local GIF image resources | load placeholder with local resources)](/img/73/19e2e0fc5ea6f05e34584ba40a452d.jpg)
[shutter] image component (configure local GIF image resources | load placeholder with local resources)
随机推荐
指针进阶(一)
18_微信小程序之微信视频号滚动自动播放视频效果实现2.0
Array and collection performance comparison
ROS2之ESP32简单速度消息测试(极限频率)
Leetcode-1964: find the longest effective obstacle race route to each position
1.12 - 指令
异步、邮件、定时三大任务
1696C. Fishingprince Plays With Array【思维题 + 中间状态 + 优化存储】
Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
[AUTOSAR nine c/s principle Architecture]
数学建模之线性规划(含MATLAB代码)
Basic use of sringcloud & use of component Nacos
Linear programming of mathematical modeling (including Matlab code)
Assets, vulnerabilities, threats and events of the four elements of safe operation
(C语言)数据的存储
解决ReactNative使用webView存在缓存问题
(C language) data storage
Sentry developer contribution Guide - configure pycharm
Every k nodes in the linked list are flipped
Win10 多种方式解决无法安装.Net3.5的问题