Simple and powerful cache using redis
In this example, we use spring boot but not limited to other java project
Add pom
<dependency>
<groupId>com.ahyakamil</groupId>
<artifactId>akcache</artifactId>
</dependency>
Create configuration class, ex: AKCacheConfig.java
@Aspect
@Configuration
public class AKCacheConfig {
@Autowired
AKService akService;
@Bean
public void akCacheSetup() {
AKCacheSetup.setupConnection("localhost", 6379, "", "");
}
@Around("execution(* *(..)) && @annotation(com.ahyakamil.AKCache.annotation.AKCache) || @annotation(com.ahyakamil.AKCache.annotation.AKCacheUpdate)")
public Object setListener(ProceedingJoinPoint pjp) throws Throwable {
Object result = AKCacheSetup.setListener(pjp);
akService.renewCache();
return result;
}
}
@Service
class AKService {
@Async
@Transactional // <-- Optional
public void renewCache() throws Throwable {
AKCacheSetup.renewCache();
}
}
IMPORTANT
- Do renewCache() asynchronously for better experience
- Transactional used for avoid lazy session exception hibernate
@AKCache
- updateType: SMART
- serializeClass: Object.class
- ttl: 24 hours
- conditionRegex: .*
- UpdateType SMART : will return cache and if ttl is more than 75%, it will execute real method to update cache
- UpdateType FETCH : will return cache and execute real method immediately to update cache
- for debug you can add properties "logging.level.com.ahyakamil=DEBUG"
@AKCache(serializeClass = HttpEntity.class)
@GetMapping("/hello")
public Object newEmployee() {
return ResponseEntity.ok("hello world");
}
Since spring boot ResponseEntity doesn't have "no args constructor" which is used for serialization, we can use HttpEntity for serializing.
@AKCache(serializeClass = HttpEntity.class, conditionRegex = ".*\"statusCodeValue\":200")
@GetMapping("/hello")
public Object newEmployee() {
return ResponseEntity.ok("hello world");
}
cache if statusCodeValue 200
@AKCache(updateType = UpdateType.FETCH, serializeClass = HttpEntity.class)
@GetMapping("/hello")
public Object newEmployee() {
return ResponseEntity.ok(Math.random());
}
return cache if exist then update cache immediately
TODO
Will update for more feature, stay tuned..
Licensed under Apache 2.0 license