Reputation: 1
I am adding a cache (caffeine) to rest api call in camel code.
Please consider the code below:
@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();
}
}
How can I set and configure the cache instead of passing the parameters every time I do a call to the cache? I have try with caffeineCacheBuilder but seems that my custom cache is overwrited by the default one Thanks
Upvotes: 0
Views: 335
Reputation: 427
I think you can use the component level options [1] setting them in the application.properties
file
It would be literally something like:
camel.component.caffeine-cache.expire-after-access-time=100
camel.component.caffeine-cache.expire-after-write-time=100
...
When you're using the component, if the specific parameter is not set in the URI, then, it should be taken from here.
Upvotes: 0