Skip to content
gbbennett edited this page Jun 15, 2013 · 3 revisions

Quick example to show usage of caching annotations

Following snippet is example using memcached. Initialisation only needs to be done once and of course could be injected via a framework such as Spring.

public class CachedExample {
    @CacheImplementation
    private CacheInterface memcachedBasedCache;
	
    public CachedExample(){
        super();
        MemcachedServer server = new MemcachedServer();
        server.setServer("localhost");
        server.setPort(11211);
        List<MemcachedServer> servers = new ArrayList<MemcachedServer>();
        servers.add(server);
        memcachedBasedCache = new MemcachedBasedCache(servers);
    }
    @Cache(name="test.Country.Cache")
    public Country lookupCountry(String isoCode){
        // this method is cached keyed on isoCode
    }
    @Cache(name="test.Language.Cache")
    public List<Language> lookupLanguages(@CacheKey String isoCode, boolean defaultOnly){
        // this method is cached keyed only on isoCode
    }
    @Cache(name="test.Flights.Cache")
    public List<Flight> getFlights(@CacheKey String isoCode, 
        @CacheKey(style="date", format="dd-MM-yy") Date date){
        // method cached keyed on isoCode and date as string format as shown
    }
}

Clone this wiki locally