zoukankan      html  css  js  c++  java
  • springboot 之redis 分布式锁

    工具类如下:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.RedisSerializer;
    import org.springframework.stereotype.Component;
    import redis.clients.jedis.Protocol;
    import redis.clients.util.SafeEncoder;
    
    import java.io.Serializable;
    
    
    @Component
    public class RedisUtils {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        public RedisTemplate getRedisTemplate() {
            return this.redisTemplate;
        }
    
        /**
         * 设置redis分布式锁
         * @param key
         * @param value
         * @param expire 锁过期时间
         * @return
         */
        public boolean tryLock(final String key, final Serializable value, final long expire){
            boolean isSuccess = (boolean) redisTemplate.execute((RedisCallback) connection -> {
                RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
                RedisSerializer keySerializer = redisTemplate.getKeySerializer();
                Object object = connection.execute("set",keySerializer.serialize(key),valueSerializer.serialize(value), SafeEncoder.encode("NX"),SafeEncoder.encode("EX"), Protocol.toByteArray(expire));
                return null != object;
            });
            return isSuccess;
        }
      //释放锁
        public boolean releaseLock(String key){
            return  redisTemplate.delete(key);
        }
    
    }
  • 相关阅读:
    136. 只出现一次的数字
    Eclipse Git Pull报 cannot open git-upload-pack错误的解决方案
    数据结构和算法1 稀疏数组
    Netty学习二 TCP粘包拆包以及Netty解决TCP粘包拆包
    Java值传递和引用传递
    Git命令教程
    Properties文件载入工具类
    有序的properties的工具类
    对象操作工具类
    反射工具类
  • 原文地址:https://www.cnblogs.com/ywjfx/p/12100817.html
Copyright © 2011-2022 走看看