/* (C) 2022 YiRing, Inc. */
package com.yiring.common.config;

import cn.hutool.crypto.digest.DigestUtil;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;

/**
 * Cache KeyGenerator
 *
 * @author Jim
 * @version 0.1
 * 2022/4/19 15:36
 */

@Slf4j
@Component
public class CacheKeyGenerator implements KeyGenerator {

    @Override
    @NonNull
    public Object generate(Object target, Method method, Object... params) {
        int len = params.length;

        Map<String, Object> map = new HashMap<>(2 + len);
        map.put("target", target.getClass().toGenericString());
        map.put("method", method.getName());
        for (int i = 0; i < len; i++) {
            map.put("params-" + i, Objects.toString(params[i]));
        }

        return DigestUtil.sha256(map.toString());
    }
}
