一、异步接口实现
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 异步功能并没有起到作用。执行结果如下: