Spring Boot使用Redis实现分布式锁

在分布式系统中,分布式锁是一种解决并发问题的常用技术。Redis由于其高性能和丰富的特性,成为实现分布式锁的理想选择。本文将详细介绍如何在Spring Boot应用中使用Redis实现分布式锁。

一、环境准备

  1. 安装Redis:确保已经安装并运行Redis服务。

  2. Spring Boot项目:确保已经创建并配置好了Spring Boot项目。

  3. 添加依赖 :在 pom.xml中添加Spring Data Redis和Lettuce依赖。

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> </dependency> ​

二、Redis配置

application.propertiesapplication.yml文件中配置Redis连接信息。

复制代码
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword # 如果Redis设置了密码
​

三、实现分布式锁

1. 创建Redis配置类
复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@Configuration
public class RedisConfig {

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        return new StringRedisTemplate(factory);
    }

    @Bean
    public ValueOperations<String, String> valueOperations(StringRedisTemplate stringRedisTemplate) {
        return stringRedisTemplate.opsForValue();
    }
}
​
2. 创建分布式锁工具类
复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {

    @Autowired
    private ValueOperations<String, String> valueOperations;

    private static final long LOCK_EXPIRE = 30L; // 锁过期时间,30秒
    private static final String LOCK_VALUE = "LOCKED";

    public boolean lock(String key) {
        Boolean success = valueOperations.setIfAbsent(key, LOCK_VALUE, LOCK_EXPIRE, TimeUnit.SECONDS);
        return success != null && success;
    }

    public void unlock(String key) {
        valueOperations.getOperations().delete(key);
    }
}
​
3. 使用分布式锁
复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LockController {

    @Autowired
    private RedisLock redisLock;

    @GetMapping("/lock")
    public String lock() {
        String key = "myLock";
        if (redisLock.lock(key)) {
            try {
                // 业务逻辑
                Thread.sleep(2000); // 模拟业务处理时间
                return "Locked and processed";
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                redisLock.unlock(key);
            }
        } else {
            return "Failed to acquire lock";
        }
        return "Unexpected error";
    }
}
​
相关推荐
whltaoin39 分钟前
【JAVA全栈项目】弧图图-智能图床SpringBoot+MySQL API接口结合Redis+Caffeine多级缓存实践解析
java·redis·spring·缓存·caffeine·多级缓存
一 乐1 小时前
医疗管理|医院医疗管理系统|基于springboot+vue医疗管理系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·医疗管理系统
EllenShen1231 小时前
(Azure)PGSQL和redis 连通性测试 --code 备份
redis·postgresql·azure
华仔啊1 小时前
SpringBoot 2.x 和 3.x 的核心区别,这些变化你必须知道
java·spring boot·后端
不见长安在1 小时前
分布式ID
java·分布式·分布式id
qq_316837752 小时前
jmeter 分布式压测
分布式·jmeter
西岭千秋雪_4 小时前
Zookeeper实现分布式锁
java·分布式·后端·zookeeper·wpf
毕设源码-钟学长7 小时前
【开题答辩全过程】以 分布式菌菇销售系统为例,包含答辩的问题和答案
分布式
2401_837088508 小时前
stringRedisTemplate.opsForHash().entries
java·redis
爱敲键盘的猴子10 小时前
Redis内存回收,缓存问题
redis