缓存类型及实现方式

缓存类型及实现方式

缓存概念

数据交换的缓冲区(Cache),程序访问频繁数据会从内存复制到缓存,供程序读取,由于缓存的访问速度高于内存,从而提升程序读写数据速度

缓存类型

堆缓存

使用Java堆内存存储缓存对象,存储较热对象

特点
  • 优点:无需序列化/反序列化,速度最快
  • 缺点:缓存数据量大时,GC(垃圾回收)暂停时间会变长,存储容量受限于堆空间大小,程序重启数据丢失

一般通过软引用/弱引用方式存储缓存对象,当堆内存不足时,可以强制回收这部分缓存释放堆内存空间。

实现方式
  1. HashMap:HashMap是Java中最常用的内存缓存实现之一。它使用哈希表数据结构来存储键值对,具有快速的查找和插入操作。

  2. ConcurrentHashMap:ConcurrentHashMap是线程安全的HashMap实现,适用于多线程环境下的缓存需求。它使用分段锁来实现并发访问,提供了更高的并发性能。

  3. Caffeine:Caffeine是一个基于Java的高性能缓存库,提供了内存缓存的功能。它使用了类似于ConcurrentHashMap的分段锁机制,并提供了更多的缓存策略和配置选项。

  4. Guava Cache:Guava Cache是Google Guava库中提供的一个内存缓存实现。它提供了简单易用的API,并支持缓存的过期时间、最大大小等配置选项。

  5. Ehcache:Ehcache是一个流行的Java缓存框架,支持内存缓存和磁盘缓存。它提供了丰富的配置选项和缓存策略,适用于各种缓存需求。

堆外缓存

使用堆外内存缓存对象

特点
  • 优点:GC暂停时间较短(堆对象转移到堆外,GC扫描和移动对象变少)、支持更大缓存空间(只受限于机器内存大小,不受限堆空间影响)
  • 缺点:读写数据需要序列化/反序列化,速度较堆缓存慢,程序重启数据丢失
实现方式

Ehcache 3.x、MapDB

磁盘缓存

使用磁盘缓存对象

特点
  • 优点:容量大,JVM重启缓存数据不会丢失,而堆缓存/堆外缓存数据会丢失
  • 缺点:读写速度慢
实现方式

文件缓存、数据库缓存

分布式缓存

使用分布式集群存储数据

特点
  • 优点:支持横向扩展、支持海量数据、高可用性、数据一致性
  • 缺点:配置和使用与其他相比较为复杂
实现方式
  1. Redis:Redis是一种开源的内存数据存储系统,也可以用作分布式缓存。它支持多种数据结构(如字符串、哈希、列表、集合、有序集合等),并提供了丰富的缓存功能和命令。

  2. Memcached:Memcached是一种高性能的分布式内存对象缓存系统。它以键值对的形式存储数据,并提供了简单的API来进行数据的读取和写入。Memcached可以水平扩展,适用于大规模的分布式缓存需求。

  3. Hazelcast:Hazelcast是一个开源的分布式缓存和计算平台。它提供了分布式数据结构(如Map、Queue、Set等),支持高可用性和水平扩展,并提供了分布式缓存的功能。

  4. Apache Ignite:Apache Ignite是一个内存中的分布式数据库和计算平台。它提供了分布式缓存、分布式查询、分布式计算等功能,并支持持久化存储和高可用性。

  5. Caffeine:虽然Caffeine在前面提到的是内存缓存,但它通过扩展也可以用作分布式缓存。Caffeine提供了一些分布式缓存的扩展,如Caffeine-JCache和Caffeine-Rest。

缓存实现

Ehcache
特点
  • 优点:

    • 支持本地缓存和分布式缓存。
    • 提供了丰富的配置选项和缓存策略,如过期时间、最大大小、持久化等。
    • 可以与Spring框架无缝集成。
  • 缺点:

    • 在高并发环境下,性能可能不如Caffeine、Memcached和Redis。
    • 分布式缓存功能相对较新,可能不如Redis和Memcached成熟稳定。
支持数据类型

支持存储任意类型的数据,包括基本数据类型、自定义对象等

适用场景
  • 需要本地缓存和分布式缓存的场景。
  • 对缓存的配置和策略有较高要求的场景。
