首页 > 解决方案 > 使用缓存组件以在 Apache Camel 中将变量保存为全局变量

问题描述

目标是使从主体中获取的变量可重用,以便将其也用于路径中的其他转换。更具体地说,目的是从接口获取令牌并将其用于进一步的访问,如图像中所示。流程图

要求是:

  1. 将变量保存一段可设置的时间。
  2. 管理变量以便在需要时获取它。

标签: javaapache-camelcaffeine-cache

解决方案


为了保存它,可以使用一个叫做 Caffeine 的 Cache 组件。

以下是实现目标的一些有用的关键步骤:

//get of the token from the cache
.setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_GET))
.setHeader(CaffeineConstants.KEY, constant("<KEY>")))
.toF("caffeine-cache://%s", cacheName?evictionType=TIME_BASED&expireAfterWriteTime=60) //options settings


.choice()
      //if is not valid
      .when(header(CaffeineConstants.ACTION_HAS_RESULT).isEqualTo(Boolean.FALSE))
                .to("direct-some-external-service") //token obtaining
                
      // save resulting token into cache
                .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_PUT))
                .setHeader(CaffeineConstants.KEY, constant(constant(<KEY>")))
                .toF("caffeine-cache://%s", cacheName?evictionType=TIME_BASED&expireAfterWriteTime=60)
                .otherwise()
.end()

//some other steps

这是将令牌保存为全局变量并使其可用 60 秒的过程。

这里是该组件文档的直接链接:

还有一个有用的例子:


推荐阅读