Reputation: 32144
I'm writing a java project using Spring framework 3.2.4.
I have many SQL queries that needs to be cached for 10 seconds.
I know that with @cacheable
annotation i can cache functions result.
What I don't understand is how to cache for only 10 seconds. i know you can add conditions to the cacheable annotation but it's hard for me to figure out how to add timing to these conditions.
any information regarding the issue would be greatly appreciated.
Upvotes: 2
Views: 9075
Reputation: 11
You can solve it with a LocalDateTime object. For example:
@Cacheable(value="forecast", key = "#date.toString()")
public void forecast(LocalDateTime date){
//
}
public void call(){
LocalDateTime dateTime = LocalDateTime.now();
int currentSecond = dateTime.getSecond();
int newSecond = currentSecond - (currentSecond % 10);
forecast(dateTime.withSecond(newSecond));
}
Cache will expire after 10 seconds.
Positive aspect - it does not require a scheduled job.
Negative aspect - old data remains cached.
Upvotes: 0
Reputation: 14551
You can use a Scheduler to periodically call a service method which evicts the caches.
Scheduler:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.beans.factory.annotation.Autowired;
public class Scheduler {
@Autowired
private SomeService someService;
@Scheduled(fixedRate = 10000)
public void evictCaches() {
someService.evictCaches();
}
}
Service:
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class SomeService {
@CacheEvict(value = { "cache1", "cache2" }, allEntries = true)
public void evictAllCaches() {
}
}
Upvotes: 3
Reputation: 15901
Spring doesn't offer this out of the box but it supports adapters and you may use for example guava adapter which among other things allows configure expiration timeout.
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<list>
<bean name="testCache"
class="org.hypoport.springGuavaCacheAdapter.SpringGuavaCacheAdapter">
<property name="expireAfterAccessInSeconds" value="10"/>
<property name="expireAfterWriteInSeconds" value="10"/>
</bean>
</list>
</property>
</bean>
Upvotes: 2