package com.muyu.data.processing.utils;

import com.github.yulichang.toolkit.SpringContentUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

/**
* 缓存工具类
* @Author: 胡杨
* @Name: CacheUtils
* @Description: 缓存工具类
* @CreatedDate: 2024/10/9 下午4:21
* @FilePath: com.muyu.data.processing.utils
*/

@Slf4j
@Component
public class CacheUtils {
    private static CacheManager cacheManager = SpringContentUtils.getBean(CacheManager.class);

    /**
     * 获取缓存分区
     * @param cacheName 缓存分区名称
     * @return 缓存实例
     */
    public Cache getCache(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null){
            throw new RuntimeException("缓存分区: "+cacheName+" 不存在");
        }
        return cache;
    }

    /**
     * 设置缓存值
     * @param cacheName 缓存分区名称
     * @param key 键
     * @param value 值
     */
    public void setCacheValue(String cacheName, String key, Object value) {
        getCache(cacheName).put(key, value);
        log.info("缓存存储成功:分区-{}, 键-{}, 值-{}", cacheName, key, value);
    }


    /**
     * 判断缓存是否存在
     * @param cacheName 缓存分区名称
     * @param key 键
     * @return  结果
     */
    public Boolean hasKey(String cacheName, String key) {
        return ObjectUtils.isNotEmpty(getCache(cacheName).get(key));
    }

    /**
     * 获取缓存值(不限定类型)
     * @param cacheName 缓存分区名称
     * @param key 键
     * @return  结果
     */
    public Object getCacheValue(String cacheName, String key) {
        return getCache(cacheName).get(key);
    }

    /**
     * 获取缓存值(限定类型)
     * @param cacheName 缓存分区名称
     * @param key 键
     * @param type 返回值类型
     * @return  结果
     */
    public <T> T getCacheValue(String cacheName, String key, Class<T> type) {
        return getCache(cacheName).get(key, type);
    }
}
