一個簡單的例子,告訴用戶如何通過hiredis接口訪問ZSet對象:包括創建和訪問.
#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;
redisReply *reply_sec;
const char* a[10] = {"XUANXIU","kong","wukong", "YUWEN", "XUANXU", "SHUXUE", "FEIXUANXIU", "TIYU","gaoxiao","kaiwanxiao"};
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
int port = (argc > 2) ? atoi(argv[2]) : 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = 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);
}
/* PING server */
reply = redisCommand(c,"PING");
printf("PING: %s\n", reply->str);
freeReplyObject(reply);
/*Create a sort set ,from 0 to 9 */
reply = redisCommand(c,"DEL page_rank");
for(j = 0;j < 10;j++){
char buf[64];
snprintf(buf,64,"%d",j);
reply = redisCommand(c,"ZADD page_rank %s %s",buf,a[j]);
}
freeReplyObject(reply);
/*Let's check what we have inside the set*/
reply = redisCommand(c,"ZRANGE page_rank 0 -1 WITHSCORES");
if(reply->type == REDIS_REPLY_ARRAY){
for(j = 0 ; j< reply->elements;j++){
printf("%s \t",reply->element[j]->str);
reply_sec = redisCommand(c,"ZSCORE page_rank %s",reply->element[j]->str);
printf("%s\n",reply_sec->str);
j++;
freeReplyObject(reply_sec);
}
}
freeReplyObject(reply);
/* Disconnects and frees the context */
redisFree(c);
return 0;
}