栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot redis分布式锁代码实例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135676.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号