一文搞懂redis的用户权限管理(ACL)功能
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main(int argc, char **argv) {
// 连接到Redis服务器
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
int port = (argc > 2) ? atoi(argv[2]) : 6379;
redisContext *c = redisConnect(hostname, port);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
// 使用ACL命令添加用户
redisReply *reply = redisCommand(c, "ACL SETUSER newuser on >mypassword ~*:*");
if (reply->type == REDIS_REPLY_ERROR) {
printf("Error: %s\n", reply->str);
} else {
printf("User added successfully\n");
}
freeReplyObject(reply);
// 列出所有用户
reply = redisCommand(c, "ACL LIST");
if (reply->type == REDIS_REPLY_ERROR) {
printf("Error: %s\n", reply->str);
} else if (reply->type == REDIS_REPLY_ARRAY) {
printf("Number of users: %ld\n", reply->elements);
for (int i = 0; i < reply->elements; i++) {
printf("User %d: %s\n", i, reply->element[i]->str);
}
}
freeReplyObject(reply);
// 删除用户
reply = redisCommand(c, "ACL SETUSER newuser on >mypassword ~*:*");
if (reply->type == REDIS_REPLY_ERROR) {
printf("Error: %s\n", reply->str);
} else {
printf("User deleted successfully\n");
}
freeReplyObject(reply);
// 关闭连接
redisFree(c);
return 0;
}
这段代码展示了如何使用Redis的ACL命令来添加、列出和删除用户。注意,实际应用中需要处理内存分配失败的情况,并且在生产环境中应该使用合适的错误处理和资源管理策略。
评论已关闭