当前位置:网站首页>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/
边栏推荐
- 瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
- RK3568开发板评测篇(二):开发环境搭建
- 【AutoSAR 五 方法论】
- 【AutoSAR 十三 NVM】
- 1696C. Fishingprince Plays With Array【思维题 + 中间状态 + 优化存储】
- [AUTOSAR eight OS]
- leetcode-1964:找出到每个位置为止最长的有效障碍赛跑路线
- Leetcode-241: designing priorities for operational expressions
- Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
- Win10 can't be installed in many ways Problems with NET3.5
猜你喜欢

Is there a free text to speech tool to help recommend?

世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力

1.12 - Instructions

异步、邮件、定时三大任务
![[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)

【AutoSAR 十二 模式管理】

leetcode-2280:表示一个折线图的最少线段数

Win10 can't be installed in many ways Problems with NET3.5

leetcode-849:到最近的人的最大距离

Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
随机推荐
Arduino开发之按键检测与正弦信号输出
数学建模之线性规划(含MATLAB代码)
leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
电话网络问题
1696C. Fishingprince Plays With Array【思维题 + 中间状态 + 优化存储】
Linear programming of mathematical modeling (including Matlab code)
[AUTOSAR I overview]
【AutoSAR 十三 NVM】
Solve the cache problem of reactnative using WebView
[C language] branch and loop statements (Part 1)
ROS2之ESP32简单速度消息测试(极限频率)
[AUTOSAR eight OS]
FPGA - 7 Series FPGA internal structure clocking -04- multi area clock
Vulkan practice first bullet
瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南
1.12 - Instructions
Problèmes de configuration lex & yacc & Bison & Flex
mysql 多表联合删除
删除有序链表中重复的元素-II
这不平凡的两年,感谢我们一直在一起!