说明:
如果业务层代码使用了 web 框架,可以参考框架访问单机版 redis 的方法来接入 Keewidb。
准备工作
在 KeeWiDB 控制台 的实例详情页面的网络信息区域,获取连接数据库的内网 IPv4地址及端口。具体信息,请参见 查看实例详情。
已获取访问数据库的账号与密码。
下载并安装 hiredis。
连接示例
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <hiredis/hiredis.h>int main(int argc, char **argv) {unsigned int j;redisContext *c;redisReply *reply;if (argc < 4) {printf("Usage: 192.xx.xx.195 6379 instance_id password\\n");exit(0);}const char *hostname = argv[1];const int port = atoi(argv[2]);const char *instance_id = argv[3];const char *password = argv[4];struct timeval timeout = { 1, 500000 }; // 1.5 secondsc = redisConnectWithTimeout(hostname, port, timeout);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);}/* AUTH */reply = redisCommand(c, "AUTH %s", password);printf("AUTH: %s\\n", reply->str);freeReplyObject(reply);/* PING server */reply = redisCommand(c,"PING");printf("PING: %s\\n", reply->str);freeReplyObject(reply);/* Set a key */reply = redisCommand(c,"SET %s %s", "name", "credis_test");printf("SET: %s\\n", reply->str);freeReplyObject(reply);/* Try a GET */reply = redisCommand(c,"GET name");printf("GET name: %s\\n", reply->str);freeReplyObject(reply);/* Disconnects and frees the context */redisFree(c);return 0;}
运行结果