c++ - 在 Redis 中存储字符 vector - 包含 NUL

标签 c++ redis hiredis

我想将 JPEG 图像作为单个键值对存储在 Redis 中。 从 OpenCV 中,我得到 std::vector<unsigned char> jpeg来自imencode()

现在我将此 vector 转换为 std::stringSET与 Hiredis 一起。 问题是jpeg vector 包含 NUL字符 ( ANSII == 0 ) 和 Hiredis SET函数接收value.c_str().c_str()在第一次出现 NUL 后截断字符串,因此只有这个子字符串存储在数据库中。

我的问题是:我怎样才能SETGET一个std::vector<unsigned char> (包含 NUL )与 Hiredis? (最小化运行时间至关重要。)

这是我的代码:

// Create vector of uchars, = From CV [Disregard inefficiency here]

std::vector<unsigned char> jpeg;
jpeg.push_back( 'a' );
jpeg.push_back( 'b' );
jpeg.push_back( (unsigned char) 0 );
jpeg.push_back( 'c' );
jpeg.push_back( 'd' );

// Convert to string

std::string word = "";
for (int i=0; i<jpeg.size(); ++i)
{
    word.push_back(jpeg[i]);
}

std::cout << "word = " << word << std::endl;
std::cout << "word.c_str() = " << word.c_str() << std::endl;

// connect redis

std::string hostname = "127.0.0.1";
int port = 6379;
timeval timeout = { 1, 500000 }; // 1.5 seconds
redisContext* context = redisConnectWithTimeout(hostname.c_str(), port, timeout);

// set redis

std::string key = "jpeg";
redisReply* reply = (redisReply *)redisCommand(context, "SET %s %s", key.c_str(), word.c_str() );
freeReplyObject( (void*) reply);

// get redis

reply = (redisReply *)redisCommand(context, "GET %s", key.c_str() );
std::string value = reply->str;
freeReplyObject((void*) reply);
std::cout << "returned value = " << value << std::endl;

// Convert back to vector of uchars (this should be the same as the original jpeg)  [Disregard inefficiency here]

std::vector<unsigned char> jpeg_returned;
for (int i=0; i<value.size(); ++i)
{
    jpeg_returned.push_back(value[i]);
    // std::cout << "value[i] = " << value[i] << std::endl;
}

最佳答案

在显示代码之前,我想再次警告一下,在没有正确序列化的情况下存储二进制数据可能会出现问题。至少确保所有服务器都具有相同的字节序并且具有相同的 sizeof(int)。

std::vector<char> v{'A', 'B', '\0', 'C', 'D'};

std::string key = "jpeg";
redisReply* reply = static_cast<redisReply *>( redisCommand(context, "SET %s %b", key.c_str(), v.data(), v.size() ) );
freeReplyObject( reply );

并从 python 中读取。

>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> r.get("jpeg")
'AB\x00CD'

关于c++ - 在 Redis 中存储字符 vector - 包含 NUL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42800878/

相关文章:

c++ - 静态和共享库符号冲突?

node.js - 如何在socketio-redis管理的socketio进程集群中查找用户socket

Node.js、Socket.io、Redis pub/sub 大容量、低延迟困难

node.js - Redis - 经济拒绝。即使服务器正在运行

c++ - 在 C++ 中,template<> 是什么意思?

c++ - 如何将模板函数作为模板函数的参数传递?

php - 使用(客户端)javascript 直接连接到 Redis?

c - 加载共享库时出错,无法打开共享对象文件 : No such file or directory (hiredis)

c - Docker容器无法连接到Redis

C++风格问题: what to #include?