工具类如下:

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);
    }

}

相关文章:

  • 2018-12-09
  • 2022-12-23
  • 2021-07-09
  • 2021-04-11
  • 2019-02-11
  • 2021-08-16
  • 2022-12-23
  • 2021-05-29
猜你喜欢
  • 2021-01-18
  • 2019-06-29
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案