当前位置: 代码网 > it编程>数据库>Redis > Redis框架在项目中的实战

Redis框架在项目中的实战

2026年02月10日 Redis 我要评论
一、redis 哨兵模式(redis sentinel)redis sentinel 是 redis 官方提供的高可用解决方案,核心作用是监控 redis 主从集群、自动完成主从切换、通知客户端主节点

一、redis 哨兵模式(redis sentinel)

redis sentinel 是 redis 官方提供的高可用解决方案,核心作用是监控 redis 主从集群、自动完成主从切换、通知客户端主节点变更,解决单机 redis 宕机后无法自动恢复的问题。

lettuce 是一款高性能、异步非阻塞的 redis 客户端,基于 netty 框架开发,也是 spring boot 2.x 及以上版本默认的 redis 客户端客户端(lettuce)只需配置哨兵节点地址和主节点名称,无需知道主从节点的具体地址,哨兵会自动告知客户端当前的主节点。

二、lettuce 和redission 如何选择

在实际项目中,lettuce 和 redisson 是互补使用的 ——lettuce 作为底层高性能 redis 客户端负责基础通信,redisson 基于 lettuce 封装了丰富的分布式数据结构和服务(如分布式锁、分布式 map),既发挥 lettuce 的性能优势,又利用 redisson 简化业务开发。

  1. 依赖引入(pom.xml)
<!-- spring boot 整合 redis(默认内置 lettuce) -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>

<!-- redisson 核心依赖(适配 spring boot) -->
<dependency>
    <groupid>org.redisson</groupid>
    <artifactid>redisson-spring-boot-starter</artifactid>
    <version>3.23.0</version> <!-- 选稳定版本 -->
</dependency>
  • 配置文件:
redis.lettuce.client.enable=true # 启用lettuce客户端
# 连接池配置(核心)
redis.lettuce.client.pool.minidle=6 # 最小空闲连接(保活)
redis.lettuce.client.pool.maxidle=21 # 最大空闲连接
redis.lettuce.client.pool.maxtotal=100 # 最大连接数
redis.lettuce.client.pool.maxwaitmillis=4000 # 最大等待时间
redis.lettuce.client.sentinel.mastername=master # 监控的主节点名称
redis.lettuce.client.sentinel.password=***
redis.lettuce.client.sentinel.database=0
redis.lettuce.client.sentinel.nodeinfo[0]=10.193.114.0:26379 # 哨兵节点列表
redis.lettuce.client.sentinel.nodeinfo[0]=10.193.114.2:26379 # 哨兵节点列表
redis.lettuce.client.sentinel.nodeinfo[0]=10.193.114.3:26379 # 哨兵节点列表

三、代码示例

场景 1:用 lettuce 做基础缓存读写(spring redistemplate)
spring data redis 封装了 lettuce,提供 redistemplate 简化操作,这是项目中最基础的用法:

@component
public class cacheservice {
    // 注入 spring 封装的 redistemplate(底层是 lettuce)
    @resource
    private redistemplate<string, object> redistemplate;

    // 存储合约基础信息(string 类型)
    public void settestinfo(string testkey, object testinfo) {
        // 底层通过 lettuce 发送 set 命令到 redis 哨兵集群
        redistemplate.opsforvalue().set(
            testkey, 
            testinfo, 
            1, // 过期时间 1 小时
            timeunit.hours
        );
    }

    public object gettestinfo(string testkey) {
        // 底层通过 lettuce 发送 get 命令
        return redistemplate.opsforvalue().get(testkey);
    }

    // 异步操作(lettuce 核心优势,高并发场景用)
    public void settestinfoasync(string testkey, object testinfo) {
        // 异步设置,不阻塞主线程(高并发场景推荐)
        redistemplate.opsforvalue().setasync(testkey, testinfo);
    }
}

场景 2:用 redisson 操作分布式 map(对应你的 info:test_key)
redisson 封装的 rmap 是分布式 map,比 lettuce 的 hash 更易用,支持自动序列化 / 反序列化:

@component
public class testmapservice {
    // 注入 redissonclient(底层复用 lettuce 连接)
    @resource
    private redissonclient redissonclient;

    // 批量存储合约信息到分布式 map
    public void batchsavetestinfo(list<testinfopo> testlist) {
        // 获取 redis 中的分布式 map(info:test_key)
        rmap<string, testinfopo> testmap = 
            redissonclient.getmap("info:test_key");
        
        // 批量存入:info:test_key
        testlist.foreach(d -> {
            string key = ...
            testmap.put(key, d); // 原子操作,线程安全
        });
    }

    // 获取单个test信息
    public testinfopo gettestinfo(string testid) {
        rmap<string, testinfopo> testmap = redissonclient.getmap("info:test_key");
        string key = ...;
        return testmap.get(key);
    }
}

场景 3:用 redisson 实现分布式锁(防并发修改)

@component
public class updateservice {
    @resource
    private redissonclient redissonclient;

    // 修改(加分布式锁)
    public void updatetestinfo(string testtid, testinfopo newinfo) {
        // 1. 定义锁的唯一标识
        string lockkey = "lock:test:update:" + testid;
        rlock lock = redissonclient.getlock(lockkey);

        try {
            // 2. 获取锁:最多等5秒,持有锁10秒(自动释放,防止死锁)
            boolean locked = lock.trylock(5, 10, timeunit.seconds);
            if (!locked) {
                throw new runtimeexception("正在修改中,请稍后重试");
            }

            // 3. 执行业务逻辑
            // ... 你的更新数据库/缓存逻辑 ...

        } catch (interruptedexception e) {
            thread.currentthread().interrupt();
            throw new runtimeexception("获取锁失败", e);
        } finally {
            // 4. 释放锁(必须在 finally 中,防止锁泄露)
            if (lock.isheldbycurrentthread()) {
                lock.unlock();
            }
        }
    }
}

四、项目中的最佳实践

  1. 分工明确:简单的缓存读写(string/hash)用 redistemplate(底层 lettuce);
  2. 分布式锁、分布式集合、延迟队列等复杂场景用 redisson;
  3. 复用连接池:让 redisson 复用 lettuce 的连接池配置,避免重复创建连接;
  4. 异步优先:高并发场景(如期货行情缓存)用 lettuce 的异步 api(setasync/getasync),提升吞吐量;
  5. 锁的规范:分布式锁必须设置超时时间,且在 finally 中释放,防止死锁;
  6. 序列化配置:统一配置 redistemplate 的序列化方式(如 jackson2jsonredisserializer),避免乱码:
@configuration
public class redisconfig {
    @bean
    public redistemplate<string, object> redistemplate(redisconnectionfactory factory) {
        redistemplate<string, object> template = new redistemplate<>();
        template.setconnectionfactory(factory);
        // 设置 json 序列化器
        jackson2jsonredisserializer<object> serializer = new jackson2jsonredisserializer<>(object.class);
        template.setvalueserializer(serializer);
        template.setkeyserializer(new stringredisserializer());
        template.afterpropertiesset();
        return template;
    }
}

到此这篇关于redis框架在项目中的实战的文章就介绍到这了,更多相关redis框架项目应用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com