美文网首页初见
J2Cache调用Redis的setnx和getset

J2Cache调用Redis的setnx和getset

作者: 可乐ZClyde | 来源:发表于2019-03-11 11:04 被阅读0次
    private CacheChannel cacheChannel = SpringUtil.getBean(CacheChannel.class);
    private static class Holder {
            private static J2CacheUtils single = new J2CacheUtils();
    }
    public static CacheProvider getL2Provider() {
            return Holder.single.cacheChannel.getL2Provider();
    }
    
    public static boolean setNxWithL2Redis(String region, String key, String val) {
            CacheProvider provider = getL2Provider();
            if (provider instanceof RedisCacheProvider) {
                RedisCacheProvider redisCacheProvider = (RedisCacheProvider) provider;
                RedisClient redisClient = redisCacheProvider.getRedisClient();
                Long result = redisClient.get().setnx((region + ":" + key).getBytes(), val.getBytes());
                return result == 0 ? false : true;
            } else {
                throw new RuntimeException("L2缓存不是Redis");
            }
    }
    
    public static String getSetWithL2Redis(String region, String key, String val) {
            CacheProvider provider = getL2Provider();
            if (provider instanceof RedisCacheProvider) {
                RedisCacheProvider redisCacheProvider = (RedisCacheProvider) provider;
                RedisClient redisClient = redisCacheProvider.getRedisClient();
                byte[] result = redisClient.get().getSet((region + ":" + key).getBytes(), val.getBytes());
                return new String(result);
            } else {
                throw new RuntimeException("L2缓存不是Redis");
            }
    }
    

    相关文章

      网友评论

        本文标题:J2Cache调用Redis的setnx和getset

        本文链接:https://www.haomeiwen.com/subject/uzcvpqtx.html