简体   繁体   English

异步注释在 SpringBoot 中对我不起作用

[英]Async Annotation not working for me in SpringBoot

@Async is not working for me, tried debugging it multiple times but the api was running in same thread. @Async 对我不起作用,尝试多次调试它,但 api 在同一个线程中运行。

Am I missing something in my configuration or there is some interplay between the components which I cannot see?我是否在我的配置中遗漏了某些东西,或者我看不到的组件之间存在一些相互作用?

I am debugging by calling the same api 2-3 times with fixed interval of time but all are running in same thread.我通过以固定的时间间隔调用相同的 api 2-3 次进行调试,但所有这些都在同一个线程中运行。

Config Class:配置类:

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean("threadPoolTaskExecutor")
    public TaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsyncThread-");
        executor.initialize();
        return executor;
    }

}

Method where I want to apply async我要应用异步的方法

@Async("threadPoolTaskExecutor")
    public static CompletableFuture<Object> getExecutionDatafromDb() {
        long start = System.currentTimeMillis();

        Object executionData = "";

        db = mongoClient.getDatabase(database);

        collection = db.getCollection("executiondata");

        Document data = null;
        BasicDBObject whereQuery = new BasicDBObject();
        Document document = new Document();

        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json = null;

        whereQuery.put(MACHINE_ID, 8);
        whereQuery.put(PROJECT_ID, 121);
        iterDoc = collection.find(whereQuery).cursor();

        try {
            if (iterDoc.hasNext()) {
                data = iterDoc.next();
                executionData = data.get("execution_data");
            } else {
                executionData = createExecutionDataJson();
                document.put("execution_data", executionData);
                document.put(MACHINE_ID, machineId);
                document.put(PROJECT_ID, projectId);
            }

        } catch (Exception e) {
            throw new BusinessException("605",
                    "Something went wrong in Service layer while fetching Execution Data From Db" + e.getMessage());
        }

        logger.info("Fecthing data "+Thread.currentThread().getName());
        try {
            json = ow.writeValueAsString(executionData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } finally {
            iterDoc.close();

        }
        long end = System.currentTimeMillis();
        logger.info("Total time {}", (end - start));
 
        return CompletableFuture.completedFuture(json);
    }

Api which I want to hit:我想打的API:

@SuppressWarnings("static-access")
@GetMapping(value = "/getExecutionDataByThread", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getExecutionDataByThread() {
    
    Object result1 = asyncService.getExecutionDatafromDb();
    sleep(2); // for demonstration
    Object result2 = asyncService.getExecutionDatafromDb();
    sleep(2);
    Object result3 = asyncService.getExecutionDatafromDb();
    

    return ResponseEntity.status(HttpStatus.OK).build();
    
}

The async method works by wrapping the object with the annotated method in a proxy that gets a thread from the pool and executes the task on it. async 方法通过将带有注释方法的对象包装在代理中来工作,该代理从池中获取线程并在其上执行任务。 This works for instance methods of spring managed objects, it doesn't work for static methods.这适用于 spring 管理对象的实例方法,它不适用于静态方法。 Make the method an instance method.使该方法成为实例方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM