简体   繁体   English

在不阻塞主线程的情况下异步调用方法调用

[英]Invoke method call asynchronously without blocking main thread

I have a scenario where the spring-boot application have to download a file from downstream application and pass it to the client.我有一个场景,spring-boot 应用程序必须从下游应用程序下载文件并将其传递给客户端。 The API also needs to update a read flag in the database without blocking the response(main-thread). API 还需要在不阻塞响应(主线程)的情况下更新数据库中的读取标志。

A basic async use-case is what I thought of and implemented in the respective API.一个基本的异步用例是我在各自的 API 中想到并实现的。 But, I am getting a behavioral issue with @Async.但是,我遇到了@Async 的行为问题。 The annotation is able to spawn a new thread, but its blocking the main-thread and holding the response.注释能够产生一个新线程,但它阻塞了主线程并持有响应。 The expectation was to return without holding the main-thread.期望是在不持有主线程的情况下返回。 Actually, the async update is the last operation of main-thread, and I guess due to that @Async is blocking the main-thread.实际上,异步更新是主线程的最后一个操作,我猜是因为@Async 阻塞了主线程。

Can anyone please suggest a better solution of this scenario.任何人都可以建议这种情况的更好解决方案。

Calling class调用 class

ResponseEntity<byte[]> parsedResponse = retrieverService.retrieve(id,"html");

retrieverService.update(id);

return parsedResponse;

Async method异步方法

@Override
@Async("updateTaskExecutor")
public void update(String id) {
    LOG.info("Updating data for metaTagId: {}", id);
    db.updateReadFlag(id);
}

Async Config异步配置

@Configuration
@EnableAsync
public class AsyncConfiguration {

    @Bean(name = "updateTaskExecutor")
    public Executor updateTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(100);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("UpdateTaskClient-");
        executor.initialize();
        return executor;
    }
}

The Configurations were correct.配置是正确的。 I was using debugger to check the parallelism.我正在使用调试器来检查并行度。 As suggested by @M.正如@M 所建议的那样。 Deinum, its not the correct way to check parallelism. Deinum,它不是检查并行性的正确方法。 After using Thread.sleep(), I could see that asynchronous calls are working as expected.使用 Thread.sleep() 后,我可以看到异步调用按预期工作。 I am able to send the response back, while performing an update query asynchronously.我能够在异步执行更新查询的同时发回响应。

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

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