码迷,mamicode.com
首页 > 编程语言 > 详细

Spring @Async

时间:2020-04-20 10:24:36      阅读:61      评论:0      收藏:0      [点我收藏+]

标签: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<String> asynReturn() {
        System.out.println("返回值Future(AsyncResult)");
        try {
            Thread.sleep(3000);
            TestService testService = SpringUtil.getBean(TestService.class); //获取代理类proxy
            testService.update(); //事务有效
            return new AsyncResult<String>("异步返回");
        } 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<String> 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!