Created
June 27, 2018 23:41
-
-
Save bszeti/4f855cd80cd69e3953ff990b0ae056a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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