All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.eworkcloud.caffeine.CaffeineCacheTemplate Maven / Gradle / Ivy

There is a newer version: 2.5.8
Show newest version
package com.eworkcloud.caffeine;

import org.springframework.cache.Cache;
import org.springframework.cache.caffeine.CaffeineCacheManager;

public class CaffeineCacheTemplate {

    private CaffeineCacheManager caffeineCacheManager;

    protected CaffeineCacheTemplate(CaffeineCacheManager caffeineCacheManager) {
        this.caffeineCacheManager = caffeineCacheManager;
    }

    /**
     * 获取缓存
     *
     * @param name 名称
     * @return 缓存
     */
    public Cache getCache(String name) {
        return caffeineCacheManager.getCache(name);
    }

    /**
     * 读取缓存
     *
     * @param name 名称
     * @param key  键
     * @param   类型
     * @return 值
     */
    @SuppressWarnings("unchecked")
    public  T get(String name, String key) {
        Cache cache = getCache(name);

        Cache.ValueWrapper valueWrapper = cache.get(key);
        if (null == valueWrapper) {
            return null;
        }

        return (T) valueWrapper.get();
    }

    /**
     * 设置缓存(替换已存在键)
     *
     * @param name  名称
     * @param key   键
     * @param value 值
     * @param    类型
     */
    public  void put(String name, String key, T value) {
        Cache cache = getCache(name);

        cache.put(key, value);
    }

    /**
     * 设置缓存(忽略已存在键)
     *
     * @param name  名称
     * @param key   键
     * @param value 值
     * @param    类型
     * @return 已有值
     */
    @SuppressWarnings("unchecked")
    public  T putIfAbsent(String name, String key, T value) {
        Cache cache = getCache(name);

        Cache.ValueWrapper valueWrapper = cache.putIfAbsent(key, value);
        if (null == valueWrapper) {
            return null;
        }

        return (T) valueWrapper.get();
    }

    /**
     * 删除缓存
     *
     * @param name 名称
     * @param key  键
     */
    public void evict(String name, String key) {
        Cache cache = getCache(name);

        cache.evict(key);
    }

    /**
     * 清除缓存
     *
     * @param name 名称
     */
    public void clear(String name) {
        Cache cache = getCache(name);

        cache.clear();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy