首页 > 解决方案 > @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;

    }

}

标签: spring-bootasynchronous

解决方案


配置看起来不错。您是否在调用该方法的同一类中创建了 searchByTag() 方法?如果是这样,请尝试创建一个包含您的异步方法的单独服务类。


推荐阅读