perkenalan
Dalam pemrosesan bisnis, beberapa bisnis menggunakan metode asinkron lebih masuk akal. Misalnya, dalam logika bisnis tertentu, beberapa data disimpan dalam cache Redis. Cache hanyalah fungsi tambahan. Keberhasilan atau kegagalan tidak akan memiliki dampak mendasar pada bisnis utama. Proses ini dapat dilakukan melalui metode asinkron.
Di musim semi, metode ini dapat disebut secara asinkron dengan mengatur anotasi @Async pada metode ini. Dengan kata lain, metode ini akan segera kembali setelah doa, dan eksekusi yang sebenarnya dari metode ini diserahkan kepada Taskexecutor Spring untuk diselesaikan.
Contoh Kode
Proyek ini adalah proyek musim semi normal, file konfigurasi pegas:
<? XML Versi = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmls xmlns: context = "http://www.springframework.org/schema/context" xmlns: Task = "http://www.springframework.org/schema/task" xsi: schemalocation = "http:/schema http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/www.spramework.org/schema/contex http://www.springframework.org/schema/task http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-tkask.xsd "> <! Base-package = "com.lzumetal.ssm"/> <!-kumpulan utas untuk mengeksekusi tugas asinkron Taskexecutor-> <Tugas: Executor ID = "MyExecutor" Pool-size = "5"/> <Tugas: Executor yang digerakkan oleh anotasi = "MyExecutor"/</Beans>
Dua kelas layanan:
Paket com.lzumetal.ssm.anotation.service; impor org.slf4j.logger; impor org.slf4j.loggerFactory; impor org.springframework.beans.factory.annotation.Autowired; impor org.springframework.sereotypy.servacy; java.util.concurrent.executionException; impor java.util.concurrent.future;/** * Layanan Bisnis */@Servicepublic Businessservice {private static final Logger Log = loggerFactory.getLogger (bisnisservice.class); @Autowired Private Cacheservice Cacheservice; public void dobusiness () {log.error ("Mulai berurusan dengan bisnis kami"); cacheservice.cachedata (); Log.Error ("Operasi Layanan Comlete"); } / *** Dapatkan nilai pengembalian untuk Eksekusi Metode Asynchronous* / public void DobusinessWithAsynCreturn () melempar ExecutionException, InterruptedException {LOG.Error ("Mulai berurusan dengan bisnis kami"); Masa depan <string> masa depan = cacheservice.cachedatawithreturn (); Log.Error (Future.get ()); //future.get () Metode adalah log.Error blocking ("Comlete Service Operation"); }} Paket com.lzumetal.ssm.anotation.service; impor org.slf4j.logger; impor org.slf4j.loggerFactory; impor org.springframework.scheduling.annotation.async; Import org.springframework.scheduling.annotation.async; org.springframework.stereotype.Service;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;/** * Cache Service*/@Servicepublic class CacheService { private static final Logger log = LoggerFactory.getLogger(CacheService.class); @Async (value = "myexecutor") // Tentukan Taskexecutor untuk menjalankan tugas public void cacachedata () {coba {timeunit.seconds.sleep (3L); } catch (InterruptedException e) {E.PrintStackTrace (); } log.Error ("Sukses Simpan hasilnya ke cache"); } @Async Public Future <string> CachedataWithReturn () {coba {timeunit.seconds.sleep (3l); } catch (InterruptedException e) {E.PrintStackTrace (); } log.Error ("Sukses Simpan hasilnya ke cache"); // Hasil yang dikembalikan perlu dibungkus oleh kelas asyncresult mengembalikan asyncresult baru <> ("keberhasilan operasi async"); }}Kelas Tes:
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; impor org.springframework.test.context.junit4.springjunit4classRunner; import java.util.concurrent.timeunit; @runwith (springJunit4classrassrassrass) {"classpath: spring-ontext.xml"}) kelas publik Maintest {@Autowired swasta bisnis layanan bisnis layanan; @Test public void test () melempar InterruptedException {BusinessService.Dobusiness (); // Jangan biarkan utas utama berakhir terlalu dini, jika tidak, konsol tidak akan melihat konten output dalam metode asinkron timeunit.seconds.sleep (5L); } @Test public void testAsynCreturn () melempar Exception {BusinessService.DobusinessWithAsynCreturn (); Timeunit.seconds.sleep (5L); }}Hasil dari menjalankan metode test ():
22: 20: 33.207 Info Dukungan Utama. org.springframework.test.context.support.dirtiescontextBeforemodestestExecutionListener, org.springframework.test.context.support.testexport.contextextextereren, org.spramewework.testextex.contextextener, org.spramework.testextex.contextexer org.springframework.test.context.transaction.transactionaltestExecutionListener, org.springframework.test.context.jdbc.sqlscriptstestExecutionListener]]
22: 20: 33.226 Info Dukungan Utama. Tentukan kelas pendengar khusus atau buat kelas pendengar default (dan dependensi yang diperlukan) tersedia. Kelas pelanggaran: [JAVAX/SERVLET/SERVLETCONTEXT]
22: 20: 33.227 Info Dukungan Utama. org.springframework.test.context.support.dependencynectionTestExecutionListener@643b1d11, org.springframework.test.context.support.dirtiescontexttexecutionListener@2ef5e5e3, org.springframework.test.context.transaction.transactionaltestexecutionListener@36d4b5c, org.springframework.test.context.jdbc.sqlscriptStestExecutionListener@6d00a15d] 22: 20: 33.33.33.33.32. Memuat definisi kacang xml dari sumber daya jalur kelas [spring-ontext.xml]
22: 20: 33.585 Info Dukungan Utama. akar hierarki konteks
22: 20: 33.763 Info Main concurrent.threadpooltaskexecutor: 165 - Inisialisasi ExecutorService
22: 20: 33.766 Info Dukungan Utama. PostProcessor registrationDelegate $ beanpostprocessorChecker: 325 - bean 'myexecutor' tipe [org.springframework.scheduling.config.taskexecutorcorybean tidak dapat diproses oleh overpossorfactorybean. proxying otomatis)
22: 20: 33.767 Info Dukungan utama. PostProcessor registrationDelegate $ beanpostprocessorChecker: 325 - bean 'myexecutor' tipe [org.springframework.scheduling.concurrent.threadpooltaskexecutor] tidak perlu diproses. proxying otomatis)
22: 20: 34.107 Kesalahan Layanan Utama.BusinessService: 24 - Mulai berurusan dengan bisnis kami
22: 20: 34.113 Kesalahan Layanan Utama.BusinessService: 26 - Operasi Layanan Lengkap
22: 20: 37.166 Kesalahan Layanan MyExecutor -1.
22: 20: 39.117 Info Thread -0 Support.GenericappLicationContext: 984 - penutupan org.springframework.context.support.genericapplicationContext@4F7D0008: Tanggal awal [Rabu 30 Mei 22:20:33 CST 2018]; akar hierarki konteks
22: 20: 39.118 Info Thread -0 concurrent.threadpooltaskexecutor: 203 - Mematikan ExecutorService
Hasil dari menjalankan metode testasyncreturn ():
21: 38: 16.908 Info Dukungan Utama. org.springframework.test.context.support.dirtiescontextBeforemodestestExecutionListener, org.springframework.test.context.support.testexport.contextextextereren, org.spramewework.testextex.contextextener, org.spramework.testextex.contextexer org.springframework.test.context.transaction.transactionaltestExecutionListener, org.springframework.test.context.jdbc.sqlscriptstestExecutionListener]]
21: 38: 16.926 Info Dukungan Utama. Tentukan kelas pendengar khusus atau buat kelas pendengar default (dan dependensi yang diperlukan) tersedia. Kelas pelanggaran: [JAVAX/SERVLET/SERVLETCONTEXT]
21: 38: 16.927 Info Dukungan Utama. org.springframework.test.context.support.dependencynectionTestExecutionListener@643b1d11, org.springframework.test.context.support.dirtiescontexttexecutionListener@2ef5e5e3, org.springframework.test.context.transaction.transactionaltestexecutionListener@36d4b5c, org.springframework.test.context.jdbc.sqlscriptStestExecutionListener@6d00a15d] 21: 17: 17: 17.17: 17.17: 17.17: 17.17: 17: 17.17: 17.17: 17: 17.17: 17: 17.17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: 17: Memuat definisi kacang xml dari sumber daya jalur kelas [spring-ontext.xml]
21: 38: 17.263 Info Dukungan Utama. akar hierarki konteks
21: 38: 17.405 Info Main Concurrent.ThreadpooltaskExecutor: 165 - Inisialisasi ExecutorService
21:38:17,407 INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.config.TaskExecutorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for proxying otomatis)
21: 38: 17.407 Info Dukungan Utama. PostProcessor registrationDelegate $ beanpostprocessorChecker: 325 - bean 'myexecutor' tipe [org.springframework.scheduling.concurrent.threadpooltaskexecutor] tidak perlu diproses. proxying otomatis)
21: 38: 17.692 Kesalahan Layanan Utama.BusinessService: 35 - Mulailah berurusan dengan bisnis kami
21: 38: 20.833 Kesalahan MyExecutor -1 Service.Cacheservice: 39 - Sukses Simpan Hasilnya untuk Cache
21: 38: 20.834 Kesalahan Layanan Utama.
21: 38: 20.835 Kesalahan Layanan Utama.BusinessService: 38 - Operasi Layanan Lengkap
21: 38: 25.838 Info Thread -0 Support.GenericapplicationContext: 984 - penutupan org.springframework.context.support.genericapplicationContext@4F7D0008: Tanggal Startup [Rabu 30 Mei 21:38:17 CST 2018]; akar hierarki konteks
21: 38: 25.839 Info Thread -0 concurrent.threadpooltaskexecutor: 203 - Mematikan ExecutorService
Poin penggunaan @async
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.