• 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);
        }
    
    }
  • 相关阅读:
    【Oracle 12c】最新CUUG OCP-071考试题库(58题)
    【Oracle 12c】最新CUUG OCP-071考试题库(57题)
    【Oracle 12c】最新CUUG OCP-071考试题库(56题)
    【Oracle 12c】最新CUUG OCP-071考试题库(55题)
    voip,
    处理xmpp 离线信息,
    流程,xmpp发送信息,
    折腾我几天的 消息状态,
    三者的区别,
    bundle,
  • 原文地址:https://www.cnblogs.com/ywjfx/p/12100817.html
Copyright © 2020-2023  润新知