工具类如下:
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); } }