天天看點

本地緩存-google guava

http://ifeve.com/google-guava-cachesexplained/

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


public class ConvertBeanUtil {
    private static final Logger logger = LoggerFactory.getLogger(ConvertBeanUtil.class);
    private static ConcurrentHashMap<String, BeanCopier> cache = new ConcurrentHashMap<String, BeanCopier>();


    /**
     * 使用json轉換對象效率低。但是可以相容不通資料類型 無實際需求不建議使用
     * @param object
     * @param entityClass
     * @param <T>
     * @return
     */
    public static <T> T convertBeanByJson(Object object, Class<T> entityClass) {
        if (null == object) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(object), entityClass);
    }

    /**
     * 使用json轉換對象效率低。但是可以相容不通資料類型 無實際需求不建議使用
     * @param sourceObjs
     * @param entityClass
     * @param <T>
     * @return
     */
    public static <T> List<T> convertBeanListByJson(List<?> sourceObjs, Class<T> entityClass) {
        if (null == sourceObjs) {
            return null;
        }
        return JSON.parseArray(JSON.toJSONString(sourceObjs), entityClass);
    }


    /**
     * @param source       源對象class
     * @param target       目标對對象class
     * @param sourceObj    複制的源對象
     * @param useConverter
     * @return
     * @throws Exception
     */
    public static <T> T copyBeanProperties(@SuppressWarnings("rawtypes") Class source, Class<T> target,
                                           Object sourceObj, boolean useConverter) {
        if (sourceObj == null) return null;
        T t;
        try {
            t = target.newInstance();
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
        String key = source.getSimpleName() + target.getSimpleName();
        BeanCopier copier = cache.get(key);
        if (copier == null) {
            copier = createBeanCopier(source, target, useConverter, key);
        }
        copier.copy(sourceObj, t, null);
        return t;
    }

    /**
     * @param sourceObj 源對象
     * @param target    目标對象
     * @return
     * @throws Exception
     */
    public static <T> T copyBeanProperties(Object sourceObj, T target) {
        return copyBeanProperties(sourceObj, target, false);
    }

    /**
     * @param sourceObj    源對象
     * @param target       目标對象
     * @param useConverter
     * @return
     * @throws Exception
     */
    public static <T> T copyBeanProperties(Object sourceObj, T target, boolean useConverter) {
        if (sourceObj == null || target == null) return null;
        String key = sourceObj.getClass().getSimpleName() + target.getClass().getSimpleName();
        BeanCopier copier = cache.get(key);
        if (copier == null) {
            copier = createBeanCopier(sourceObj.getClass(), target.getClass(), useConverter, key);
        }
        copier.copy(sourceObj, target, null);
        return target;
    }

    public static <T> List<T> copyListBeanPropertiesToList(List<?> sourceObjs, List<T> targets, Class<T> targetType) {
        if (sourceObjs == null || targets == null || targetType == null) return null;
        T t;
        for (Object o : sourceObjs) {
            try {
                t = targetType.newInstance();
                targets.add(copyBeanProperties(o, t, false));
            } catch (InstantiationException e) {
                logger.error("", e);
            } catch (IllegalAccessException e) {
                logger.error("", e);
            }
        }
        return targets;
    }

    @SuppressWarnings("unused")
    private static String getHashKey(String str) {
        if (str == null) return null;
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }

    @SuppressWarnings({"rawtypes"})
    private static BeanCopier createBeanCopier(Class sourceClass, Class targetClass, boolean useConverter,
                                               String cacheKey) {
        BeanCopier copier = BeanCopier.create(sourceClass, targetClass, useConverter);
        cache.putIfAbsent(cacheKey, copier);
        return copier;
    }
}
           
public class FileTypeService {

    private final String CORE_FILE_TYPE = "core_file_type";

    @Autowired
    private CreditAdapter creditAdapter;


    /**
     * @desc  本地配置緩存
     * @author zoufan
     * @date 2020/7/22
    */
    private LoadingCache<String, List<CreditFileTypesQueryRespDto>> configListCache = CacheBuilder.newBuilder()
            .expireAfterWrite(1, TimeUnit.DAYS)
            .build(new CacheLoader<String, List<CreditFileTypesQueryRespDto>>() {
                @Override
                public List<CreditFileTypesQueryRespDto> load(String key) throws Exception {
                    List list = new ArrayList();
                    if (CORE_FILE_TYPE.equals(key)) {
                        list = creditAdapter.creditFileTypesQuery("ALL");
                    }
                    List<CreditFileTypesQueryRespDto> list2 = new ArrayList<>();
                    if(Objects.nonNull(list)&& list.size()>0){
                        ConvertBeanUtil.copyListBeanPropertiesToList(list, list2, CreditFileTypesQueryRespDto.class);
                    }
                    return list2;
                }
            });

    /**
     * @desc  擷取單條緩存資訊
     * @author zoufan
     * @date 2020/7/22
     * @param source
     * @return cn.com.cxjk.service.api.cxph.common.entity.LoanDataSetEntity
    */
    public List<CreditFileTypesQueryRespDto> queryListBySource(String source){
        log.info("FileTypeService.queryListBySource,source: ", source);
        try {
            List<CreditFileTypesQueryRespDto> list = configListCache.get(CORE_FILE_TYPE).stream().filter(CreditFileTypesQueryRespDto -> CreditFileTypesQueryRespDto.getSource().contains(source)).collect(Collectors.toList());
            return list;
        } catch (ExecutionException e) {
            log.error("FileTypeService.queryListBySource, error:{}", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 清空緩存
     */
    public void refreshFileTypeCache() {
        // 重新整理今日緩存
        configListCache.refresh(CORE_FILE_TYPE);
    }


}