栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Redis帮助类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Redis帮助类

项目使用的为 spring框架

redis配置:

文件名:application.properties


 配置代码:

# Redis 配置
spring.redis.host=192.168.10.20
spring.redis.port=6379
spring.redis.database=105
spring.redis.password=CN66law123
spring.redis.timeout=5000ms

Redis帮助类代码:


@Component
public class RedisUtils {

    private final StringRedisTemplate redisTemplate;

    private final RedissonClient client;

    static final int RANDOM_CACHE_TIME_LEVEL_1 = 60;

    static final int RANDOM_CACHE_TIME_LEVEL_2 = 300;

    public RedisUtils(StringRedisTemplate redisTemplate, RedissonClient client) {
        this.redisTemplate = redisTemplate;
        this.client = client;
    }

    
    public  Map hashGetAll(String key, Class clazz) {
        var map = redisTemplate.opsForHash().entries(key);
        var res = new HashMap(map.size());
        if (map.isEmpty()) {
            return res;
        }
        map.forEach((k, v) -> {
            if (v instanceof String) {
                res.put(k.toString(), (T) v);
            } else {
                res.put(k.toString(), JsonUtils.parseObject(v.toString(), clazz));
            }
        });
        return res;
    }

    
    public  T hashGet(String key, String dataKey, Class clazz) {
        var value = redisTemplate.opsForHash().get(key, dataKey);
        if (value == null || StrUtil.isBlank(value.toString())) {
            return null;
        }
        return JsonUtils.parseObject(value.toString(), clazz);
    }

    
    public  void hashSetAll(String key, Map map, int cacheTime, boolean alwaysSetExpire, boolean appendRandomCacheTime) {
        var keyExists = redisTemplate.hasKey(key);
        Map strMap = new HashMap<>(map.size());
        map.forEach((k, v) -> strMap.put(k, JsonUtils.toJsonString(v)));
        redisTemplate.opsForHash().putAll(key, strMap);
        if (keyExists == null || !keyExists || alwaysSetExpire) {
            long cacheSeconds = appendRandomCacheTime(cacheTime, appendRandomCacheTime);
            redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS);
        }
    }

    
    public  void hashSet(String key, String dataKey, T t, int cacheTime, boolean alwaysSetExpire, boolean appendRandomCacheTime) {
        var json = JsonUtils.toJsonString(t);
        var keyExists = redisTemplate.hasKey(key);
        redisTemplate.opsForHash().put(key, dataKey, json);
        if (keyExists == null || !keyExists || alwaysSetExpire) {
            long cacheSeconds = appendRandomCacheTime(cacheTime, appendRandomCacheTime);
            redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS);
        }
    }

    
    public  void set(String key, T t, int cacheTime, boolean alwaysSetExpire, boolean appendRandomCacheTime) {
        var json = JsonUtils.toJsonString(t);
        var keyExists = redisTemplate.hasKey(key);
        redisTemplate.opsForValue().set(key, json);
        if (keyExists == null || !keyExists || alwaysSetExpire) {
            long cacheSeconds = appendRandomCacheTime(cacheTime, appendRandomCacheTime);
            redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS);
        }
    }

    
    public  T get(String key, Class clazz) {
        var value = redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(value)) {
            return null;
        }
        return JsonUtils.parseObject(value, clazz);
    }

    
    public Long increment(String key, Long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    
    public  void offerDelayQueue(String queueName, T t, Long delay, TimeUnit timeUnit) {
        RBlockingQueue blockingQueue = client.getBlockingQueue(queueName);
        RDelayedQueue delayedQueue = client.getDelayedQueue(blockingQueue);
        delayedQueue.offer(JsonUtils.toJsonString(t), delay, timeUnit);
    }

    
    public  T takeDelayQueue(String queueName, Class clazz) {
        RBlockingQueue blockingQueue = client.getBlockingQueue(queueName);
        client.getDelayedQueue(blockingQueue);
        try {
            if (blockingQueue.isEmpty()) {
                return null;
            }
            var data = blockingQueue.take();
            return JsonUtils.parseObject(data, clazz);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    
    public Boolean tryLock(String lockKey, TimeUnit timeUnit, long leaseTime, long waitTime) {
        RLock lock = client.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, timeUnit);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public Boolean isLocked(String lockKey) {
        RLock lock = client.getLock(lockKey);
        return lock.isLocked();
    }

    
    public void unLock(String lockKey) {
        RLock lock = client.getLock(lockKey);
        if (lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

    
    private long appendRandomCacheTime(int cacheTime, boolean appendRandomCacheTime) {
        long cacheSeconds = TimeoutUtils.toSeconds(cacheTime, TimeUnit.MINUTES);
        if (appendRandomCacheTime) {
            int min, max;
            if (cacheTime <= RANDOM_CACHE_TIME_LEVEL_1) {
                min = 6;
                max = 18;
            } else if (cacheTime <= RANDOM_CACHE_TIME_LEVEL_2) {
                min = 18;
                max = 60;
            } else {
                min = 60;
                max = 5 * 60;
            }
            cacheSeconds += RandomUtil.randomInt(min, max);
        }
        return cacheSeconds;
    }

     
    public  List multiGet(Collection key, Class clazz) {
        var list = redisTemplate.opsForValue().multiGet(key);
        if (list == null || list.size() <= 0) {
            return new ArrayList<>();
        }
        List res = new ArrayList<>();
        list.forEach(item -> {
            if (item != null) {
                res.add(JSONUtil.toBean(item, clazz));
            }
        });
        return res;
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/667301.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号