/** * 缓存管理类一定要设计成单例模式. * 1、单例模式只提供私有的构造函数. * 2、类中含有一个该类的静态私有对象. * 3、对外提供一个静态的共有的函数用于获取本身的静态私有对象. * @author lenovo * */ public class MemcacheManager { private static MemcachedClient memcache; private static MemcacheManager instance = new MemcacheManager(); private MemcacheManager() { XMemcachedClientBuilder memcachedClientBuilder = new XMemcachedClientBuilder(AddrUtil.getAddresses("124.16.154.180:11211")); try { memcache = memcachedClientBuilder.build(); } catch (IOException e) { e.printStackTrace(); } } public static MemcacheManager getInstance(){ return instance; } public void addCache(String key,Object value){ try { memcache.add(key, 0, value); //设置缓存中数据过期时间. } catch (Exception e) { e.printStackTrace(); } } public Object getCache(String key){ try { Object obj = memcache.get(key); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) throws Exception { MemcacheManager mm = new MemcacheManager(); mm.addCache("w", "wxh"); System.out.println(mm.getCache("w")); } }
利用缓存能够明显的提高网页性能,我们一般会吧一些常用的或者每次访问时需要发费大量时间处理的数据缓存起来,我们这里使用缓存是因为页面中的数据是通过大量的计算得到的统计数据,如果每次访问都通过数据库的话,性能是非常低下的,所以我们在此做了缓存,并在后台定时更新缓存中的内容。