Spring Boot使用Redis实现分布式锁

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

一、环境准备

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

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

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

    org.springframework.boot spring-boot-starter-data-redis io.lettuce.core lettuce-core

二、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";
    }
}
​
相关推荐
李白客4 小时前
分布式集群与数据库产业:从单机到集群的架构跃迁与市场重构
数据库·分布式·架构
传感器与混合集成电路4 小时前
储气库漏失检测技术解析:分布式光纤如何锁定环空窜漏的精确位置
分布式·数据分析·信号处理
福大大架构师每日一题5 小时前
Redis 8.10.0 正式发布:紧凑哈希、批量导入、备份恢复、流与时序能力全面升级
数据库·redis·哈希算法
祈禾7 小时前
Redis三大特殊数据类型
运维·服务器·数据库·redis·笔记·缓存
cfm_29147 小时前
了解Sentinel
分布式·架构·sentinel
y = xⁿ7 小时前
一文掌握Redis常见八股
数据库·redis·缓存
上海云盾-小余7 小时前
全域网络安全防护思路:借助分布式节点抵御异常访问实战
分布式·安全·web安全
山荷枝7 小时前
04-框架--SpringBoot
java·spring boot·后端
用户31268748772010 小时前
你的配置真的绑定上了吗?Spring Boot @ConfigurationProperties 全链路拆解
spring boot
2601_9638702210 小时前
【计算机毕业设计】基于Spring Boot+Vue的高考志愿填报系统的设计与实现
spring boot·课程设计·高考