java—在ApacheCamel中使用缓存组件将变量保存为全局变量

cczfrluj  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(403)

我们的目标是使可重用的变量从主体中获取,以便将它也用于通过路由的其他转换。更具体地说,目的是从接口获取一个令牌,并将其用于进一步的访问,如image.flow chart所示

要求如下:

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

krcsximq

krcsximq1#

为了保存它,可以使用名为caffee的缓存组件。
以下是实现目标的一些有用的关键步骤:

//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秒的过程。
以下是该组件文档的直接链接:
https://camel.apache.org/components/latest/caffeine-cachecomponent.html#_examples
还有一个有用的例子:
https://danielblancocuadrado.medium.com/apache-camel-use-of-cache-with-caffeine-63a147aac785.

相关问题