使用示例
<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.9.4</version>
</dependency>
/**
 * Ehcache2Config
 */
public interface Ehcache2Config {

    /**
     * 内存中最大的缓存对象数量
     */
    int MAX_ELEMENTS_IN_MEMORY = 500;

    /**
     * 是否把溢出数据持久化到硬盘
     */
    boolean OVER_FLOW_TO_DISK = true;

    /**
     * 是否永久存活
     */
    boolean ETERNAL = false;

    /**
     * 缓存空闲多久后失效/秒
     */
    int TIME_TO_IDLE_SECONDS = 600;

    /**
     * 缓存最多存活时间/秒
     */
    int TIME_TO_LIVE_SECONDS = 1800;

    /**
     * 是否需要持久化到硬盘
     */
    boolean DISK_PERSISTENT = false;

    /**
     * 缓存策略
     */
    String MEMORY_STORE_EVICTION_POLICY = "LFU";

    /**
     * 默认的cacheName
     */
    String DEFAULT_CACHE = "cache";
}

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.data.util.Pair;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * ehcache工具类
 */
public class Ehcache2Cache implements Ehcache2Config {

    private static CacheManager cacheManager = null;
    private static Cache cache = null;

    static {
        initCacheManager();
        initCache();
    }

    /**
     * 初始化缓存管理容器
     */
    public static CacheManager initCacheManager() {
        try {
            if (cacheManager == null) {
                cacheManager = CacheManager.getInstance();
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return cacheManager;
    }

    /**
     * 初始化缓存管理容器
     *
     * @param path ehcache.xml存放的路徑
     */
    public static CacheManager initCacheManager(String path) {
        try {
            if (cacheManager == null) {
                CacheManager.getInstance();
                cacheManager = CacheManager.create(path);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return cacheManager;
    }


    /**
     * 初始化cache
     */
    public static Cache initCache() {
        return initCache(DEFAULT_CACHE);
    }

    /**
     * 获取cache
     */
    public static Cache initCache(String cacheName) {
        checkCacheManager();
        if (null == cacheManager.getCache(cacheName)) {
            cacheManager.addCache(cacheName);
        }
        cache = cacheManager.getCache(cacheName);
        return cache;
    }

    /**
     * 添加缓存
     *
     * @param key   关键字
     * @param value 值
     */
    public static void put(Object key, Object value) {
        checkCache();
        // 创建Element,然后放入Cache对象中
        Element element = new Element(key, value);
        cache.put(element);
    }

    /**
     * 获取cache
     *
     * @param key 关键字
     * @return value
     */
    public static Object get(Object key) {
        checkCache();
        Element element = cache.get(key);
        if (null == element) {
            return null;
        }
        return element.getObjectValue();
    }

    /**
     * 初始化缓存
     *
     * @param cacheName           缓存名称
     * @param maxElementsInMemory 元素最大数量
     * @param overflowToDisk      是否持久化到硬盘
     * @param eternal             是否永远存活
     * @param timeToLiveSeconds   缓存存活时间
     * @param timeToIdleSeconds   缓存的间隔时间
     * @return cache 缓存
     * @throws RuntimeException e
     */
    public static Cache initCache(String cacheName, int maxElementsInMemory,
                                  boolean overflowToDisk, boolean eternal,
                                  long timeToLiveSeconds, long timeToIdleSeconds)
            throws RuntimeException {

        try {
            Cache myCache = cacheManager.getCache(cacheName);
            if (myCache != null) {
                CacheConfiguration config = cache.getCacheConfiguration();
                config.setTimeToLiveSeconds(timeToLiveSeconds);
                config.setMaxEntriesLocalHeap(maxElementsInMemory);
                config.setOverflowToDisk(overflowToDisk);
                config.setEternal(eternal);
                config.setTimeToIdleSeconds(timeToIdleSeconds);
            }
            if (myCache == null) {
                Cache memoryOnlyCache = new Cache(cacheName, maxElementsInMemory,
                        overflowToDisk, eternal, timeToLiveSeconds, timeToIdleSeconds);
                cacheManager.addCache(memoryOnlyCache);
                myCache = cacheManager.getCache(cacheName);
            }
            return myCache;
        } catch (RuntimeException e) {
            throw new RuntimeException("init cache " + cacheName + " failed!!!");
        }
    }

    /**
     * 初始化cache
     *
     * @param cacheName         cache的名字
     * @param timeToLiveSeconds 有效时间
     * @return cache 缓存
     * @throws RuntimeException e
     */
    public static Cache initCache(String cacheName, long timeToLiveSeconds) throws RuntimeException {
        return initCache(cacheName, MAX_ELEMENTS_IN_MEMORY, OVER_FLOW_TO_DISK,
                ETERNAL, timeToLiveSeconds, TIME_TO_IDLE_SECONDS);
    }

    /**
     * 初始化Cache
     *
     * @param cacheName cache容器名
     * @return cache容器
     * @throws RuntimeException e
     */
    public static Cache initMyCache(String cacheName) throws RuntimeException {
        return initCache(cacheName, TIME_TO_LIVE_SECONDS);
    }

    /**
     * 修改缓存容器配置
     *
     * @param cacheName           缓存名
     * @param timeToLiveSeconds   有效时间
     * @param maxElementsInMemory 最大数量
     * @throws RuntimeException e
     */
    public static boolean modifyCache(String cacheName, long timeToLiveSeconds, int maxElementsInMemory) throws RuntimeException {
        try {
            if (cacheName != null && !"".equals(cacheName)
                    && timeToLiveSeconds != 0L && maxElementsInMemory != 0) {
                Cache myCache = cacheManager.getCache(cacheName);
                CacheConfiguration config = myCache.getCacheConfiguration();
                config.setTimeToLiveSeconds(timeToLiveSeconds);
                config.setMaxEntriesLocalHeap(maxElementsInMemory);
                return true;
            } else {
                return false;
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("modify cache " + cacheName + " failed!!!");
        }
    }

    /**
     * 向指定容器中设置值
     *
     * @param cacheName 容器名
     * @param key       键
     * @param value     值
     * @return 返回真
     * @throws RuntimeException e
     */

    public static boolean setValue(String cacheName, String key, Object value) throws RuntimeException {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            if (myCache == null) {
                myCache = initCache(cacheName);
            }
            myCache.put(new Element(key, value));
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("set cache " + cacheName + " failed!!!");
        }
    }

    /**
     * 向指定容器中设置值
     *
     * @param cacheName         容器名
     * @param key               键
     * @param value             值
     * @param timeToLiveSeconds 存活时间
     * @return 真
     * @throws RuntimeException e
     */
    public static boolean setValue(String cacheName, String key, Object value, Integer timeToLiveSeconds) throws RuntimeException {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            if (myCache == null) {
                initCache(cacheName, timeToLiveSeconds);
                myCache = cacheManager.getCache(cacheName);
            }
            myCache.put(new Element(key, value, timeToLiveSeconds, timeToLiveSeconds));
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("set cache " + cacheName + " failed!!!");
        }
    }

    /**
     * 从ehcache的指定容器中取值
     *
     * @param key 键
     * @return 返回Object类型的值
     * @throws RuntimeException e
     */
    public static Object getValue(String cacheName, String key) throws RuntimeException {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            if (myCache == null) {
                myCache = initMyCache(cacheName);
            }
            Element element = myCache.get(key);
            return element == null ? null : element.getObjectValue();
        } catch (RuntimeException e) {
            throw new RuntimeException("get cache " + cacheName + " value failed!!!");
        }
    }

    /**
     * 从ehcache的指定容器中取值,并获取标识位,标识是否缓存中存在这个Key
     * 该设计是为了避免空值时出现缓存穿透的可能
     *
     * @param key 键
     * @return 返回Object类型的值
     * @throws RuntimeException e
     */
    public static Pair<Boolean, Optional<?>> getValueWithState(String cacheName, String key) throws RuntimeException {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            if (myCache == null) {
                myCache = initMyCache(cacheName);
            }
            Element element = myCache.get(key);
            boolean cacheContainsKey = element != null;
            Object value = cacheContainsKey ? element.getObjectValue() : null;
            return Pair.of(cacheContainsKey, Optional.ofNullable(value));
        } catch (RuntimeException e) {
            throw new RuntimeException("get cache " + cacheName + " value failed!!!");
        }
    }

    /**
     * 删除指定的ehcache容器
     *
     * @param cacheName cacheName
     * @return 真
     * @throws RuntimeException e
     */

    public static boolean removeCache(String cacheName) throws RuntimeException {
        try {
            cacheManager.removeCache(cacheName);
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("remove cache " + cacheName + " failed!!!");
        }
    }

    /**
     * 删除所有的ehcache容器
     *
     * @return 返回真
     * @throws RuntimeException e
     */

    public static boolean removeAllCache() throws RuntimeException {
        try {
            cacheManager.removeAllCaches();
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("remove cache failed!!!");
        }
    }

    /**
     * 删除ehcache容器中的元素
     *
     * @param cacheName 容器名
     * @param key       键
     * @return 真
     * @throws RuntimeException e
     */
    public static boolean removeElement(String cacheName, String key) throws RuntimeException {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            myCache.remove(key);
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("remove cache " + cacheName + " failed!!!");
        }
    }

