Reputation: 55
I started building a JSF 2.0 application recently and i was thinking if someone could help me with an idea i had.
I have a List of objects (pulled from a lookup table) that i know it doesn't changes often (let's say a List of Countries). Countries is a simple example of a list that doesn't change so often but that list could easily be objects that change for example every a couple of weeks.
In a session-scoped bean what i usually do is load that List from the database.
Now my question is this: is there any way to keep such a List (or Lists of course) in a cache that expires after a period of time and reload this List after expiration? Hopefully somebody would have faced the same "problem" and could share his experience!
Thanks in advance!
Upvotes: 1
Views: 1626
Reputation: 3509
I would not do it in UI layer but rather cache your lookup method using ehcache. In case you use hibernate, you can use it's second level cache (look also for query cache). In case you use Spring you can easily annotate your service methods this way:
@Cacheable("countries")
public List<Country> findCountries(){
// ... your lookup code here....
}
You can also invalidate the cache when a country gets updated:
@CacheEvict(value = "countries", allEntries=true)
public void saveCountry(Country country){
// your code for saving a country
}
And finally in your ehcache.xml you can define the live time (timeToLiveSeconds) of the cache. You can even define that it never should be invalidated (eternal=true), when you are sure that changes can be only applied through your service facade.
<cache name="countries" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120"/>
Update 1:
So your backing bean itself can be even request or view scoped:
@ManagedBean
@ViewScoped
public class Bean{
@Inject
private CountryService countryService;
public List<Country> getCountries(){
return countryService.findCountries();
}
}
Upvotes: 4