🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
在这里插入图片描述

SpringBoot整合Redis高阶用法:哨兵模式+分布式锁实战

一、引言

在当今的分布式系统开发中,Redis作为一款高性能的内存数据库,被广泛应用于缓存、消息队列、分布式锁等场景。而Spring Boot作为一款简化Spring应用开发的框架,与Redis的整合能够大大提高开发效率。本文将详细介绍Spring Boot整合Redis的高阶用法,包括哨兵模式的配置以及分布式锁的实战应用。

二、Redis哨兵模式简介

2.1 什么是哨兵模式

Redis哨兵模式是Redis官方提供的一种高可用解决方案。在主从复制的基础上,哨兵可以监控主从节点的状态,当主节点出现故障时,哨兵会自动将从节点提升为主节点,从而保证系统的高可用性。

2.2 哨兵模式的工作原理

  • 监控:哨兵会周期性地向所有Redis节点发送PING命令,检查节点是否存活。
  • 通知:当哨兵发现某个节点出现故障时,会通知其他哨兵和客户端。
  • 自动故障转移:当主节点出现故障时,哨兵会从从节点中选举一个新的主节点,并将其他从节点指向新的主节点。

三、Spring Boot整合Redis哨兵模式

3.1 环境准备

  • JDK 1.8及以上
  • Maven 3.x
  • Spring Boot 2.x
  • Redis 5.x及以上

3.2 创建Spring Boot项目

可以使用Spring Initializr(https://start.spring.io/)快速创建一个Spring Boot项目,添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
</dependencies>

3.3 配置Redis哨兵模式

在application.properties或application.yml中配置Redis哨兵模式:

spring:
  redis:
    sentinel:
      master: mymaster
      nodes: 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

3.4 编写Redis配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.HashSet;
import java.util.Set;

@Configuration
public class RedisConfig {

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
               .master("mymaster")
               .sentinels(new HashSet<>(Set.of("127.0.0.1:26379", "127.0.0.1:26380", "127.0.0.1:26381")));
        return new LettuceConnectionFactory(sentinelConfig);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

3.5 测试Redis连接

编写一个简单的测试类来验证Redis连接:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisTestService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void testRedis() {
        redisTemplate.opsForValue().set("testKey", "testValue");
        Object value = redisTemplate.opsForValue().get("testKey");
        System.out.println("Redis value: " + value);
    }
}

四、Redis分布式锁实战

4.1 为什么需要分布式锁

在分布式系统中,多个服务实例可能会同时访问共享资源,为了保证数据的一致性和完整性,需要使用分布式锁来控制对共享资源的访问。

4.2 Redis实现分布式锁的原理

Redis实现分布式锁主要是通过SETNX(SET if Not eXists)命令来实现的。当一个客户端尝试获取锁时,会向Redis发送SETNX命令,如果返回值为1,表示获取锁成功;如果返回值为0,表示锁已经被其他客户端持有。

4.3 基于RedisTemplate实现分布式锁

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisDistributedLock {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public boolean tryLock(String lockKey, String requestId, long expireTime) {
        return redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS);
    }

    public void unlock(String lockKey, String requestId) {
        if (requestId.equals(redisTemplate.opsForValue().get(lockKey))) {
            redisTemplate.delete(lockKey);
        }
    }
}

4.4 使用分布式锁的示例

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class DistributedLockService {

    @Autowired
    private RedisDistributedLock redisDistributedLock;

    public void doSomething() {
        String lockKey = "distributedLock";
        String requestId = UUID.randomUUID().toString();
        boolean locked = redisDistributedLock.tryLock(lockKey, requestId, 10);
        if (locked) {
            try {
                // 模拟业务逻辑
                System.out.println("获取到锁,开始执行业务逻辑");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                redisDistributedLock.unlock(lockKey, requestId);
                System.out.println("释放锁");
            }
        } else {
            System.out.println("未获取到锁");
        }
    }
}

五、总结

本文详细介绍了Spring Boot整合Redis哨兵模式的步骤,以及如何使用Redis实现分布式锁。通过哨兵模式,可以保证Redis的高可用性;通过分布式锁,可以解决分布式系统中的并发问题。希望本文能够对广大技术人员有所帮助。

更多推荐