    /**
     * 删除指定容器中的所有元素
     *
     * @param cacheName 容器名
     * @param key       键
     * @return 真
     * @throws RuntimeException e
     */
    public static boolean removeAllElement(String cacheName, String key) throws RuntimeException {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            myCache.removeAll();
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("remove cache failed!!!");
        }
    }

    /**
     * 释放CacheManage
     */
    public static void shutdown() {
        cacheManager.shutdown();
    }

    /**
     * 移除默认cache
     */
    public static void removeCache() {
        checkCacheManager();
        if (null != cache) {
            cacheManager.removeCache(DEFAULT_CACHE);
        }
        cache = null;
    }

    /**
     * 移除默认cache中的key
     *
     * @param key key
     */
    public static void remove(String key) {
        checkCache();
        cache.remove(key);
    }

    /**
     * 移除默认cache所有Element
     */
    public static void removeAllKey() {
        checkCache();
        cache.removeAll();
    }

    /**
     * 获取所有的cache名称
     *
     * @return String[]
     */
    public static String[] getAllCaches() {
        checkCacheManager();
        return cacheManager.getCacheNames();
    }

    /**
     * 获取Cache所有的Keys
     *
     * @return List
     */
    public static List<?> getKeys() {
        checkCache();
        return cache.getKeys();
    }

    /**
     * 获取Cache所有的Keys
     *
     * @return List
     */
    public static List<?> getKeys(String cacheName) {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            if (myCache == null) {
                return new ArrayList<>();
            }
            return myCache.getKeys();
        } catch (RuntimeException e) {
            throw new RuntimeException("get cache " + cacheName + " value failed!!!");
        }
    }

    /**
     * 判断缓存是否存在该Key
     *
     * @param cacheName 缓存名称
     * @param key       key
     * @return true存在
     */
    public static boolean containsKey(String cacheName, String key) {
        try {
            Cache myCache = cacheManager.getCache(cacheName);
            if (myCache == null) {
                return false;
            }
            Element element = myCache.get(key);
            return element != null;
        } catch (RuntimeException e) {
            throw new RuntimeException("get cache " + cacheName + " value failed!!!");
        }
    }

    /**
     * 检测cacheManager
     */
    private static void checkCacheManager() {
        if (null == cacheManager) {
            throw new IllegalArgumentException("调用前请先初始化CacheManager值:initCacheManager");
        }
    }

    /**
     * 检测cache
     */
    private static void checkCache() {
        if (null == cache) {
            throw new IllegalArgumentException("调用前请先初始化Cache值:initCache(参数)");
        }
    }

    /**
     * 输出cache信息
     */
    public static void showCache() {
        String[] cacheNames = cacheManager.getCacheNames();
        System.out.println("缓存的key cacheNames length := "
                + cacheNames.length + " 具体详细列表如下:");
        for (String cacheName : cacheNames) {
            System.out.println("cacheName := " + cacheName);
            Cache cache = cacheManager.getCache(cacheName);
            List<?> cacheKeys = cache.getKeys();
            for (Object key : cacheKeys) {
                System.out.println(key + " = " + cache.get(key));
            }
        }
    }
}
Caffeine
特点
  • 优点:
    • 提供了高性能的本地缓存实现。
    • 支持多种缓存策略,如最大大小、过期时间、自动加载等。
    • 可以根据应用程序的需求进行灵活的配置。
  • 缺点:
    • 不支持分布式缓存,只能用作本地缓存。
    • 不支持持久化存储。
