springboot redis分布式锁代码实例

这篇文章主要介绍了springboot redis分布式锁代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

随着微服务等分布式架构的快速发展及应用,在很多情况下,我们都会遇到在并发情况下多个线程竞争资源的情况,比如我们耳熟能详的秒杀活动,多平台多用户对同一个资源进行操作等场景等。分布式锁的实现方式有很多种,比如基于数据库、Zookeeper、Redis等,本文我们主要介绍Spring Boot整合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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

相关文章

今天小编给大家分享的是Springboot下使用Redis管道(pipeline...
本篇文章和大家了解一下springBoot项目常用目录有哪些。有一...
本篇文章和大家了解一下Springboot自带线程池怎么实现。有一...
这篇文章主要介绍了SpringBoot读取yml文件有哪几种方式,具有...
今天小编给大家分享的是SpringBoot配置Controller实现Web请求...
本篇文章和大家了解一下SpringBoot实现PDF添加水印的方法。有...