当前位置:网站首页>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/
边栏推荐
- 【AutoSAR 十三 NVM】
- Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
- 研发一款国产ARM智能边缘计算网关需要什么
- leetcode:701. 二叉搜索树中的插入操作【bst的插入】
- Hdu3507 (slope DP entry)
- What is needed to develop a domestic arm intelligent edge computing gateway
- Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
- Leetcode-1964: find the longest effective obstacle race route to each position
- 拥抱平台化交付的安全理念
- Foundations of data science is free to download
猜你喜欢

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

matlab将数字矩阵保存为地理空间数据出错,显示下标索引必须为正整数类型或逻辑类型,解决

安全运营四要素之资产、脆弱性、威胁和事件

Test shift right: Elk practice of online quality monitoring

excel表格计算时间日期的差值,并转化为分钟数

Illustrated network: what is virtual router redundancy protocol VRRP?

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

【AutoSAR 一 概述】

测试右移:线上质量监控 ELK 实战
![[applet project development -- JD mall] user defined search component of uni app (middle) -- search suggestions](/img/ea/ee1ad50a497478b9d080bb5e4bdfb5.png)
[applet project development -- JD mall] user defined search component of uni app (middle) -- search suggestions
随机推荐
删除有序链表中重复的元素-II
Understanding and distinguishing of some noun concepts in adjustment / filtering
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
1.12 - Instructions
电话网络问题
leetcode-849:到最近的人的最大距离
How to systematically learn machine learning
leetcode:701. 二叉搜索树中的插入操作【bst的插入】
[AUTOSAR II appl overview]
2022.2.14 resumption
leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
【C语言】分支和循环语句(上)
瑞萨电子RZ/G2L开发板上手评测
飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
Is there a free text to speech tool to help recommend?
Sentry developer contribution Guide - configure pycharm
1.12 - 指令
Leetcode-241: designing priorities for operational expressions
MySQL multi table joint deletion
Explain the basic concepts and five attributes of RDD in detail