支持数据类型

支持存储任意类型的数据,包括基本数据类型、自定义对象等

适用场景
  • 需要高性能的本地缓存的场景。
  • 对缓存的灵活配置和策略有较高要求的场景。
使用示例
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.5.0</version>
</dependency>
import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

public class CaffeineCacheUtils {
    private static Cache<Object, Object> syncCache;
    private static AsyncCache<Object, Object> asyncCache;

    private CaffeineCacheUtils() {
    }

    public static void initCache() {
        syncCache = Caffeine.newBuilder()
                // 初始化缓存长度
                .initialCapacity(100)
                // 最大长度
                .maximumSize(1000)
                // 更新策略
                .refreshAfterWrite(10, TimeUnit.SECONDS)
                // 设置缓存的过期时间
                .expireAfterWrite(30, TimeUnit.MINUTES)
                .build();

        asyncCache = Caffeine.newBuilder()
                // 初始化缓存长度
                .initialCapacity(100)
                // 最大长度
                .maximumSize(1000)
                // 更新策略
                .expireAfterWrite(30, TimeUnit.MINUTES)
                // 设置缓存的过期时间
                .buildAsync();
    }

    public static void putSync(Object key, Object value) {
        syncCache.put(key, value);
    }

    public static Object getSync(Object key) {
        return syncCache.getIfPresent(key);
    }
    
