package com.muyu.common.cache.abs;

import com.muyu.common.cache.Cache;
import com.muyu.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

/**
 * @author DongZl
 * @description: 缓存抽象类
 * @Date 2024-3-27 下午 03:10
 */
public abstract class CacheAbs<K, V> implements Cache<K, V> {

    @Autowired
    private RedisService redisService;

    /**
     * 编码
     * @param key ID
     * @return 键
     */
    @Override
    public String encode (K key) {
        return keyPre() + key;
    }

    /**
     * 通过Key获取value值
     * @param key 键
     * @return 值
     */
    @Override
    public V get (K key) {
        V value = redisService.getCacheObject(encode(key));
        if (value == null){
            value = getData(key);
            if (value == null){
                value = defaultValue();
            }
        }
        this.put(key, value);
        return value;
    }

    /**
     * 缓存添加/修改
     * @param key   键
     * @param value 值
     */
    @Override
    public void put (K key, V value) {
        this.redisService.setCacheObject(encode(key), value);
    }

    /**
     * 通过键删除
     * @param key 键
     */
    @Override
    public void remove (K key) {
        this.redisService.deleteObject(encode(key));
    }

    /**
     * 刷新缓存
     * @param key 键
     */
    @Override
    public void refreshTime (K key) {
        this.redisService.expire(encode(key), 60, TimeUnit.SECONDS);
    }

    /**
     * 刷新缓存数据
     *
     * @param key 键
     */
    @Override
    public void refreshData (K key) {
        this.put(key, getData(key));
    }

    /**
     * 从数据库获取数据
     * @param key ID
     * @return 缓存对象
     */
    public abstract V getData(K key);

    /**
     * 默认值
     */
    public abstract V defaultValue();
}
