DataDictionaryCache.java 2.93 KB
package com.diligrp.website.manager.cache;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.diligrp.website.dao.DataDictionaryDao;
import com.diligrp.website.domain.DataDictionary;
import com.diligrp.website.domain.DataDictionaryValue;
import com.diligrp.website.util.redis.RedisUtil;

@Component
public class DataDictionaryCache {

    public static final String DATA_DICTIONARY_REDIS_KEY = "DATA_DICTIONARY_REDIS_KEY_";
    
    public static final String DATA_DICTIONARY_REDIS_VALUE_KEY = "DATA_DICTIONARY_REDIS_VALUE_KEY";
    
    @Resource
    private RedisUtil redisUtils;

    @Resource
    private DataDictionaryDao dataDictionaryDao;

    /**
     * 
     * 获取redis 缓存数据
     * @param code
     * @return
     * @createTime 2014年7月23日 下午3:43:36
     * @author Wang22
     */
    public DataDictionary getDataDictionary(String code) {
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        String redisKey = redisUtils.makeKey(DATA_DICTIONARY_REDIS_KEY, code);
        DataDictionary dic = redisUtils.getObject(redisKey, DataDictionary.class);
        if (dic == null) {
            dic = dataDictionaryDao.getDataDictionaryByCode(code);
            if (dic != null) {
                redisUtils.setObject(redisKey, dic);
            }
        }
        return dic;
    }

    /**
     * 
     * 清除缓存
     * @param code
     * @createTime 2014年7月23日 下午3:43:48
     * @author Wang22
     */
    public void clearDataDictionaryCache(Long dicId) {
        if(dicId == null || dicId < 0) {
            return;
        }
        DataDictionary dic = dataDictionaryDao.getDataDictionaryById(dicId);
        if (dic == null) {
            return;
        }
        String code = dic.getCode();
        String redisKey = redisUtils.makeKey(DATA_DICTIONARY_REDIS_KEY, code);
        redisUtils.deleteByKey(redisKey);
        clearDataDicionaryValue(dic.getId());
    }

    public List<DataDictionaryValue> getDataDictionaryValue(Long id) {
        if (id == null || id < 0) {
            return null;
        }
        String redisKey = redisUtils.makeKey(DATA_DICTIONARY_REDIS_VALUE_KEY, String.valueOf(id));
        List<DataDictionaryValue> dicVal = redisUtils.getList(redisKey, DataDictionaryValue.class);
        if (CollectionUtils.isEmpty(dicVal)) {
            dicVal = dataDictionaryDao.getDataDictionaryValue(id);
            if(!CollectionUtils.isEmpty(dicVal)){
                redisUtils.setObject(redisKey, dicVal);
            }
        }
        return dicVal;
    }
    
    public void clearDataDicionaryValue(Long id) {
        if (id == null || id < 0) {
            return;
        }
        String redisKey = redisUtils.makeKey(DATA_DICTIONARY_REDIS_VALUE_KEY, String.valueOf(id));
        redisUtils.deleteByKey(redisKey);
    }

}