	// 从asyncCache中获取数据,如果缓存中没有数据,则使用一个异步的supplyAsync方法从数据源获取数据,并通过传入的Executor执行器来执行这个异步任务
    public static CompletableFuture<Object> getAsync(Object key, Executor executor) {
        return asyncCache.get(key, k -> CompletableFuture.supplyAsync(() -> fetchDataFromDataSource(k), executor));
    }

    public static void putAsync(Object key, Object value, Executor executor) {
        asyncCache.put(key, CompletableFuture.completedFuture(value));
    }

    public static void removeSync(Object key) {
        syncCache.invalidate(key);
    }

    public static void clearSync() {
        syncCache.invalidateAll();
    }

    private static Object fetchDataFromDataSource(Object key) {
        // 模拟从数据源获取数据的操作
        // 这里可以根据具体业务需求进行实现
        return null;
    }
}
Memcached
特点
  • 优点:
    • 提供了高性能的分布式缓存实现。
    • 支持多种数据结构和缓存策略。
    • 可以水平扩展,适用于大规模的分布式缓存需求。
  • 缺点:
    • 不支持持久化存储。
    • 功能相对较简单,不如Redis丰富。
支持数据类型

键值存储系统,它存储的是字节数组(byte array)类型的数据。在使用Memcached时,需要将数据序列化为字节数组进行存储,然后再进行反序列化获取数据。

适用场景
  • 需要高性能的分布式缓存的场景。
  • 对缓存的扩展性和可伸缩性有较高要求的场景。
使用示例
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeoutException;
 
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
 
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;

public class XMemcachedClientWrapper implements DisposableBean {
 
    private static Logger logger = LoggerFactory.getLogger(XMemcachedClientWrapper.class);
 
    private MemcachedClient memcachedClient;
 
    /**
     * Get方法, 转换结果类型,失败时屏蔽异常只返回null.
     */
    public <T> T get(String key) {
        try {
            return (T) memcachedClient.get(key);
        } catch (Exception e) {
            handleException(e, key);
            return null;
        }
    }
    /**
     * Get方法,同时更新过期时间, 转换结果类型,失败时屏蔽异常只返回null.
     * @param exp 过期秒数
     */
    public <T> T get(String key,int exp) {
        try {
            return (T) memcachedClient.getAndTouch(key,exp);
        } catch (Exception e) {
            handleException(e, key);
            return null;
        }
    }
    
    /**
     * 功能描述:判断key是否存在
     */
    public boolean keyIsExist(String key){
        try {
            if(null == memcachedClient.get(key))
                return false;
            return true;
        } catch (TimeoutException e) {
            return false;
        } catch (InterruptedException e) {
            return false;
        } catch (MemcachedException e) {
            return false;
        }
    }
 
