目前系统的大部分业务和配置需要使用数据库中的数据,如果每次使用这些数据都从数据库中读取的话,不仅数据访问时间长,而且会给数据库服务器带来较大的压力。缓存就是将数据库中的内容读取出来,放到内存中,网元在需要数据时不再从数据库中读取,而是直接从缓存中读取。
二、缓存实现
1、Ehcache配置文件*.ehcache.xml
系统使用的缓存是基于Ehcache开源缓存框架上开发的,大部分原理与其相同。
// 将数据放到Ehcache中管理 Element element = new Element(key, value); Cache.putQuiet(element); // 从Ehcache中获取数据 Element element = Cache.getQuiet(key); Object value = element.getObjectValue(); // 从Ehcache中删除数据 Cache.remove(key);
2、缓存加载接口Cacheable
Cacheable接口是缓存加载接口,所有实现缓存的类必须实现,该类中有3个方法。
// 根据index获取某条记录 public Object getAllInfoById(T index); // 获取该类实现的缓存的名称 public String getCacheName(); // 从数据库中读取所有的缓存数据 public Map<T, Object> getAllInfo();
系统会遍历所有实现了Cacheable接口的类,调用该类的getAllInfo方法加载所有缓存。
三、缓存使用
1、实现Cacheable接口,实现Cacheable接口的3个方法。
2、修改Ehcache配置文件*.ehcache.xml,配置实现的缓存。
3、修改Spring配置文件*.service.xml,配置缓存实现类的Bean。
4、通过CacheQuerier读取缓存中的数据
// 根据cacheName和key获取相应的数据 public static Object get(String cacheName, Object key); // 获取cacheName指定缓存的所有数据 public static Map<Object, Object> getAll(String cacheName);
5、通过CacheModifier更新缓存中的数据
// 向缓存中添加一条记录或修改已有的记录 public static void put(String cacheName, Object key, Object value); // 删除缓存中的一条记录 public static void remove(String cacheName, String key); // 重新加载一块缓存 public static void updateAll(String cacheName);