spring-boot - @Async 不适用于我的一种方法
问题描述
我认为当我为此方法添加 @Async 表示法时,它会返回一个空结果。方法是从网站获取数据并返回数据。当我删除@Async 时它会起作用。当我不使用@Async 时,它使用的是一个名为“http-nio-8080-exec-1”的线程,当我使用@Async 时,它使用的是一个带有我的命名前缀“My-thread1”的线程。我不知道我是否需要在其他任何地方进行配置,例如 xml 之类的。谢谢!
@Async
public CompletableFuture<List<Post>> searchByTag(String[] tags, String sortBy, String direction ) throws ExecutionException, InterruptedException, IOException {
logger.info("I am here---------------------------------------------------------- ");
if(tags == null || tags.length == 0){
throw new ResponseStatusException(HttpStatus.BAD_REQUEST , "Tags parameter is required");
}
if(sortBy == null){
sortBy = "id";
} else if(!sortBy.equals("id") && !sortBy.equals("reads") && !sortBy.equals("likes") && !sortBy.equals("popularity")){
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "sortBy parameter is invalid");
}
if(direction == null){
direction = "asc";
} else if(!direction.equals("asc") && !direction.equals("desc")){
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "direction parameter is invalid");
}
long start = System.currentTimeMillis();
Set<Post> postSet = new HashSet<Post>();
String baseUrl = "https://api.hatchways.io/assessment/blog/posts?tag=";
HttpClient client = HttpClient.newHttpClient();
// send a get request to get all the posts with certain tag
for(int i = 0; i < tags.length; i++){
String url = baseUrl + tags[i];
HttpRequest request = HttpRequest.newBuilder()
.GET()
.header("Accept", "application/json")
.uri(URI.create(url))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
ObjectMapper mapper = new ObjectMapper();
// HttpResponse<String> result = response.get();
String responseBody = response.body().substring(9, response.body().length()-1);
logger.info("Using Thread: " + Thread.currentThread().getName());
List<Post> posts = mapper.readValue(responseBody, new TypeReference<List<Post>>() {});
// put all the posts into a set to filter out all the repeated posts
postSet.addAll(posts);
}
ArrayList<Post> postList = new ArrayList<>(postSet);
sortThePosts(sortBy, direction, postList);
long end = System.currentTimeMillis();
logger.info("Total time: " + Long.toString(end-start));
return CompletableFuture.completedFuture(postList);
}
以下是我的配置:
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "threadPoolTaskExecutor")
public Executor taskExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(3);
threadPoolTaskExecutor.setMaxPoolSize(5);
threadPoolTaskExecutor.setQueueCapacity(20);
threadPoolTaskExecutor.setThreadNamePrefix("My_Thread");
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
解决方案
配置看起来不错。您是否在调用该方法的同一类中创建了 searchByTag() 方法?如果是这样,请尝试创建一个包含您的异步方法的单独服务类。
推荐阅读
- reactjs - 每当我重新加载仪表板时,我的登录组件都会闪烁
- android - Android Studio:元素不对交互做出反应(但仅在模拟器中)
- python - pytorch中的层规范化
- docker - Docker 容器日志文件丢失
- django - django-channels 在连接时将用户添加到多个组
- recursion - Rust - 在递归函数中收集 Vec 的切片
- python - 将循环输出转换为列表 python
- c++ - Visual Studio (C++) 中的构建错误(文件/目录丢失?)
- node.js - MongoDB,在数组中填充嵌套对象
- ansible - 角色内的 Ansible 复制模块