    /**
     * GetBulk方法, 转换结果类型, 失败时屏蔽异常只返回null.
     */
    public <T> Map<String, T> getBulk(Collection<String> keys) {
        try {
            return (Map<String, T>) memcachedClient.get(keys);
        } catch (Exception e) {
            handleException(e, StringUtils.join(keys, ","));
            return null;
        }
    }
 
    /**
     * Set方法, 不等待操作返回结果, 失败抛出RuntimeException..
     */
    public void asyncSet(String key, int expiredTime, Object value) {
        try {
            memcachedClient.setWithNoReply(key, expiredTime, value);
        } catch (Exception e) {
            handleException(e, key);
        }
    }
 
    /**
     * Set方法,等待操作返回结果,失败抛出RuntimeException..
     */
    public boolean set(String key, int expiredTime, Object value) {
        try {
            return memcachedClient.set(key, expiredTime, value);
        } catch (Exception e) {
            throw handleException(e, key);
        }
    }
 
    /**
     * Delete方法, 失败抛出RuntimeException.
     */
    public boolean delete(String key) {
        try {
            return memcachedClient.delete(key);
        } catch (Exception e) {
            throw handleException(e, key);
        }
    }
 
    /**
     * Incr方法, 失败抛出RuntimeException.
     */
    public long incr(String key, int by, long defaultValue) {
        try {
            return memcachedClient.incr(key, by, defaultValue);
        } catch (Exception e) {
            throw handleException(e, key);
        }
    }
 
    /**
     * Decr方法, 失败RuntimeException.
     */
    public long decr(String key, int by, long defaultValue) {
        try {
            return memcachedClient.decr(key, by, defaultValue);
        } catch (Exception e) {
            throw handleException(e, key);
        }
    }
 
    private RuntimeException handleException(Exception e, String key) {
        logger.warn("xmemcached client receive an exception with key:" + key, e);
        return new RuntimeException(e);
    }
 
    public MemcachedClient getMemcachedClient() {
        return memcachedClient;
    }
 
    @Autowired(required = false)
    public void setMemcachedClient(MemcachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
        if (memcachedClient != null) {
            this.memcachedClient.setOpTimeout(5000L);
//            this.memcachedClient.setOptimizeGet(false);
        }
    }
 
    public void destroy() throws Exception {
        if (memcachedClient != null) {
            memcachedClient.shutdown();
        }
 
    }
}
Redis
特点
  • 优点:
    • 提供了高性能的分布式缓存和数据存储。
    • 支持多种数据结构和缓存策略。
    • 支持持久化存储和数据复制。
    • 提供了丰富的功能,如发布/订阅、事务等。
  • 缺点:
    • 相对于本地缓存实现,性能可能稍低。
支持数据类型

高级键值存储系统,支持多种数据类型,包括字符串(String)、哈希(Hash)、列表(List)、集合(Set)、有序集合(Sorted Set)等。这使得Redis可以存储和操作更复杂的数据结构。

适用场景
  • 需要高性能的分布式缓存和数据存储的场景。
  • 对缓存的持久化和数据复制有较高要求的场景。
  • 需要使用缓存以外的功能,如发布/订阅、事务等的场景。
