首页 > 解决方案 > 将resilience4j @TimeLimiter 注释转换为代码

问题描述

@TimeLimiter注释到底是什么?

例子

    @TimeLimiter(name = "abc123")
    public <T> CompletableFuture<T> execute(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier);
    }

可能等于:

    public <T> CompletableFuture<T> execute(Supplier<T> supplier) {
        TimeLimiter timeLimiter = timeLimiterRegistry.timeLimiter("abc123");

        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3); // This scheduler must somehow exist with the annotation as well right?
        return timeLimiter.executeCompletionStage(
            scheduler, () -> CompletableFuture.supplyAsync(supplier)).toCompletableFuture();
    }

代码的非阻塞变体中所需的调度程序是否以某种方式参与注释?

研究

我主要读过:

  1. Resilience4J 的TimeLimiter 指南
  2. Reflectoring 的博客文章使用 Resilience4j 实现超时

还有其他地方我可以理解注释的作用吗?

标签: annotationsresilience4jtime-limiting

解决方案


注释由注释处理器收集,resilience4j-springTimeLimiterAspect.

这里使用面向切面编程 (AOP) 扩展AspectJ为带注释方法的JointPoint周围的时限弹性切面创建Advice 。

您可以查看它的代码,例如第 90 行,以了解评估的注释和方法/类元信息如何用于围绕带注释的方法的执行 (JointPoint)编织(Advice)TimeLimiter装饰 (Aspect)。

进一步阅读

有关 AOP 与 AspectJ 的介绍,您可以阅读 Baeldung 的AspectJ 简介

Resilience4J 如何利用 AOP 可以在官方 Resilience4J 指南、 Spring Boot 2Resilience4j-spring-boot2 入门、注释中阅读:

Spring Boot2 starter 提供了自动配置的注解和 AOP Aspects。


推荐阅读