提问人:Arianna Stefanoni 提问时间:10/27/2023 更新时间:10/27/2023 访问量:35
如何在骆驼中配置咖啡因缓存
How to configure caffeine cache in camel
问:
我正在为骆驼代码中的 rest api 调用添加缓存(咖啡因)。
请考虑以下代码:
@Component
public class TenantIdService extends ServiceBaseRouteBuilder {
@Value("${platform.endpointsOrchestrated.tenantId}")
private String msEndpoint;
@Value("${spring.cache.caffeine.maximumSize}")
private String maximumSize;
@Value("${spring.cache.caffeine.expireAfterWriteTime}")
private String expireAfterWriteTime;
@Value("${spring.cache.caffeine.cacheName}")
private String cacheName;
private StmKafkaDTO stmKafkaDTORequest;
@Override
public void configure() {
super.configure();
from(direct(CALL_CACHE))
.toF("caffeine-cache://%s?evictionType=TIME_BASED&expireAfterWriteTime=%s&maximumSize=%s",
cacheName,
expireAfterWriteTime,
maximumSize);
// cached call
from(direct(ADD_TENANT_ID))
.unmarshal().json(StmKafkaDTO.class)
.process(exchange -> {
stmKafkaDTORequest = exchange.getIn().getBody(StmKafkaDTO.class);
exchange.setProperty(STM_EVENT_EXCHANGE_PROPERTY, stmKafkaDTORequest.getPayload());
})
// Check if result is in cache
.setHeader(CaffeineConstants.ACTION, constant("get"))
.setHeader(CaffeineConstants.KEY, constant("TranslateEvent"))
.to(direct(CALL_CACHE).getUri())
//TODO: test log
.log("Has Result ${header.CamelCaffeineActionHasResult} ActionSucceeded ${header.CamelCaffeineActionSucceeded}")
.log("Cache body: ${body}")
.choice()
.when(header(CaffeineConstants.ACTION_HAS_RESULT).isEqualTo(Boolean.FALSE))
.log(LoggingLevel.INFO, "Cache miss. Calling TranslateEvent...")
// Cache miss, call the endpoint
.setHeader(Exchange.HTTP_METHOD, constant("GET"))
.toD(msEndpoint + Util.BRIDGE_ENDPOINT + Util.THROW_EXCEPTION_OFF)
.unmarshal().json(CoCountryMappingDTOResponse[].class)
.process(TenantIdMapper::mapResponse) // Map the cached response
.process(PublishToPlatService::publishStmEventToPlatform) // Publish the mapped response
.setHeader(CaffeineConstants.ACTION, constant("put")) // Cache the result
.to(direct(CALL_CACHE).getUri())
.otherwise()
.log(LoggingLevel.INFO, "Cache hit. Response from cache: ${body}")
.process(TenantIdMapper::mapResponse) // Map the cached response
.process(PublishToPlatService::publishStmEventToPlatform) // Publish the mapped response
.end()
.stop();
}
}
如何设置和配置缓存,而不是在每次调用缓存时都传递参数? 我尝试过使用 caffeineCacheBuilder,但似乎我的自定义缓存被默认缓存覆盖了 谢谢
答:
0赞
Squake
10/27/2023
#1
我认为您可以使用组件级选项 [1] 在文件中设置它们application.properties
从字面上看,它是这样的:
camel.component.caffeine-cache.expire-after-access-time=100
camel.component.caffeine-cache.expire-after-write-time=100
...
使用组件时,如果未在 URI 中设置特定参数,则应从此处获取该参数。
评论