SpringBoot中使用Redis分布式锁

1 篇文章 0 订阅
1 篇文章 0 订阅

在现代的分布式系统中,为了保证数据的一致性和并发性,我们经常需要使用分布式锁。而Redis则是一个高性能的内存数据库,非常适合作为分布式锁的存储介质。本文将介绍如何在SpringBoot项目中使用Redis实现分布式锁。

1. 引入依赖

首先,我们需要在项目的pom.xml文件中添加Redis和SpringBoot相关的依赖:

<dependencies>
    <!-- Spring Boot Starter Data Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. 配置Redis

接下来,我们需要在application.propertiesapplication.yml文件中配置Redis连接信息:

spring:
  redis:
    host: localhost
    port: 6379

3. 创建Redis分布式锁工具类

为了方便使用,我们可以创建一个名为RedisLockUtil的工具类,用于封装Redis分布式锁的操作:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLockUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 加锁
     * @param key 锁的key
     * @param value 锁的value
     * @param timeout 锁的超时时间,单位为毫秒
     * @return 是否成功获取锁
     */
    public boolean lock(String key, String value, long timeout) {
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, value);
        if (result != null && result) {
            stringRedisTemplate.expire(key, timeout, TimeUnit.MILLISECONDS);
            return true;
        }
        return false;
    }
    /**
     * 解锁
     * @param key 锁的key
     * @param value 锁的value
     * @return 是否成功释放锁
     */
    public boolean unlock(String key, String value) {
        String currentValue = stringRedisTemplate.opsForValue().get(key);
        if (currentValue != null && currentValue.equals(value)) {
            return stringRedisTemplate.delete(key);
        }
        return false;
    }
}

4. 使用分布式锁

现在我们可以在需要使用分布式锁的地方调用RedisLockUtil类的lockunlock方法了。例如,我们可以在一个定时任务中使用分布式锁来保证任务的幂等性:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
@Component
public class MyTask {
    @Resource
    private RedisLockUtil redisLockUtil;
    @Scheduled(cron = "0/5 * * * * ?") // 每5秒执行一次
    public void execute() {
        String lockKey = "my_task_lock";
        String lockValue = "lock_value";
        long lockTimeout = 5000; // 锁的超时时间为5秒
        if (redisLockUtil.lock(lockKey, lockValue, lockTimeout)) {
            try {
                // 执行任务逻辑
                System.out.println("执行任务");
            } finally {
                redisLockUtil.unlock(lockKey, lockValue);
            }
        } else {
            System.out.println("无法获取锁,跳过本次任务");
        }
    }
}

通过以上代码,我们实现了一个简单的基于Redis的分布式锁。当然,实际应用中可能需要考虑更多的细节,如锁的续命、锁的粒度等。希望这篇文章能帮助你入门SpringBoot中使用Redis分布式锁。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值