Posted By

nialace on 03/29/11


Tagged

java caching


Versions (?)

caching with ehcache


 / Published in: Java
 

download Ehcache (www.http://ehcache.org/) from website, unzip it and use ehcache.xml inside root folder

  1. package ilex;
  2.  
  3. import net.sf.ehcache.Cache;
  4. import net.sf.ehcache.CacheException;
  5. import net.sf.ehcache.CacheManager;
  6. import net.sf.ehcache.Element;
  7.  
  8. public class testos2 {
  9.  
  10.  
  11. static Cache cache = null;
  12.  
  13. static {
  14.  
  15. CacheManager cacheManager = null;
  16. try {
  17. cacheManager = CacheManager.create("C:/Users/asel/Desktop/MPPSources/MeiboPeoplePack/Packaging/Tools/Meibo/Studio/ehcache.xml");
  18. } catch (CacheException e) {
  19. e.printStackTrace();
  20. }
  21.  
  22. cache = cacheManager.getCache("sampleCache1");
  23.  
  24.  
  25. }
  26.  
  27. /**
  28.   * @param args
  29.   * @throws CacheException
  30.   * @throws IllegalStateException
  31.   */
  32. public static void main(String[] args) throws IllegalStateException, CacheException {
  33.  
  34.  
  35. String result = doit("a");
  36. System.out.println(result);
  37.  
  38. result = doit("a");
  39. System.out.println(result);
  40.  
  41.  
  42. }
  43.  
  44.  
  45. public static String doit(String key) throws IllegalStateException, CacheException {
  46. String result;
  47.  
  48. //get an element from cache by key
  49. Element e = cache.get(key);
  50. if (e != null) {
  51. result = (String)e.getValue();
  52. System.out.println("retrieved "+ result+" from cache ");
  53. }
  54. else {
  55. result = "new value" ;
  56. cache.put(new Element(key, result));
  57. }
  58. return result;
  59. }
  60.  
  61. }

Report this snippet  

You need to login to post a comment.