package com.ishop.merchant.cache; import com.ishop.merchant.ArticleCategoryCache; import com.ishop.merchant.Constants; import com.ishop.merchant.service.ArticleServiceImpl; import com.ishop.merchant.util.VoUtils; import com.ishop.model.po.EbArticleCategory; import com.ishop.model.vo.ArticleCategoryVo; import com.walker.cache.Cache; import com.walker.infrastructure.ApplicationRuntimeException; import com.walker.infrastructure.utils.JsonUtils; import com.walker.infrastructure.utils.StringUtils; import com.walker.support.redis.cache.RedisCache; import com.walker.support.redis.cache.RedisCacheProvider; import java.util.ArrayList; import java.util.List; public class RedisArticleCateCache extends RedisCacheProvider implements ArticleCategoryCache { public RedisArticleCateCache(){ this.setUseRedis(true); this.setLoadPage(false); } @Override protected int loadDataToCache(Cache cache) { List hosts = this.articleService.selectAll(new EbArticleCategory()); if(!StringUtils.isEmptyList(hosts)){ // ------------------------- 切换成普通缓存步骤:3 if(this.isUseRedis()){ // 如果redis中缓存数量和数据库中不一致(少),则清空redis缓存,重新加载数据库数据到缓存中。 long totalCache = cache.getPersistentSize(); if(totalCache < hosts.size()){ logger.info("redis缓存中Category数量小于实际用户,需要清空缓存重新加载! cache = " + totalCache + ", db = " + hosts.size()); cache.clear(); for(EbArticleCategory h : hosts){ if(h.getIsDel().intValue() == 1){ continue; } cache.put(String.valueOf(h.getId()), VoUtils.acquireArticleCategoryVo(h, "")); } } }//------------------------------------------ return hosts.size(); } return 0; } @Override public List getList() { List data = new ArrayList<>(2); ArticleCategoryVo vo = null; for(String value : ((RedisCache)this.getCache()).getIterator(null)){ try{ vo = JsonUtils.jsonStringToObject(value, ArticleCategoryVo.class); } catch (Exception ex){ throw new ApplicationRuntimeException("redis存储'S_category'解析错误:" + value, ex); } if(vo.getStatus()){ data.add(vo); } } return data; } @Override public ArticleCategoryVo get(long id) { return this.getCacheData(String.valueOf(id)); } @Override public void save(ArticleCategoryVo category) { this.putCacheData(String.valueOf(category.getId()), category); } @Override public void update(ArticleCategoryVo category) { this.updateCacheData(String.valueOf(category.getId()), category); } @Override public void remove(long id) { this.removeCacheData(String.valueOf(id)); } @Override public String getProviderName() { return Constants.CACHE_NAME_ARTICLE_CATE; } @Override public Class getProviderType() { return ArticleCategoryVo.class; } public void setArticleService(ArticleServiceImpl articleService) { this.articleService = articleService; } private ArticleServiceImpl articleService; }