基于redisson实现快速缓存

package com.*.servicecore;

import com.google.common.collect.*;
import org.redisson.api.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
/**
 * @desc redis缓存工具类
 * @author ly
 * @date 2019-05-20
 */
public final class RedisCacheService {

    /* 空值缓存时间5分钟 */
    private static final int NULL_VALUE_KEY_CACHE_MILLISECONDS = 5 * 60 * 1000;

    //分布式map集合
    private RMap rMap;

    //集合可缓存空值
    private RSetCache rSetCache;

    // redisson客户端
    private RedissonClient redisson;

    /** 批量操作选项 (目前redisson版本不支持)*/
    //private BatchOptions options = BatchOptions.defaults();

    // 是否有ttl控制
    private boolean ttlControl;

    //缓存名称
    private String cacheName;

    // 集合名称
    private String cacheSetName;

    // 是否缓存null值
    private boolean cacheNull;

    /**
     * 静态构造方法
     * @param redisson redisson客户端
     * @param cacheName 缓存名称
     * @param ttlControl 是否有缓存时间控制
     * @param cacheNull 是否缓存null
     * @return
     */
    public static RedisCacheService of(RedissonClient redisson, String cacheName,
                              boolean ttlControl, boolean cacheNull){
        return new RedisCacheService(redisson,cacheName,ttlControl,cacheNull);
    }

    private RedisCacheService(RedissonClient redisson, String cacheName,
                     boolean ttlControl, boolean cacheNull){
        this.redisson = redisson;
        this.cacheName = cacheName;
        this.cacheSetName = cacheName + "_null_value_key_set";
        if(ttlControl){
            //RMapCache继承RMap,并提供元素淘汰功能,根据过期时间清理过期缓存元素
            this.rMap = redisson.getMapCache(this.cacheName);
        }else {
            this.rMap = redisson.getMap(this.cacheName);
        }
        if(cacheNull){
            //RSetCache继承Set,并提供元素淘汰功能,根据过期时间清理过期缓存元素
            this.rSetCache = redisson.getSetCache(this.cacheSetName);
        }
        this.ttlControl = ttlControl;
        this.cacheNull = cacheNull;
    }

    /**
     * 判断是否存在key
     * @param key
     * @return
     */
    public boolean containsKey(Object key){
        boolean result = rMap.containsKey(key);
        if(!result && cacheNull){
            result = rSetCache.contains(key);
        }
        return result;
    }

    /**
     * 清除全部缓存
     */
    public void clear(){
        rMap.clear();
        if(cacheNull){
            rSetCache.clear();
        }
    }

    /**
     * 获取数据集合
     * @param key
     * @return
     */
    public Map get(Object key){
        Map map = Maps.newHashMapWithExpectedSize(1);
        Object result = rMap.get(key);
        if((result == null && cacheNull && rSetCache.contains(key)) || result != null){
            map.put(key,result);
        }
        return map;
    }

    /**
     * 存入map
     * @param key
     * @param value
     * @return
     */
    public Object put(Object key,Object value){
        if(value == null){
            if(cacheNull){
                rSetCache.add(key,NULL_VALUE_KEY_CACHE_MILLISECONDS, TimeUnit.MILLISECONDS);
            }
        }else {
            rMap.put(key,value);
        }
        return value;
    }

    /**
     * 移除缓存元素
     * @param key
     * @return
     */
    public Object remove(Object key){
        Object o = rMap.remove(key);
        if(cacheNull){
            rSetCache.remove(key);
        }
        return o;
    }

    /**
     * 批量存储
     *
     * @param map
     */
    /*public void putAll(Map map) {
        RBatch batch = redisson.createBatch(options);
        RMapAsync mapCache = ttlControl ? batch.getMapCache(this.cacheName) : batch
                .getMap(this.cacheName);
        RSetCacheAsync setCache = batch.getSetCache(this.cacheSetName);
        Set<Map.Entry> entrySet = map.entrySet();
        Iterator<Map.Entry> it = entrySet.iterator();
        while (it.hasNext()) {
            Map.Entry e = it.next();
            if (e.getValue() == null) {
                if (cacheNull) {// 缓存null
                    setCache.addAsync(e.getKey(),
                            NULL_VALUE_KEY_CACHE_MILLISECONDS,
                            TimeUnit.MILLISECONDS);
                }
            } else {
                mapCache.putAsync(e.getKey(), e.getValue());
            }
        }
        batch.execute();
    }*/

    /**
     * 根据键值获取缓存集合
     * @param keys
     * @return
     */
    public Map getAll(Set keys) {
        Map map = rMap.getAll(keys);
        if (keys.size() == map.size()) {
            return map;
        } else if (cacheNull) {
            Set set = rSetCache.readAll();
            for (Object key : keys) {
                if (!map.containsKey(key) && set.contains(key)) {
                    map.put(key, null);
                }
            }
        }
        return map;
    }

