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

com.eworkcloud.guava.GuavaCacheTemplate Maven / Gradle / Ivy

There is a newer version: 1.8.6
Show newest version
package com.eworkcloud.guava;

import org.springframework.cache.Cache;
import org.springframework.cache.guava.GuavaCacheManager;

public class GuavaCacheTemplate {

    private GuavaCacheManager guavaCacheManager;

    public GuavaCacheTemplate(GuavaCacheManager guavaCacheManager) {
        this.guavaCacheManager = guavaCacheManager;
    }

    /**
     * 获取缓存
     *
     * @param name 名称
     * @return 缓存
     */
    public Cache getCache(String name) {
        return guavaCacheManager.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);
        return null == valueWrapper ? null : (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);
        return null == valueWrapper ? null : (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