`

cacheable 将一个对象作为key

阅读更多

@Cacheable(value = {"userLogs"}, keyGenerator = "cacheKeyGenerator" )

 

 

 

package com.opencloud.common.configuration;

 

import lombok.extern.slf4j.Slf4j;

import org.springframework.cache.interceptor.KeyGenerator;

import org.springframework.cache.interceptor.SimpleKey;

import org.springframework.stereotype.Component;

 

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

 

// 缓存key 生成器

@Slf4j

@Component

public class CacheKeyGenerator implements KeyGenerator {

 

    @Override

    public Object generate(Object target, Method method, Object... params) {

        if(params.length == 0){

            return SimpleKey.EMPTY;

        }

        StringBuilder key = new StringBuilder();

        for (Object param : params) {

            //此处处理的是一个对象 如果是Map需自行验证是否可行

            Field[] fields = getAllFields(param.getClass());

            for(Field field:fields) {

                //抑制Java对修饰符的检查

                field.setAccessible(true);

                try {

//                    log.info("fieldName:{} fieldVuale:{}",field.getName(),field.get(param));

                    key.append(field.getName()+"="+field.get(param)+" , ");

                } catch (IllegalAccessException e) {

                    e.printStackTrace();

                }

 

            }

        }

        return key;

    }

 

    /**

     * 获取本类以及父类的属性方法

     * @param clazz 当前类对象

     * @return 字段数组

     */

    private static Field[] getAllFields(Class<?> clazz){

        List<Field> fieldList = new ArrayList<>();

        while (clazz != null){

            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));

            clazz = clazz.getSuperclass();

        }

        Field[] fields = new Field[fieldList.size()];

        return fieldList.toArray(fields);

    }

 

  

}

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics