package com.ylcm.sys.config;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSONObject;

@Configuration
@EnableCaching
public class CacheConfig {

	@Bean("cacheManager")
	public EhCacheCacheManager EhcacheManager() {
    	EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    	return ehCacheManager;
    }
	
	@Bean
    public KeyGenerator cacheKeyGenerator(){
        CacheKeyGenerator cacheKeyGenerator = new CacheKeyGenerator();
        return cacheKeyGenerator;

    }
    public class CacheKeyGenerator implements KeyGenerator {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            Map<String, Object> map = new LinkedHashMap<>();
            if (params != null && params.length > 0) {
                int i = 0;
                for (Object o : params) {
                    map.put("params-" + i, o);
                    i++;
                }
            }
            String str = JSONObject.toJSON(map).toString();
            return method.getName() + "-" + DigestUtils.md5DigestAsHex(str.getBytes());
        }
    }
}
