通过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模式

相关推荐
陈文锦丫1 分钟前
Redis原理篇
数据库·redis·缓存
xuanloyer10 分钟前
oracle从入门到精通--oracle基础
数据库·oracle
GEM的左耳返14 分钟前
Java面试实战:从Spring Boot到AI集成的技术深度挑战
spring boot·redis·微服务·kafka·java面试·spring ai·缓存优化
老华带你飞16 分钟前
动物救助|流浪狗救助|基于Springboot+vue的流浪狗救助平台设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·流浪动物救助平台
曹牧42 分钟前
Oracle中ROW_NUMBER() OVER()
java·数据库·sql
jnrjian1 小时前
MOS oracle rman backup 脚本
数据库·oracle
zhangfeng11331 小时前
KAT-Coder-Pro V1免费活动继续,免费原来定于北京时间 2025年11月11日 ,快手也加入了模型集成商的队伍了,支持国内各种开原模型
数据库
Amarantine、沐风倩✨1 小时前
深度解析:轨迹数据抽稀到底该放数据库还是 Java?(以 56800 条数据为例)
java·开发语言·数据库
欢乐的小猪1 小时前
win10如何更改mysql的密码
数据库·mysql
Gauss松鼠会1 小时前
【openGauss】如何通过pg_trigger.tgtype获取触发器的各种触发条件
数据库·vr·database·opengauss