帮我写一个reids工具类
时间: 2023-04-06 18:00:39 浏览: 102
好的,我可以回答这个问题。Redis 是一个开源的内存数据结构存储系统,可以用作数据库、缓存和消息中间件。为了使用 Redis,我们需要使用 Redis 客户端库。以下是一个 Redis 工具类的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>
typedef struct RedisClient {
redisContext *context;
redisReply *reply;
} RedisClient;
RedisClient *redis_connect(const char *host, int port) {
RedisClient *client = (RedisClient *) malloc(sizeof(RedisClient));
client->context = redisConnect(host, port);
if (client->context == NULL || client->context->err) {
printf("Error: %s\n", client->context->errstr);
exit(EXIT_FAILURE);
}
return client;
}
void redis_disconnect(RedisClient *client) {
redisFree(client->context);
free(client);
}
void redis_set(RedisClient *client, const char *key, const char *value) {
client->reply = redisCommand(client->context, "SET %s %s", key, value);
freeReplyObject(client->reply);
}
char *redis_get(RedisClient *client, const char *key) {
client->reply = redisCommand(client->context, "GET %s", key);
char *value = strdup(client->reply->str);
freeReplyObject(client->reply);
return value;
}
int main() {
RedisClient *client = redis_connect("localhost", 6379);
redis_set(client, "name", "Tom");
char *name = redis_get(client, "name");
printf("Name: %s\n", name);
free(name);
redis_disconnect(client);
return 0;
}
```
这个 Redis 工具类包含了连接 Redis 服务器、设置键值对、获取键值对和断开连接等基本操作。我们可以根据自己的需求进行扩展。
阅读全文