introduction
Dans le traitement des affaires, certaines entreprises utilisent des méthodes asynchrones plus raisonnables. Par exemple, dans une certaine logique métier, certaines données sont stockées dans le cache Redis. Le cache n'est qu'une fonction auxiliaire. Le succès ou l'échec n'aura pas d'impact fondamental sur l'activité principale. Ce processus peut être effectué via une méthode asynchrone.
Au printemps, la méthode peut être appelée de manière asynchrone en définissant l'annotation @async sur la méthode. C'est-à-dire que la méthode reviendra immédiatement lors de l'invocation, et l'exécution réelle de cette méthode est remise au taskexecutor de Spring.
Exemple de code
Le projet est un projet de printemps normal, Spring Configuration Fichier:
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: task = "http://www.springframework.org/schema/task" xsi: schemalocation = "http://www.springfrramework.org/schema/Beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd "> <! Base-Package = "com.lzumetal.ssm" /> <! - Pool de thread pour exécuter des tâches asynchrones taskexecutor -> <tâche: exécutor id = "myexecutor" pool-size = "5" /> <tâche: annotation-drive exécutor = "myexecutor" /> </ beeps>
Deux cours de service:
package com.lzumetal.ssm.anotation.service; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.sterEotype.service; Importer java.util.concurrent.Expection; Service; Import java.util.concurrent.future; / ** * Service commercial * / @ ServicePublic Class BusinessService {private static final logger log = loggerfactory.getLogger (businesservice.class); @Autowired Private Cacheservice Cacheservice; public void dobusiness () {Log.Error ("commencer à traiter avec notre entreprise"); cacheservice.cachedata (); Log.Error ("Comlete Service Operation"); } / ** * Obtenez la valeur de retour pour la méthode asynchrone Exécution * / public void dobusiness withasyncreturn () lève ExecutionException, InterruptedException {Log.Error ("Commencez à traiter avec notre entreprise"); Future <string> futur = cacheService.Cachedatawithreturn (); Log.Error (futur.get ()); //future.get () est un Log.Error de blocage ("Comlete Service Operation"); }} package com.lzumetal.ssm.anotation.service; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.scheling.annotation.asynccrèse; org.springframework.sterreotype.service; import java.util.concurrent.future; import java.util.concurrent.timeunit; / ** * service de cache * / @ servicepublic class cacheservice {private static final logger log = loggerfactory.getLogger (cacheservice.class static); @Async (value = "myexecutor") // spécifiez le taskexecutor pour exécuter la tâche publique void cachedata () {try {timeunit.seconds.sleep (3l); } catch (InterruptedException e) {e.printStackTrace (); } log.Error ("Success Stocker le résultat au cache"); } @Async Public Future <string> cachedatawithreturn () {try {timeunit.seconds.sleep (3l); } catch (InterruptedException e) {e.printStackTrace (); } log.Error ("Success Stocker le résultat au cache"); // Le résultat renvoyé doit être enveloppé par la classe AsynCresult Retourne New AsynCresult <> ("Async Operation Success"); }}Classe de test:
package com.lzumetal.ssm.anotation.test; import com.lzumetal.ssm.anotation.service.businessservice; import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowired; import org.springframework.test.context.contextConfiguration; import org.springframework.test.context.junit4 {"ClassPath: Spring-Context.xml"}) Classe publique MainTest {@Autowired Private BusinessService BusinessService; @Test Public Void test () lève InterruptedException {BusinessVice.Dobusiness (); // Ne laissez pas le thread principal se terminer trop tôt, sinon la console ne verra pas le contenu de sortie dans la méthode asynchrone timeUnit.seconds.sleed (5L); } @Test public void testasyncreturn () lève une exception {businesservice.dobusinesswithasyncreturn (); TimeUnit.seconds.Sleep (5L); }}Le résultat de l'exécution de la méthode Test ():
22: 20: 33,207 Info Main Support.DefaultTestContextBootSstrapper: 260 - Noms de classe TestExECUTURSEner par défaut de défaut à partir de l'emplacement [meta-inf / printemps.factories]: [org.springframework.test.context.web.servlettestexecutionListener, org.springframework.test.context.support.DirtiesContextBeForModeSesTexecutionListener, org.springframework.test.context.support.test.contextestexecutionListener, org.springframework.test.context.support.DirtiesContextTestSecutionListener, org.springframework.test.context.transaction.transactionaltestExecutionListener, org.springframework.test.context.jdbc.sqlscriptSteStexecutionListener]
22: 20: 33,226 Info Main Support.DefaultTestContextbootSstrapper: 209 - n'a pas pu instancier TestExecutionListener [org.springframework.test.context.web.servlettesExecutionListener]. Spécifiez les classes d'écoute personnalisées ou rendez les classes d'écoute par défaut (et leurs dépendances requises) disponibles. Classe d'offense: [Javax / Servlet / ServletContext]
22: 20: 33,227 info principal org.springframework.test.context.support.dependencyInjectionTestexEcutionListener@643b1d11, org.springframework.test.context.support.DirtiesContexTestexecutionListener@2ef5e5e3, org.springframework.test.context.transaction.transactionaltestexecutionListener@36d4b5c, org.springframework.test.context.jdbc. Définitions de bean xml à partir de la ressource du chemin de classe [printemps-context.xml]
22: 20: 33 585 INFO PRINCIPAL PRESSION.GENERICAPPLICATIONCONTTEXT: 583 - Rafraîchissement org.springframework.context.support.genericApplicationContext@4f7d0008: Date de démarrage [Mer May 30 22:20:33 CST 2018]; Racine de la hiérarchie du contexte
22: 20: 33 763 infos principaux concurrent.
22: 20: 33 766 INFO PRINCIPAL SUPPRIANCE.POSTPROCESSORRÉGRÉGRENTIFICATIONSDELEGATE $ BeanPostProcessorchecker: 325 - Bean 'MyExecUtor' de type [org.springframework.Scheduling.Config.taskexecutorfactoryBean] n'est pas éligible pour obtenir un traitement par tous les haricots auto-proxying)
22: 20: 33 767 INFO PRINCIPAL SUPPRIANCE.POSTPROCESSORRÉGRÉGRENTIFICATIONSDELEGATE $ BeanPostProcessorChecker: 325 - Bean 'MyExecUtor' de Type [org.SpringFramework.Scheduling.Concurrent.ThreadpoolTasKexECUTOR] n'est pas éligible pour être traité par All BeanPostProcessors (pour EXCIBLE pour être éligible pour être traité par All BeanPostProcessors (pour EXCIBLE pour être éligible pour être traité par All BeanPostProcessors (pour EXIGUBLE pour être éligible pour être traité par All BeanPostProcessors (pour EXIGIBL auto-proxying)
22: 20: 34,107 Error Service principal. BusinessService: 24 - Commencez à traiter avec notre entreprise
22: 20: 34,113 Error Service principal.
22: 20: 37,166 Erreur MyExecUtor-1 Service.Cacheservice: 28 - Success Store the Result to Cache
22: 20: 39,117 Info Thread-0 Support.GenericApplicationContext: 984 - Clôture org.springframework.context.support.genericApplicationContext@4f7d0008: Date de démarrage [Mer May 30 22:20:33 CST 2018]; Racine de la hiérarchie du contexte
22: 20: 39,118 Info Thread-0 simultante.threadpooltaskexecutor: 203 - Arrêt
Le résultat de l'exécution de la méthode TestAsynCreturn ():
21: 38: 16 908 Info Main Support.DefaultTestContextBootSstrapper: 260 - Noms de classe TestExecutionListener chargés de défaut à partir de l'emplacement [meta-inf / printemps.factories]: [org.springframework.test.context.web.servlettestexecutionListener, org.springframework.test.context.support.DirtiesContextBeForModeSesTexecutionListener, org.springframework.test.context.support.test.contextestexecutionListener, org.springframework.test.context.support.DirtiesContextTestSecutionListener, org.springframework.test.context.transaction.transactionaltestExecutionListener, org.springframework.test.context.jdbc.sqlscriptSteStexecutionListener]
21: 38: 16 926 INFO PRINCIPAL PRÉPADENCE.DEFAULTTESTCONTEXTBOOTSTTPAPPER: 209 - n'a pas pu instancier TestExecutionListener [org.springframework.test.context.web.servlettesExecutionListener]. Spécifiez les classes d'écoute personnalisées ou rendez les classes d'écoute par défaut (et leurs dépendances requises) disponibles. Classe d'offense: [Javax / Servlet / ServletContext]
21: 38: 16 927 info principale support.DefaultTestContextbootstrapperpapper: 187 - Utilisation de TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeLoDestesStexecutionListener@100fc185, org.springframework.test.context.support.dependencyInjectionTestexEcutionListener@643b1d11, org.springframework.test.context.support.DirtiesContexTestexecutionListener@2ef5e5e3, org.springframework.test.context.transaction.transactionaltestexecutionListener@36d4b5c, org.springframework.test.context.jdbc. Définitions de bean xml à partir de la ressource du chemin de classe [printemps-context.xml]
21: 38: 17,263 INFO PRINCIPAL PRESSION.GENERICAPPLICATIONCONTTEXT: 583 - Rafraîchissement org.springframework.context.support.genericApplicationContext@4f7d0008: Date de démarrage [Mer 30 mai 21:38:17 CST 2018]; Racine de la hiérarchie du contexte
21: 38: 17 405 infos principale concurrent.ThreadpoolTasKexecutor: 165 - Initialisation de l'exécution
21: 38: 17 407 Info Principale support.PostProcessorRegistrationDelegate $ beanPostProcessorchecker: 325 - bean 'myexecutor' of type [org.springframework.scheduling.config.taskexecutorfactorybean] n'est pas éligible pour obtenir un traitement par tous les haricots auto-proxying)
21: 38: 17 407 Info Principale support.PostProcessorRegistrationDelegate $ beanPostProcessorChecker: 325 - bean 'myexecutor' of type [org.springframework.Scheduling.Concurrent.ThreadpooltasKexECUTOR] n'est pas éligible pour se procéder par tous auto-proxying)
21: 38: 17 692 Error Service principal. BusinessService: 35 - Commencez à traiter avec notre entreprise
21: 38: 20 833 ERREUR MYEXECUTOR-1 Service.Cacheservice: 39 - Success Store Le résultat pour cache
21: 38: 20 834 Error Service principal.
21: 38: 20 835 Error Service principal.
21: 38: 25 838 Info Thread-0 Support.GenericApplicationContext: 984 - Clôture org.springframework.context.support.genericApplicationContext@4f7d0008: Date de démarrage [Mer mai 30 21:38:17 CST 2018]; Racine de la hiérarchie du contexte
21: 38: 25 839 Info Thread-0 simultante.threadpooltaskexecutor: 203 - Arrêt
@ Points d'utilisation d'Async
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.