使用示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public final class RedisUtil {

  @Autowired
  private RedisTemplate<String, Object> redisTemplate;

  // =============================common============================

  /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     */
  public boolean expire(String key, long time) {
    try {
      if (time > 0) {
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
  public long getExpire(String key) {
    return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  }


  /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
  public boolean hasKey(String key) {
    try {
      return redisTemplate.hasKey(key);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
  @SuppressWarnings("unchecked")
  public void del(String... key) {
    if (key != null && key.length > 0) {
      if (key.length == 1) {
        redisTemplate.delete(key[0]);
      } else {
        redisTemplate.delete(CollectionUtils.arrayToList(key));
      }
    }
  }


  // ============================String=============================

  /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
  public Object get(String key) {
    return key == null ? null : redisTemplate.opsForValue().get(key);
  }

  /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

  public boolean set(String key, Object value) {
    try {
      redisTemplate.opsForValue().set(key, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */

  public boolean set(String key, Object value, long time) {
    try {
      if (time > 0) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
      } else {
        set(key, value);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     */
  public long incr(String key, long delta) {
    if (delta < 0) {
      throw new RuntimeException("递增因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, delta);
  }


  /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     */
  public long decr(String key, long delta) {
    if (delta < 0) {
      throw new RuntimeException("递减因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, -delta);
  }


  // ================================Map=================================

  /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     */
  public Object hget(String key, String item) {
    return redisTemplate.opsForHash().get(key, item);
  }

  /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
  public Map<Object, Object> hmget(String key) {
    return redisTemplate.opsForHash().entries(key);
  }

  /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     */
  public boolean hmset(String key, Map<String, Object> map) {
    try {
      redisTemplate.opsForHash().putAll(key, map);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
  public boolean hmset(String key, Map<String, Object> map, long time) {
    try {
      redisTemplate.opsForHash().putAll(key, map);
      if (time > 0) {
        expire(key, time);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
  public boolean hset(String key, String item, Object value) {
    try {
      redisTemplate.opsForHash().put(key, item, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
  public boolean hset(String key, String item, Object value, long time) {
    try {
      redisTemplate.opsForHash().put(key, item, value);
      if (time > 0) {
        expire(key, time);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
  public void hdel(String key, Object... item) {
    redisTemplate.opsForHash().delete(key, item);
  }


  /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
  public boolean hHasKey(String key, String item) {
    return redisTemplate.opsForHash().hasKey(key, item);
  }


  /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     */
  public double hincr(String key, String item, double by) {
    return redisTemplate.opsForHash().increment(key, item, by);
  }


  /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     */
  public double hdecr(String key, String item, double by) {
    return redisTemplate.opsForHash().increment(key, item, -by);
  }


  // ============================set=============================

  /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     */
  public Set<Object> sGet(String key) {
    try {
      return redisTemplate.opsForSet().members(key);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }


  /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
  public boolean sHasKey(String key, Object value) {
    try {
      return redisTemplate.opsForSet().isMember(key, value);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
  public long sSet(String key, Object... values) {
    try {
      return redisTemplate.opsForSet().add(key, values);
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }


  /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
  public long sSetAndTime(String key, long time, Object... values) {
    try {
      Long count = redisTemplate.opsForSet().add(key, values);
      if (time > 0)
        expire(key, time);
      return count;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }


  /**
     * 获取set缓存的长度
     *
     * @param key 键
     */
  public long sGetSetSize(String key) {
    try {
      return redisTemplate.opsForSet().size(key);
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }


  /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */

  public long setRemove(String key, Object... values) {
    try {
      Long count = redisTemplate.opsForSet().remove(key, values);
      return count;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }

  // ===============================list=================================

  /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     */
  public List<Object> lGet(String key, long start, long end) {
    try {
      return redisTemplate.opsForList().range(key, start, end);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }


  /**
     * 获取list缓存的长度
     *
     * @param key 键
     */
  public long lGetListSize(String key) {
    try {
      return redisTemplate.opsForList().size(key);
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }


  /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     */
  public Object lGetIndex(String key, long index) {
    try {
      return redisTemplate.opsForList().index(key, index);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }


  /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     */
  public boolean lSet(String key, Object value) {
    try {
      redisTemplate.opsForList().rightPush(key, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
  public boolean lSet(String key, Object value, long time) {
    try {
      redisTemplate.opsForList().rightPush(key, value);
      if (time > 0)
        expire(key, time);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

  }


  /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
  public boolean lSet(String key, List<Object> value) {
    try {
      redisTemplate.opsForList().rightPushAll(key, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

  }


  /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
  public boolean lSet(String key, List<Object> value, long time) {
    try {
      redisTemplate.opsForList().rightPushAll(key, value);
      if (time > 0)
        expire(key, time);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

  public boolean lUpdateIndex(String key, long index, Object value) {
    try {
      redisTemplate.opsForList().set(key, index, value);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }


  /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */

  public long lRemove(String key, long count, Object value) {
    try {
      Long remove = redisTemplate.opsForList().remove(key, count, value);
      return remove;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }

  }

}

参考博客:

https://blog.csdn.net/qq_36433289/article/details/133018346

https://blog.csdn.net/Troub_cy/article/details/130873417

https://blog.csdn.net/weixin_46089066/article/details/110946131

https://blog.csdn.net/weixin_43549578/article/details/83756139

https://blog.csdn.net/le_17_4_6/article/details/117885675

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值