scala+redis实现分布式锁

本文详细介绍如何使用Redis的单例模式特性实现分布式锁,包括锁的获取与释放过程,并提供了具体的Scala代码实现。此外,还展示了如何在实际业务场景中调用分布式锁,确保并发操作的一致性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、redis的底层是单例模式,意思是同一个脚本同一时刻只能有一个线程来执行,利用redis的这个特性来实现分布式锁。

   首先实现工具类

package utils

import CacheManager

/**
  * redis分布式锁
  */
object RedisTool {

  //加锁是否成功标志
  val LOCK_SUCCESS:String = "OK"

  //即当key不存在时,我们进行set操作;若key已经存在,则不做任何操作;
  val SET_IF_NOT_EXIST:String = "NX"

  //意思是我们要给这个key加一个过期的设置,具体时间由第五个参数决定。
  val SET_WITH_EXPIRE_TIME:String = "PX"

  val RELEASE_SUCCESS:String = "1"

  /**
    *
    * @param lockKey      锁
    * @param requestId    请求标识
    * @param expireTime   超期时间
    * @param isPersist    临时缓存或者永久缓存
    */
  def tryGetDistributedLock(lockKey:String, requestId:String, expireTime:Int,isPersist:Boolean=false){
    CacheManager.redisClientPool.withClient(
      client => {
        //val redisKeyPrefix = CacheManager.getRedisKeyPrefix(isPersist)
        client.select(CacheManager.redisDBNum)
        val result = client.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime)
        var flag = false
        if(LOCK_SUCCESS == result){
          flag = true
        }
        flag
      }
    )
  }


 /**
    *释放分布式锁
    * @param lockKey      锁
    * @param requestId    请求标识
    * @param expireTime   超期时间
    * @param isPersist    临时缓存或者永久缓存
    * @return
    */
  def releaseDistributedLock(lockKey:String, requestId:String,expireTime: Int = 10,isPersist:Boolean=false) ={
    CacheManager.redisClientPool.withClient(
      client => {
        val redisKeyPrefix = CacheManager.getRedisKeyPrefix(isPersist)
        client.select(CacheManager.redisDBNum)
        //lua脚本也是单例模式,同样也可以保证同一时刻只有一个线程执行脚本
        val lua =
          s"""
             |local current = redis.call('incrBy',KEYS[1],ARGV[1]);
             |if current == tonumber(ARGV[1]) then
             |    local t = redis.call('ttl',KEYS[1]);
             |    if t == -1 then
             |        redis.call('expire',KEYS[1],ARGV[2])
             |    end;
             |end;
             |return current;
           """.stripMargin
        val code = client.scriptLoad(lua).get
        val ret = client.evalSHA(code, List(redisKeyPrefix + lockKey),List(requestId,expireTime))
        val result = ret.get.asInstanceOf[Object].toString
        var flag = false
        if(result == RELEASE_SUCCESS){
          flag = true
        }
        flag
      }
    )
  }

}

2、实现CacheManager类

package utils

import com.redis.RedisClientPool
/**
  * 
  */
object CacheManager {

  val redisClientPool = "dev".equalsIgnoreCase(System.getenv("SCALA_ENV")) match {
    //开发环境
    case true => new RedisClientPool("127.0.0.1", 6379)
    //其他环境
    case false => new RedisClientPool("10.180.x.y", 6379, 8, 0, Some("root"))
  }

  val redisDBNum = 10

  def getRedisKeyPrefix(isPersist:Boolean) ={
    if(isPersist){
      //永久缓存前缀
      "persist_"
    }else{
      //临时缓存前缀
      "tmp_"
    }
  }

}

3、调用锁操作

def updateTableInfo(param:String) = {
    var resMap = Map[String,Any]()
    val lockKey = "mdms.MdmsUtils.updateTableInfo"
    //val requestId = UUID.randomUUID().toString().replace("-", "").toUpperCase()
    val flag = RedisTool.releaseDistributedLock(lockKey, "1")
    if(flag){
      try{
        
        //执行你的操作
        resMap = Map("code" -> 200 ,"msg" -> "成功")
      }catch {
        case e:Exception => {
          
          e.printStackTrace()
          resMap = Map("code" -> 200101 ,"msg" -> "执行失败")
        }
      }
      
    }else{
      resMap = Map("code" -> 200102 ,"msg" -> "操作冲突,已经被其他人捷足先登啦。")
    }
    resMap
  }

推荐一个公众号

号主为一线大厂架构师,CSDN博客专家,博客访问量突破一千万。主要分享Java、golang架构,源码,分布式,高并发等技术,用大厂程序员的视角来探讨技术进阶、面试指南、职业规划等。15W技术人的选择!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张音乐

请我喝杯咖啡吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值