通过Lettuce实现PB3格式对象在Redis中的存储与查询

1. Java实现代码(Lettuce客户端)

java 复制代码
import io.lettuce.core.RedisURI;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.sync.RedisCommands;
import com.google.protobuf.InvalidProtocolBufferException;
import your.package.UserPB; // 替换为您的PB3生成类

public class RedisStorage {
    private static final String HOST = "your-redis-host";
    private static final int PORT = 6379;
    private static final String PASSWORD = "your-password";
    private static final int DATABASE = 0;

    public static void main(String[] args) throws InvalidProtocolBufferException {
        // 创建Redis连接
        RedisURI uri = RedisURI.builder()
                .withHost(HOST)
                .withPort(PORT)
                .withPassword(PASSWORD.toCharArray())
                .withDatabase(DATABASE)
                .build();

        RedisClient client = RedisClient.create(uri);
        StatefulRedisConnection<String, byte[]> connection = client.connect(new PB3RedisCodec());
        RedisCommands<String, byte[]> sync = connection.sync();
            
            // 创建PB3对象
            UserPB.User user = UserPB.User.newBuilder()
                    .setId(1)
                    .setName("xxx")
                    .setEmail("xxx@example.com")
                    .build();
            
            // 序列化存储
            byte[] userBytes = user.toByteArray();
            sync.set("user:1", userBytes);
            
            // 查询反序列化
            byte[] storedBytes = sync.get("user:1");
            UserPB.User storedUser = UserPB.User.parseFrom(storedBytes);
            
            System.out.println("Retrieved User: " + storedUser);
					
					connection.close();
        
    }
}
  • 自定义 RedisCodec
java 复制代码
import io.lettuce.core.codec.RedisCodec;

import java.nio.ByteBuffer;

public class PB3RedisCodec implements RedisCodec<String, byte[]> {
    @Override
    public String decodeKey(ByteBuffer bytes) {
        return bytes.toString();
    }

    @Override
    public byte[] decodeValue(ByteBuffer bytes) {
        return toByteArray(bytes);
    }

    @Override
    public ByteBuffer encodeKey(String key) {
        return ByteBuffer.wrap(key.getBytes());
    }

    @Override
    public ByteBuffer encodeValue(byte[] value) {
        return ByteBuffer.wrap(value);
    }

    public static byte[] toByteArray(ByteBuffer buffer) {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        buffer.rewind(); // 恢复原始状态
        return bytes;
    }
}
  • 使用连接池配置
java 复制代码
GenericObjectPool<StatefulRedisConnection<String, byte[]>> pool = 
    ConnectionPoolSupport.createGenericPool(
        () -> client.connect(new PB3RedisCodec()), 
        new GenericObjectPoolConfig()
);

2. 关键配置说明

  1. PB3序列化

    java 复制代码
    // 序列化
    byte[] data = protoObject.toByteArray();
    
    // 反序列化
    ProtoClass obj = ProtoClass.parseFrom(data);
  2. Lettuce连接池优化

    java 复制代码
    // 连接池配置
    RedisURI uri = RedisURI.builder()
            .withHost("host")
            .withPassword("pass".toCharArray())
            .withTimeout(Duration.ofSeconds(10))
            .build();
    
    RedisClient client = RedisClient.create(uri);
    StatefulRedisConnection<String, byte[]> connection = client.connect();

3. 替代方案(Python实现)

若环境限制Java使用,可使用Python方案:

python 复制代码
import redis
from user_pb2 import User  # 需先编译.proto文件

# 连接Redis Labs
r = redis.Redis(
    host='your-redis-host',
    port=6379,
    password='your-password',
    decode_responses=False
)

# 序列化存储
user = User(id=1, name="John Doe", email="john.doe@example.com")
r.set("user:1", user.SerializeToString())

# 查询反序列化
stored_bytes = r.get("user:1")
stored_user = User.FromString(stored_bytes)
print(f"Retrieved User: {stored_user}")

4. 常见问题处理

  1. 依赖安装

    bash 复制代码
    # Java项目
    <dependency>
        <groupId>io.lettuce</groupId>
        <artifactId>lettuce-core</artifactId>
        <version>6.3.0.RELEASE</version>
    </dependency>
    
    # Python项目
    pip install redis protobuf
  2. 连接问题排查

    • 检查防火墙设置(开放6379端口)
    • 验证密码正确性
    • 测试网络连通性:telnet host 6379
  3. 性能优化

    • 使用连接池(Lettuce自动管理)
    • 启用压缩选项(PB3支持)
    • 设置合理超时时间(建议10-30秒)

注意:生产环境建议:

  • 使用SSL/TLS加密连接
  • 配置Redis访问白名单
  • 启用持久化存储(RDB/AOF)
  • 监控内存使用情况(免费套餐有30MB限制)

netty中实现Protobuf协议编解码与传输
Protobuf序列化机制的核心原理
lettuce支持的redis模式

相关推荐
2601_962218615 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
李高钢5 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
yuzhiboyouye7 小时前
那xml对应的sql语法,列举一下
xml·数据库·sql
. . . . .7 小时前
乐观锁 vs 悲观锁
数据库·sql
Leo.yuan7 小时前
2026年多数据库实时同步的四种架构方案及工具推荐
数据库·架构
hasty8 小时前
Origin 校验不是身份认证:MySQL MCP Server 漏洞给 AI 平台的警告
数据库·mysql·安全
梦想平凡9 小时前
百游棋牌源代码开发搭建教程(五):房间创建、座位分配与请求幂等实现
前端·javascript·数据库·源代码管理
凤山老林9 小时前
Spring Boot 整合 Flowable 的企业级落地指南
数据库·spring boot·后端·flowable·工作流
企业数字化笔记9 小时前
AI写的系统出现504怎么办?接口超时和数据库慢查询排查
数据库·后端
玄芯散人9 小时前
【筑基·047】内存Hierarchy:寄存器到硬盘的速度差
缓存·内存·计算机基础