@Async 异步不起作用

一、异步接口实现

java中的异步接口实现比较简单,主要有两步:

  • 1、在ContentServiceApplication上添加@EnableAsync。
  • 2、在需要异步的接口上添加@Async接口。
// 第一步

@EnableAsync
public class ContentServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ContentServiceApplication.class, args);
    }

}

// 第二步
    @Async
    @Override
    public void threadInfoAsync() throws InterruptedException {
        log.info("开始执行定时任务");
        HashSet<String> authorList = threadService.syncThreadEffectInfoToMongo();
        log.info("需要同步的作者列表 size = " + authorList.size());
        contentAuthorService.syncAuthorEffectInfoToMongo(authorList);
    }

二、@Async 异步不起作用

按照上面的步骤配置后就可以实现异步接口。
但有一种情况例外:@Async所修饰的接口和调用这个接口的function在同一个类中,此时异步不起作用

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static java.lang.Thread.sleep;

@RestController
@RequestMapping("/test")
@Slf4j
public class testAsync {

    @RequestMapping("/test")
    String getFunctionInfo(@RequestBody String str) throws InterruptedException {
        log.info("接受到请求");
        printAsyncInfo();
        log.info("返回请求");

        return "success";
    }

    @Async
    void printAsyncInfo() throws InterruptedException {
        for(int i = 0; i < 10; i++){
            log.info("接口异步响应中: i = " + i);
            sleep(1000);
        }
    }
}

上面代码@Async 异步功能并没有起到作用。执行结果如下:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值