Skip to content

Instantly share code, notes, and snippets.

@bszeti
Created June 27, 2018 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bszeti/4f855cd80cd69e3953ff990b0ae056a2 to your computer and use it in GitHub Desktop.
Save bszeti/4f855cd80cd69e3953ff990b0ae056a2 to your computer and use it in GitHub Desktop.
// Let's assume we have a Spring environment
...
import javax.cache.CacheManager;
import my.company.utils.CachePolicy;
@Component
public class CachedRoute extends RouteBuilder{
private static final Logger log = LoggerFactory.getLogger(CachedRoute.class);
@Override
public void configure() throws Exception {
from("direct:cachedRoute")
.policy(getUserDataCachePolicy())
.setProperty("userData").method(userDataService.class,"lookupUserDataByName");
}
@Autowired
CacheManager cacheManager;
//Cache user data by user name. If user data is found in cache the rest of the route is not executed.
private Policy getUserDataCachePolicy(){
CachePolicy cachePolicy = new CachePolicy();
if (cacheManager!=null) {
cachePolicy.setCache(cacheManager.getCache("userDataCache"));
}
//User name is the cache key
cachePolicy.setKeyExpression(simple("${header.userName}"));
//What to do the the cached object if found
cachePolicy.setApplyCachedObject(new BiConsumer<Exchange, Object>() {
public void accept(Exchange exchange, Object cached){
exchange.setProperty("userData",cached);
}
});
//Cache userData at the end of the route
cachePolicy.setValueExpression(exchangeProperty("userData"));
return cachePolicy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment