2016-12-03 redis设置初启动并执行缓存以及执行方法后再执行缓存

    xiaoxiao2021-12-14  19

    tip:重启web服务器是不能够清空redis缓存的 如果没有在web容器的监听中配置清除的方法,那么只有连接上redis的服务器并且执行flushall方法才能够清除缓存

    1.设置在WEB容器在启动的时候就加载缓存,如何设置

    思路:在Spring容器启动或者刷新的时候进行设置,所以必须用到ApplicationListener去监听ApplicationContext

    自定义的ApplicationListener如下(观察者模式)

    @Component("ContextRefreshedListener") public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> { /** * 当一个ApplicationContext被初始化或刷新触发 */ @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) { //System.out.println("spring容器初始化完毕================================================"); //多数据源缓存加载 SysSvrHelper.loadxml(); //应用系统、数据源映射缓存加载 AppUtils.loadCache(); //缓存系统参数 SysConfigUtils.loadCache(); } }}

    监听的自定义事件封装类为

    @SuppressWarnings("serial") public class ContextRefreshedEvent extends ApplicationContextEvent { /** * Create a new ContextRefreshedEvent. * @param source the {@code ApplicationContext} that has been initialized * or refreshed (must not be {@code null}) */ public ContextRefreshedEvent(ApplicationContext source) { super(source); } } 这样在ApplicationContext出现变化(启动或者刷新)的时候就会自动监听,因此我们就可以在ApplicationContext发生加载的时候调用redis缓存

    SysConfigUtils.loadCache(); public static void loadCache(){ logger.info("=============应用系统服务数据缓存加载============="); List<AppReg> appRegs = appRegDao.findAllList(); if(!appRegs.isEmpty()) { for(AppReg appReg : appRegs) { //缓存应用系统服务器 CacheUtils.put(AppUtils.SYS_APP, appReg.getCappId(), appReg.getSvrName()); } } }可以看到调用了CacheUtils,put方法

    public static void put(String cacheName, String key, Object value) { // Element element = new Element(key, value); // getCache(cacheName).put(element); RedisUtils.putCache(key, value); }import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.minstone.common.utils.redis.RedisManager; public class RedisUtils { private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class); private static RedisManager cacheManager = ((RedisManager) SpringContextHolder .getBean("redisManager")); static{ cacheManager.init(); } public static void putCache(String key, Object value) { // LOGGER.debug("根据key从redis中存储对象 key [" + key + "]"); cacheManager.set(key.getBytes(), SerializeUtils.serialize(value), 0); } public static void putCache(String key, Object value,int expire) { // LOGGER.debug("根据key从redis中存储对象 key [" + key + "]"); cacheManager.set(key.getBytes(), SerializeUtils.serialize(value), 0); } public static Object getCache(String key) { // LOGGER.debug("根据key从Redis中获取对象 key [" + key + "]"); byte[] value = cacheManager.get(key.getBytes()); Object object = SerializeUtils.deserialize(value); return object; } public static void removeCache(String key){ // LOGGER.debug("根据key从redis中删除对象 key [" + key + "]"); cacheManager.del(key.getBytes()); } /** * flush */ public void flushDB() { LOGGER.debug("清楚所有Redis Key"); cacheManager.flushDB(); } /** * size */ public Long dbSize() { Long dbSize = cacheManager.dbSize(); return dbSize; } } 直接使用SpringContextHolder获取RedisManager然后进行保存

    至此Spring启动的时候进行redis缓存部署基本完成

    2.按需加载

    触发器

    <mt:dict type="select" name="open" dictType="TREE_IS_OPEN" width="333" value="${treeDemo.open }"/> 找自定义标签mt.tld

    <tag> <name>dict</name> <tag-class>com.common.tags.DictTag</tag-class> <body-content>empty</body-content> <info>字典项标签</info> <attribute> <name>dictType</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <description>字典类型名称</description> </attribute> <attribute> <name>name</name> <required>false</required> <rtexprvalue>true</rtexprvalue> <description>表单元素名称</description> </attribute> .................. 查看类的DoTag方法

        @Override     public void doTag() throws JspException, IOException {         PageContext context = (PageContext) getJspContext();         Writer out = context.getOut();         //参数封装         Map<String ,Object> params = new HashMap<String , Object>();                  params.put("name", name);         params.put("dataList", getDictList(dictType));         params.put("type", type.toLowerCase());         params.put("value", value);         params.put("width", width);         params.put("className", className);         params.put("needDefault", needDefault);         params.put("other", other);                  //根据表单元素生成器,生成html         String html = FormEleUtils.getFormEleHtml(params);         out.write(html);     } 入口方法

    getDictList(dictType) 然后开始处理

    private List<Map<String,Object>> getDictList(String type){ //获取字典 List<Dict> dictList = DictUtils.getDictList(type); //格式转化 List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>(); for(Dict dict : dictList){ Map<String,Object> map = new HashMap<String,Object>(); //获取对应字典项的值、描述 map.put("value",dict.getDictValue()); map.put("key", dict.getDictKey()); map.put("isDefault", dict.getIsDefault()); dataList.add(map); } return dataList; } public static List<Dict> getDictList(String type){ @SuppressWarnings("unchecked") Map<String, List<Dict>> dictMap = (Map<String, List<Dict>>)CacheUtils.get(CACHE_DICT_MAP); if (dictMap==null){ dictMap = Maps.newHashMap(); for (Dict dict : dictDao.findAllList(new Dict())){ List<Dict> dictList = dictMap.get(dict.getDictType()); if (dictList != null){ dictList.add(dict); }else{ dictMap.put(dict.getDictType(), Lists.newArrayList(dict)); } } CacheUtils.put(CACHE_DICT_MAP, dictMap); } List<Dict> dictList = dictMap.get(type); if (dictList == null){ dictList = Lists.newArrayList(); } return dictList; } 同样调用了CacheUtils的方法那么和上面一样了,注意实现逻辑是如果CACHE_DICT_MAP对应的值不在redis中会直接加载缓存,如果存在就不会加载而是取出然后返回

    问题:如果修改其他数据库中的字段,radis服务器不能够及时响应,因为KEY已经存在所以不会重新加载

    转载请注明原文地址: https://ju.6miu.com/read-969998.html

    最新回复(0)