用 spring中的 redis 模板类(StringRedisTemplate)设计分布式锁(三)

上两篇介绍了两种 redis 分布式锁,均是redis 自己类库实现的,而今天这种redis 分布式锁,是spring 封装的redis 模板类,开箱即用简单方便。

1、工具类如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Component
public class RedisUtil {

  
    private static final String key = "nandao";
    private static final String value = "123456";

    private static final long EXPIRE = 60000;

    @Resource
    private StringRedisTemplate redisTemplate;//这就是redis 模板类,依赖注入到这里。

    //加锁核心方法
    public  boolean tryLock(String key,String value){
        try{
               //先加锁,然后设置超时时间,
            if (redisTemplate.opsForValue().setIfAbsent(key, value)) {
                redisTemplate.expire(key,EXPIRE,TimeUnit.MILLISECONDS);
                return true;
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return false;
    }

    public void releaseLock(){
        try {
            redisTemplate.opsForValue().getOperations().delete(key);//这里释放锁
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

 

2、这种分布式锁,底层原理和前两篇类似,可以根据不同的业务场景选择不同的方式去实现,没有最好的方案,只有最合适的;同时,如果有需要,小伙伴在使用过程中,可以继续修改优化,万变不离其宗!!!!以后有时间我会和大家,解析这是锁实现的源码和原理,让大家有个更深入的理解,敬请期待!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring Boot 使用 Redis 实现分布式锁,你可以按照以下步骤进行: 1. 添加 Redis 依赖 在 `pom.xml` 文件添加 Redis 相关的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置 Redis 连接 在 `application.properties` 或 `application.yml` 文件配置 Redis 连接信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 创建分布式锁工具类 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Component public class RedisDistributedLock { @Autowired private RedisTemplate<String, String> redisTemplate; public boolean lock(String lockKey, String requestId, long expireTime) { Boolean success = redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.MILLISECONDS); return success != null && success; } public boolean releaseLock(String lockKey, String requestId) { String value = redisTemplate.opsForValue().get(lockKey); if (value != null && value.equals(requestId)) { return redisTemplate.delete(lockKey); } return false; } } ``` 4. 在需要加锁的地方使用分布式锁 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/example") public class ExampleController { @Autowired private RedisDistributedLock distributedLock; @GetMapping("/lock") public String lockExample() { String lockKey = "exampleLock"; String requestId = UUID.randomUUID().toString(); long expireTime = 5000; // 锁的过期时间,单位为毫秒 // 尝试获取锁 boolean lockSuccess = distributedLock.lock(lockKey, requestId, expireTime); if (lockSuccess) { try { // 执行业务逻辑 Thread.sleep(2000); return "Success"; } catch (InterruptedException e) { e.printStackTrace(); } finally { // 释放锁 distributedLock.releaseLock(lockKey, requestId); } } return "Failed"; } } ``` 在上述代码,首先创建了一个 `RedisDistributedLock` 的工具类,用来进行锁的获取和释放操作。然后,在需要加锁的地方调用 `lock()` 方法尝试获取锁,如果获取成功,则执行业务逻辑;最后,在业务逻辑执行完成后,调用 `releaseLock()` 方法释放锁。 注意:在上述示例,使用了 `RedisTemplate` 作为 Redis 的操作模板,你可以根据实际情况进行调整和优化。另外,还可以对分布式锁进行进一步的优化,例如使用 Lua 脚本实现原子性操作等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

寅灯

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值