当前位置:网站首页>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
service
Sac,Créer une classe sous elleAsyncService
La 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
controller
Sac,Créer une classe sous elleAsyncController
package 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
JavaMailSenderImpl
Après avoir trouvé, Regardez le profil, c'est - à - direproperties
En 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=true
Tests
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
Service
Sac,Créer une classeScheduledService
package 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/
边栏推荐
猜你喜欢
Illustrated network: what is virtual router redundancy protocol VRRP?
Hdu3507 (slope DP entry)
12_微信小程序之微信视频号滚动自动播放视频效果实现
How to systematically learn machine learning
leetcode-2280:表示一个折线图的最少线段数
The difference between tail -f, tail -f and tail
AEM: Nanlin fan Ben et al. - plant rhizosphere growth promoting bacteria control soybean blight
Understanding and distinguishing of some noun concepts in adjustment / filtering
【AutoSAR 十 IO架构】
1696C. Fishingprince Plays With Array【思维题 + 中间状态 + 优化存储】
随机推荐
世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
链表中的节点每k个一组翻转
Win10 can't be installed in many ways Problems with NET3.5
Cordova plugin device obtains the device information plug-in, which causes Huawei to fail the audit
Linear programming of mathematical modeling (including Matlab code)
这不平凡的两年,感谢我们一直在一起!
Basic use of sringcloud & use of component Nacos
Assets, vulnerabilities, threats and events of the four elements of safe operation
[AUTOSAR XIII NVM]
Vulkan performance and refinement
全志A40i/T3如何通过SPI转CAN
【AutoSAR 五 方法论】
The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
【AutoSAR 十二 模式管理】
2022.2.14 resumption
Leetcode-934: the shortest Bridge
【AutoSAR 四 BSW概述】
基于ARM RK3568的红外热成像体温检测系统
leetcode-849:到最近的人的最大距离
Lex & yacc & bison & flex configuration problems