    /**
     * 根据key批量移除缓存
     * @param keys
     * @return
     */
    public long fastRemove(Object... keys) {
        long result = rMap.fastRemove(keys);
        if (cacheNull) {
            rSetCache.removeAll(Sets.newHashSet(keys));
        }
        return result;
    }

    /**
     * 快速存
     * @param key
     * @param value
     * @return
     */
    public boolean fastPut(Object key, Object value) {
        boolean result = true;
        if (value != null) {
            result = rMap.fastPut(key, value);
        } else if (cacheNull) {
            result = rSetCache.add(key, NULL_VALUE_KEY_CACHE_MILLISECONDS,
                    TimeUnit.MILLISECONDS);
        }
        return result;
    }

    /**
     * 带过期时间存
     * @param key
     * @param value
     * @param ttl 单位毫秒
     * @return
     */
    public Object put(Object key, Object value, long ttl) {
        if(ttl <= 0){
            return put(key, value);
        }
        if (value != null) {
            if (ttlControl) {
                ((RMapCache) rMap).put(key, value, ttl, TimeUnit.MILLISECONDS);
            } else {
                throw new IllegalArgumentException("can not support ttl");
            }
        } else if (cacheNull) {
            rSetCache.add(key, NULL_VALUE_KEY_CACHE_MILLISECONDS,
                    TimeUnit.MILLISECONDS);
        }
        return value;
    }

    /**
     * 带过期时间的putAll
     *
     * @param map
     * @param ttl
     */
    /*public void putAll(Map map, long ttl) {
        if(ttl <= 0){
            putAll(map);
            return;
        }
        RBatch batch = redisson.createBatch(options);
        RMapCacheAsync rMapCache = batch.getMapCache(this.cacheName);
        Set<Map.Entry> entrySet = map.entrySet();
        Iterator<Map.Entry> it = entrySet.iterator();
        while (it.hasNext()) {
            Map.Entry e = it.next();
            if (e.getValue() != null) {
                if (ttlControl) {
                    rMapCache.putAsync(e.getKey(), e.getValue(), ttl,
                            TimeUnit.MILLISECONDS);
                } else {
                    throw new IllegalArgumentException("can not support ttl");
                }
            } else if (cacheNull) {
                rSet.add(e.getKey(), NULL_VALUE_KEY_CACHE_MILLISECONDS,
                        TimeUnit.MILLISECONDS);
            }
        }
        // 批量操作
        batch.execute();
    }*/

    /**
     * 带过期时间快速存
     * @param key
     * @param value
     * @param ttl
     * @return
     */
    public boolean fastPut(Object key, Object value, long ttl) {
        boolean result = true;
        if (value != null) {
            if (ttlControl) {
                result = ((RMapCache) rMap).fastPut(key, value, ttl,
                        TimeUnit.MILLISECONDS);
            } else {
                throw new IllegalArgumentException("can not support ttl");
            }
        } else if (cacheNull) {
            rSetCache.add(key, NULL_VALUE_KEY_CACHE_MILLISECONDS,
                    TimeUnit.MILLISECONDS);
        }
        return result;
    }

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Redisson可以很方便地实现数据缓存Redisson是一个基于Redis的Java客户端,它提供了丰富的功能和API,包括分布式锁、分布式集合、分布式对象等。在使用Redisson实现数据缓存时,可以通过以下步骤进行操作: 1. 引入Redisson的依赖并配置Redis连接信息。 2. 创建RedissonClient对象,该对象是Redisson的核心组件,用于与Redis进行通信。 3. 使用Redisson提供的分布式锁功能,可以通过调用tryLock方法来加锁,该方法会返回一个布尔值表示是否成功获取到锁。在加锁时,可以设置锁的过期时间,以防止锁被长时间占用。 4. 在获取到锁之后,可以从缓存中读取数据。如果缓存中不存在所需的数据,可以从数据库或其他数据源中获取,并将数据存入缓存中。 5. 在数据更新或删除时,需要先获取到锁,然后进行相应的操作,并更新缓存。 6. 在操作完成后,需要释放锁,以便其他线程或进程可以获取到锁并进行操作。 通过以上步骤,可以利用Redisson实现数据缓存,并保证数据的一致性和并发安全性。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [分布式锁Redisson快速入门及利用AOP实现声明式缓存](https://blog.csdn.net/weixin_44743245/article/details/120805755)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [redisson做分布式缓存(加锁方面)](https://blog.csdn.net/weixin_55034383/article/details/129333680)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值