简体   繁体   English

使用缓存组件在 Apache Camel 中将变量保存为全局变量

[英]Using of Cache component in order to save variables as global in Apache Camel

The goal is to make reusable a variable taken from the body in order to use it also for other transitions through the route.目标是使从主体中获取的变量可重用,以便将其也用于路径中的其他转换。 More specific, the intent was to obtain a token from the interface and using it for further accesses as in the image.更具体地说,目的是从接口获取令牌并将其用于进一步的访问,如图像中所示。 Flow chart流程图

The Requirements were:要求是:

  1. Keeping the variable saved for a settable time.将变量保存一段可设置的时间。
  2. Managing of the variable in order to obtain it when required.管理变量以便在需要时获取它。

In order to save it, it is possible to use a Cache component called Caffeine.为了保存它,可以使用一个叫做 Caffeine 的 Cache 组件。

In the following, some useful key steps to accomplish the goal:以下是实现目标的一些有用的关键步骤:

//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

This is the procedure to save the token as global variable and make it available for 60 seconds.这是将令牌保存为全局变量并使其可用 60 秒的过程。

Here a direct link of the documentation of this component:这里是该组件文档的直接链接:

And one useful example:还有一个有用的例子:

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

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