java - @Async 在 Spring Boot 应用程序中给我错误

标签 java spring multithreading spring-boot asynchronous

这是主应用程序类:

@EnableAsync(proxyTargetClass = true)
@EnableDiscoveryClient
@SpringBootApplication
public class ProductApplication {

    public static void main(final String[] args) {
        SpringApplication.run(ProductApplication.class, args);
    }

    @Bean("threadPoolTaskExecutor")
    public TaskExecutor getAsyncExecutor() {
        final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(1000);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix("Async-");
        return executor;
    }

}

这是服务类别:

@Component
public class ProductServiceImpl implements ProductService {

    @Autowired
    ProductRepository productRepository;

    @Autowired
    private ProductHandler productHandler;

    @Async
    @Override
    public List<String> getAllCategories() {
        final List<String> finalList = new ArrayList<>();
        return finalList;
    }

}

这是 Controller 类:

@RestController
public class ProductResource {

    @Autowired
    private ProductServiceImpl productServiceImpl;

    @GetMapping("/categories")
    public ResponseEntity<List<String>> getAllCategories() {
        return new ResponseEntity<>(this.productServiceImpl.getAllCategories(), HttpStatus.OK);
    }
}

我已使用 @Async 注释了服务实现方法,但收到此错误:

Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

如果我尝试注释 Controller ,我的获取请求将得到空响应。我已经尝试了所有方法,包括将 proxyTargetClass 设置为 true。

最佳答案

只要你使用 @Async 注解,您必须熟悉使用它时必须遵守的规则:

  • 该方法必须是 public
  • 不能从同一类中的方法调用(自调用)
  • 如果使用返回类型,则必须将其包装在 Future<T> 中, 前任。 CompletableFuture<T>

所以你得到:

CompletableFuture<List<String>> categories = this.productServiceImpl.getAllCategories();

进一步的处理是由 Future 的实现驱动的您可以在其中阻止执行或 join将更多内容合并到一个响应中...

关于java - @Async 在 Spring Boot 应用程序中给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61134832/

相关文章:

java - 我的编码 driver.findElement(By.linkText ("Logout")).click();测试脚本中没有执行

java - 在抽象基类中使用 @autowired

java - 对于 java 线程,处理同步静态方法与非静态方法所需的时间是否有任何差异?

c# - 正确生成唯一的发票 ID

java - 使用 reactor 的 Flux.buffer 进行批处理仅适用于单个项目

java - 未使用PreparedStatement将数据插入到数据库表中

java - 在 BigDecimal 中查找有效数字位数的好方法?

java - 通过 Controller 拦截 Aspect 方法

java - 在一个实例 bean 上同时使用注解和 XML 配置

java - 在 Java 中安全地启动/停止服务实例