Spring @Async

2021-02-11 11:19

阅读:608

标签:except   nts   print   thread   返回   操作   turn   out   tac   

引入

@SpringBootApplication
@EnableAsync
public class ProjectApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProjectApplication.class, args);
    }
}

使用

@Slf4j
public class TestService {

    @Async
    @Transactional //事务无效
    public void asyncVoid() {
        TestService testService = SpringUtil.getBean(TestService.class); //获取代理类proxy
        testService.update(); //事务有效
        System.out.println("无返回值方法");
    }

    @Async
    @Transactional //事务无效
    public Future asynReturn() {
        System.out.println("返回值Future(AsyncResult)");
        try {
            Thread.sleep(3000);
            TestService testService = SpringUtil.getBean(TestService.class); //获取代理类proxy
            testService.update(); //事务有效
            return new AsyncResult("异步返回");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Transactional
    public void update(){
        System.out.println("操作数据库");
    }

    public void callAsync() throws InterruptedException, ExecutionException, TimeoutException {
        TestService testService = SpringUtil.getBean(TestService.class); //获取代理类proxy
        Future future = testService.asynReturn();
        String result = future.get(2L, TimeUnit.SECONDS); //等待2秒后获取
    }

}

Spring @Async

标签:except   nts   print   thread   返回   操作   turn   out   tac   

原文地址:https://www.cnblogs.com/itplay/p/12736183.html


评论


亲,登录后才可以留言!