springboot redis分布式锁代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot redis分布式锁代码实例

  2021-04-02 我要评论

这篇文章主要介绍了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);
  }
}
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们