SpringBoot實現方法的異步調用


使用@EnableAsync注解

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@SpringBootApplication
@MapperScan({"com.company.test.api.repository.mysql.mapper"})
@EnableCaching
@EnableSwagger2
@EnableAsync
@EnableTransactionManagement
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Serivce中的方法用@Async進行注解,如果所有的方法都是異步的,可以在類上面注解即可。

package com.company.test.api.base.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AsyncTestServiceImpl {

    @Async
    public void sayHello(){
        try {
            int total = 0;
            for(int i=0;i<10000;i++){
                total = total + i;
            }
            log.info("Hello " + total);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

進行測試

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JoyApiApplicationTest {

    @Autowired
    private AsyncTestServiceImpl asyncTestService;

    @Test
    public void async(){
        asyncTestService.sayHello();
        log.info("end");
    }
}

執行結果

 

 

 

結束


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM