本文整理汇总了C++中redisCommand函数的典型用法代码示例。如果您正苦于以下问题:C++ redisCommand函数的具体用法?C++ redisCommand怎么用?C++ redisCommand使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了redisCommand函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: keyGroupSet
int Server::appendGroupMsg(shared_ptr<IMChat::UnreadMsgRequest> ptrRequest, IMChat::UnreadMsgResponse& response)
{
auto ptrContext = m_redis.GetContext();
redisReply* ptrReply = NULL;
string keyGroupSet("groupSet:");
keyGroupSet += ptrRequest->userid();
string keyNumber("unreadNumber:");
keyNumber += ptrRequest->userid();
keyNumber += ":*";
//查询各个群未读消息数目;
//COMMAND: SORT groupSet:14006 GET # GET unreadNumber:14006:*
vector<string> numberData;
ptrReply = static_cast<redisReply*>(redisCommand(ptrContext, "SORT %s GET # GET %s", keyGroupSet.c_str(), keyNumber.c_str()));
if (NULL != ptrReply && REDIS_REPLY_ARRAY == ptrReply->type && 0 != ptrReply->elements)
{
for (size_t i = 0; i < ptrReply->elements; i++)
{
numberData.push_back(string(ptrReply->element[i]->str, ptrReply->element[i]->len));
}
}
freeReplyObject(ptrReply);
for (int i = 0; i < numberData.size()/2; i++)
{
if (numberData[2 * i + 1].compare("0") != 0)
{
//vector 数据第一个是groupId第二个是未读群消息数目;
string listName("groupMsg:");
listName += numberData[2 * i];
redisAppendCommand(ptrContext, "LRANGE %s %d %s", listName.c_str(), 0, numberData[2 * i + 1]);
}
}
//未读消息数;
int nMsgNumber = 0;
for (size_t i = 0; i < numberData.size()/2; i++)
{
if (numberData[2 * i + 1].compare("0") != 0)
{
redisGetReply(ptrContext, reinterpret_cast<void**>(&ptrReply));
if (NULL != ptrReply && REDIS_REPLY_ARRAY == ptrReply->type && 0 != ptrReply->elements)
{
for (size_t i = 0; i < ptrReply->elements; i++)
{
//添加repeated数据;
response.add_msgdata()->assign(ptrReply->element[i]->str, ptrReply->element[i]->len);
}
nMsgNumber += ptrReply->elements;
}
freeReplyObject(ptrReply);
}
}
//将未读消息数目置0;
for (size_t i = 0; i < numberData.size() / 2; i++)
{
if (numberData[2 * i + 1].compare("0") != 0)
{
//Key unreadNumber:userid:groupid
string key("unreadNumber:");
key += ptrRequest->userid();
key += ':';
key += numberData[2 * i];
m_redis.Set(key, "0");
}
}
return nMsgNumber;
}
开发者ID:hua345,项目名称:MutexIM,代码行数:70,代码来源:Server.cpp
示例2: run
void run() {
pid_t pid = -1;
void *reply = NULL;
const char *err_str = NULL;
redisContext *c = redisConnect("127.0.0.1", 6379);
if (!c || (c->err != 0))
goto ERR_CHNL_CONN;
reply = redisCommand(c, "SUBSCRIBE %s", qUtf8Printable(m_cmd.m_info_chnl));
if (!reply)
goto ERR_CHNL_SUB;
freeReplyObject(reply);
pid = fork();
if (pid == -1)
goto ERR_FORK;
else if (pid == 0) {
execute_js(m_path, m_args, m_cmd);
exit(0);
return ;
}
emit m_cmd.started();
while (redisGetReply(c, &reply) == REDIS_OK)
{
struct redisReply *r = (struct redisReply *)reply;
int ended = 0;
if (r->type == REDIS_REPLY_ARRAY && r->elements == 3) {
emit m_cmd.info(r->element[2]->str);
if (strcmp("end", r->element[2]->str) == 0)
{
ended = 1;
TEST_STOP = 1; // Question 1 : Need a extern visable to know program end or error
// : So i use TEST_STOP control GUI "elapsed time" Start/ Stop
}
// add by Alwin
//str_length_temp = strlen( r->element[2]->str ); // if message less 5 chara and elapsed time more than 2 second
//if( str_length_temp > str_length ) // elpased time stop
{
//str_length = str_length_temp;
//str_length_temp = 0;
}
emit m_cmd.justice_cmd_buf(); // Add by Alwin for GUI
}
freeReplyObject(reply);
if (ended)
break;
}
redisFree(c);
kill(pid, SIGKILL);
emit m_cmd.stopped();
waitpid(pid, NULL, 0);
if( command_input_mode == 0 )
m_control_scroll = false; // add by Alwin
return;
ERR_FORK:
err_str = "JS fork err.";
ERR_CHNL_SUB:
err_str = err_str == NULL ? "JS message channel subscribe err." : err_str;
ERR_CHNL_CONN:
err_str = err_str == NULL ? "JS message channel conn err." : err_str;
if (c)
redisFree(c);
emit m_cmd.started();
emit m_cmd.err(err_str);
emit m_cmd.stopped();
return;
}
开发者ID:junqiang521,项目名称:Test,代码行数:94,代码来源:justice_cmd.cpp
示例3: addTarget
void addTarget()
{
// Setup
static char absoluteAddress[64];
static char targetTag[64];
static char *extension;
static char *fileName;
// Clear array, avaoid issues
int i;
for (i = 0; i < 64; i++)
absoluteAddress[i] = '\0';
printf("Enter full pathname of background image:\n");
printf("Path: ");
// Get Filename
fflush(stdin);
fgets(absoluteAddress, sizeof(absoluteAddress), stdin);
absoluteAddress[strcspn(absoluteAddress, "\n")] = '\0';
fflush(stdin);
fflush(stdout);
printf("Reading File: '%s' ", absoluteAddress);
// Copy the string
char absoluteAddressFileName[64];
char absoluteAddressExtension[64];
strcpy(absoluteAddressFileName, absoluteAddress);
strcpy(absoluteAddressExtension, absoluteAddress);
// Get the extension
extension = strrchr(absoluteAddressExtension, '.');
// Get the filename
fileName = strrchr(absoluteAddressFileName, '/');
fileName[strlen(fileName)-strlen(extension)] = '\0';
for (i = 0; i < strlen(fileName); i++)
fileName[i] = fileName[i+1];
gdImagePtr target = loadImage(absoluteAddress, extension);
if (target != NULL) {
// Get Tag
printf("\nEnter a tag for this target: ");
fflush(stdin);
fgets(targetTag, sizeof(targetTag), stdin);
targetTag[strcspn(targetTag, "\n")] = '\0';
// Store data in directory
storeImageTarget(target, ".png", TargetDIR, fileName, targetTag);
// Store Tag
redisReply *setReply = redisCommand(Context, "SADD %s %s", GRP_TARGET_NAME, targetTag);
freeReplyObject(setReply);
// Successful
printf("Added to collection of background images\n");
} else {
printf("Cannot Find Image.\n");
}
free(target);
}
开发者ID:JamesMarino,项目名称:CSCI131,代码行数:67,代码来源:main.c
示例4: process
void process( redisContext *c )
{
FCGX_Stream *in, *out, *err;
FCGX_ParamArray envp;
redisReply *r;
json reason = { .type = STRING, .name = "reason", .str = NULL };
json* failureEls[1] = { &reason };
json success = { .type = OBJECT, .length = 0, .name = NULL, .objArr = NULL };
json failure = { .type = OBJECT, .length = 1, .name = NULL, .objArr = failureEls };
while ( FCGX_Accept( &in, &out, &err, &envp ) >= 0 )
{
// Check method
if ( check_method_post( out, envp ) )
continue;
// Check user is logged in
char sid[33];
char *user = session( c, envp, sid );
if ( !user )
{
header( out, 401, NULL );
reason.str = "Not logged in.";
json_out( out, &failure );
continue;
}
// Initialize reused variables
reason.str = "";
// Get contentlength
long len = content_length( envp );
// Get post params
char *s;
if ( !read_stream( &s, in, len ) )
{
header( out, 400, NULL );
reason.str = "No parameters provided";
json_out( out, &failure );
continue;
}
// Parse POST params
param *p;
ssize_t num = convert_to_params( &p, s, "&", "=", -1 );
// Get parameters
char *courses = NULL, *date = NULL, *start = NULL, *finish = NULL, *students = NULL, *idStr = NULL;
for ( int i = 0; i < num; ++i )
{
if ( !courses && !strcmp( p[i].name, "courses" ) ) {
courses = p[i].value;
} else if ( !date && !strcmp( p[i].name, "date" ) ) {
date = p[i].value;
} else if ( !start && !strcmp( p[i].name, "start" ) ) {
start = p[i].value;
} else if ( !finish && !strcmp( p[i].name, "finish" ) ) {
finish = p[i].value;
} else if ( !students && !strcmp( p[i].name, "students" ) ) {
students = p[i].value;
} else if ( !idStr && !strcmp( p[i].name, "id" ) ) {
idStr = p[i].value;
}
}
// Check all parameters entered
if ( !courses || !date || !start || !finish || !students )
{
header( out, 400, NULL );
reason.str = "All details must be entered.";
json_out( out, &failure );
goto err;
}
// URL decode components
inplace_url_decode( courses );
inplace_url_decode( date );
inplace_url_decode( start );
inplace_url_decode( finish );
inplace_url_decode( students );
// Get next tute id
long long id = -1;
if ( idStr ) {
// Convert to long long
id = strtol( idStr, NULL, 10 );
// Check user owns tute
r = redisCommand( c, "SISMEMBER tute:tutor:%s %lld", user, id );
if ( r->type != REDIS_REPLY_INTEGER )
{
header( out, 500, NULL );
reason.str = "DB Error.";
json_out( out, &failure );
freeReplyObject( r );
goto err;
//.........这里部分代码省略.........
开发者ID:joshthornton,项目名称:tutoring,代码行数:101,代码来源:save.c
示例5: redis_lookup
int redis_lookup(char *response, redisPool *pool, char *key) {
int fd;
redisReply *reply;
char replyStr[64] = "";
char registry[64] = "";
time_t client_time;
time_t reset;
int rest;
time(&client_time);
/* if the event time is greater then the init_time */
rest = ((int) client_time - init_time);
if(rest > cfg.redis_reload_time) {
syslog(LOG_INFO, "%i passed. Realoading database\n", cfg.redis_reload_time);
if(redisPoolInit(&redis_pool, cfg.redis_address, REDIS_POOL_SIZE) == -1) {
snprintf(replyStr, (size_t) strlen(POSTFIX_RESPONSE_TEMPFAIL)
+ 20, "%s %s\n", POSTFIX_RESPONSE_TEMPFAIL, "reset database error");
}
/* reset the counter */
time(&reset);
init_time = (int) reset;
}
fd = redisPoolGetCurrent(pool);
/* running the string cfg.registry_prefix to know what kinds of service i'll answer. */
int i, scount = 0;
for(i = 0; i<=strlen(cfg.registry_prefix); i++) {
/* when i found a comma or a string ending, issue the command */
if((cfg.registry_prefix[i] == ',') || cfg.registry_prefix[i] == '\0') {
registry[scount] = '\0';
reply = redisCommand(fd, "GET %b:%b", registry, strlen(registry),
key, strlen(key));
/* if the reply is not nil, break the loop.
* Case is nil, continue until the end */
if(reply->type != REDIS_REPLY_NIL)
break;
scount = 0;
registry[0] = '\0';
continue;
}
registry[scount] = cfg.registry_prefix[i];
scount++;
}
if(reply->type == REDIS_REPLY_ERROR) {
/* if disconected, try reconnect */
if(redisPoolInit(&redis_pool, cfg.redis_address, REDIS_POOL_SIZE) == -1) {
snprintf(replyStr, (size_t) strlen(POSTFIX_RESPONSE_TEMPFAIL)
+ strlen(reply->reply) +3, "%s %s\n", POSTFIX_RESPONSE_TEMPFAIL, reply->reply);
}
else {
/* if reconnected, select current */
fd = redisPoolGetCurrent(&redis_pool);
/* re-send the request */
reply = redisCommand(fd, "GET %b:%b", registry, strlen(registry), key, strlen(key));
snprintf(replyStr, (size_t) strlen(POSTFIX_RESPONSE_OK)
+ strlen(reply->reply) +3, "%s %s\n", POSTFIX_RESPONSE_OK, reply->reply);
}
}
else {
/* time the reply to client */
if(reply->type != REDIS_REPLY_NIL) {
/* if is a string (in this case, always) */
if(reply->type == REDIS_REPLY_STRING) {
snprintf(replyStr, (size_t) strlen(POSTFIX_RESPONSE_OK)
+ strlen(reply->reply) +3, "%s %s", POSTFIX_RESPONSE_OK, reply->reply);
}
}
/* if the entry does not exists, reply 500 to client */
/* update: return -1, to query a dbms */
else {
freeReplyObject(reply);
return -1;
/*snprintf(replyStr, (size_t) strlen(POSTFIX_RESPONSE_ERROR)
+ 16, "%s %s", POSTFIX_RESPONSE_ERROR, "unknown entry");*/
}
}
syslog(LOG_INFO, "Reply sent to client: (%s)", replyStr);
/* freeing response */
freeReplyObject(reply);
/* pasting into *response */
sprintf(response, "%s\n", replyStr);
return 0;
}
开发者ID:samgaw,项目名称:Postfix-Redis-TCP-Map,代码行数:97,代码来源:redis.c
示例6: cache_entry_insert
//.........这里部分代码省略.........
p = fr_asprint(request, argv[i], argv_len[i], '\0');
RDEBUG3("%s", p);
talloc_free(p);
}
REXDENT();
}
redisAppendCommandArgv(conn->handle, talloc_array_length(argv), argv, argv_len);
pipelined++;
/*
* Set the expiry time and close out the transaction.
*/
if (c->expires > 0) {
if (RDEBUG_ENABLED3) {
p = fr_asprint(request, (char const *)c->key, c->key_len, '\"');
RDEBUG3("EXPIREAT \"%s\" %li", p, (long)c->expires);
talloc_free(p);
}
if (redisAppendCommand(conn->handle, "EXPIREAT %b %i", c->key,
c->key_len, c->expires) != REDIS_OK) goto append_error;
pipelined++;
RDEBUG3("EXEC");
if (redisAppendCommand(conn->handle, "EXEC") != REDIS_OK) goto append_error;
pipelined++;
}
REXDENT();
reply_num = fr_redis_pipeline_result(&status, replies, sizeof(replies) / sizeof(*replies),
conn, pipelined);
reply = replies[0];
}
talloc_free(pool);
if (s_ret != REDIS_RCODE_SUCCESS) {
RERROR("Failed inserting entry");
return CACHE_ERROR;
}
RDEBUG3("Command results");
RINDENT();
for (i = 0; i < reply_num; i++) {
fr_redis_reply_print(L_DBG_LVL_3, replies[i], request, i);
fr_redis_reply_free(replies[i]);
}
REXDENT();
return CACHE_OK;
}
/** Call delete the cache entry from redis
*
* @copydetails cache_entry_expire_t
*/
static cache_status_t cache_entry_expire(UNUSED rlm_cache_config_t const *config, void *driver_inst,
REQUEST *request, UNUSED void *handle, uint8_t const *key, size_t key_len)
{
rlm_cache_redis_t *driver = driver_inst;
fr_redis_cluster_state_t state;
fr_redis_conn_t *conn;
fr_redis_rcode_t status;
redisReply *reply = NULL;
int s_ret;
for (s_ret = fr_redis_cluster_state_init(&state, &conn, driver->cluster, request, key, key_len, false);
s_ret == REDIS_RCODE_TRY_AGAIN; /* Continue */
s_ret = fr_redis_cluster_state_next(&state, &conn, driver->cluster, request, status, &reply)) {
reply = redisCommand(conn->handle, "DEL %b", key, key_len);
status = fr_redis_command_status(conn, reply);
}
if (s_ret != REDIS_RCODE_SUCCESS) {
RERROR("Failed expiring entry");
fr_redis_reply_free(reply);
return CACHE_ERROR;
}
rad_assert(reply); /* clang scan */
if (reply->type == REDIS_REPLY_INTEGER) {
fr_redis_reply_free(reply);
if (reply->integer) return CACHE_OK; /* Affected */
return CACHE_MISS;
}
REDEBUG("Bad result type, expected integer, got %s",
fr_int2str(redis_reply_types, reply->type, "<UNKNOWN>"));
fr_redis_reply_free(reply);
return CACHE_ERROR;
}
extern cache_driver_t rlm_cache_redis;
cache_driver_t rlm_cache_redis = {
.name = "rlm_cache_redis",
.instantiate = mod_instantiate,
.inst_size = sizeof(rlm_cache_redis_t),
.free = cache_entry_free,
.find = cache_entry_find,
.insert = cache_entry_insert,
.expire = cache_entry_expire,
};
开发者ID:0xbad0c0d3,项目名称:freeradius-server,代码行数:101,代码来源:rlm_cache_redis.c
示例7: redis_connect
int redis_connect(redis_con *con)
{
redisContext *ctx;
redisReply *rpl;
cluster_node *it;
/* connect to redis DB */
ctx = redisConnect(con->id->host,con->id->port);
if (ctx->err != REDIS_OK) {
LM_ERR("failed to open redis connection - %s\n",ctx->errstr);
return -1;
}
/* auth using password, if any */
if (con->id->password) {
rpl = redisCommand(ctx,"AUTH %s",con->id->password);
if (rpl == NULL || rpl->type == REDIS_REPLY_ERROR) {
LM_ERR("failed to auth to redis - %.*s\n",
rpl?rpl->len:7,rpl?rpl->str:"FAILURE");
freeReplyObject(rpl);
redisFree(ctx);
return -1;
}
LM_DBG("AUTH [password] - %.*s\n",rpl->len,rpl->str);
freeReplyObject(rpl);
}
rpl = redisCommand(ctx,"CLUSTER NODES");
if (rpl == NULL || rpl->type == REDIS_REPLY_ERROR) {
/* single instace mode */
con->type |= REDIS_SINGLE_INSTANCE;
con->nodes = pkg_malloc(sizeof(cluster_node));
if (con->nodes == NULL) {
LM_ERR("no more pkg\n");
freeReplyObject(rpl);
redisFree(ctx);
return -1;
}
strcpy(con->nodes->ip,con->id->host);
con->nodes->port = con->id->port;
con->nodes->start_slot = 0;
con->nodes->end_slot = 4096;
con->nodes->context = NULL;
con->nodes->next = NULL;
LM_DBG("single instance mode\n");
} else {
/* cluster instance mode */
con->type |= REDIS_CLUSTER_INSTANCE;
con->slots_assigned = 0;
LM_DBG("cluster instance mode\n");
if (build_cluster_nodes(con,rpl->str,rpl->len) < 0) {
LM_ERR("failed to parse Redis cluster info\n");
return -1;
}
}
freeReplyObject(rpl);
redisFree(ctx);
for (it=con->nodes;it;it=it->next) {
if (it->end_slot > con->slots_assigned )
con->slots_assigned = it->end_slot;
if (redis_connect_node(con,it) < 0) {
LM_ERR("failed to init connection \n");
return -1;
}
}
return 0;
}
开发者ID:NoamRom89,项目名称:opensips,代码行数:72,代码来源:cachedb_redis_dbase.c
示例8: findBigKeys
static void findBigKeys(void) {
unsigned long long biggest[5] = {0,0,0,0,0};
unsigned long long samples = 0;
redisReply *reply1, *reply2, *reply3 = NULL;
char *sizecmd, *typename[] = {"string","list","set","hash","zset"};
int type;
printf("\n# Press ctrl+c when you have had enough of it... :)\n");
printf("# You can use -i 0.1 to sleep 0.1 sec every 100 sampled keys\n");
printf("# in order to reduce server load (usually not needed).\n\n");
while(1) {
/* Sample with RANDOMKEY */
reply1 = redisCommand(context,"RANDOMKEY");
if (reply1 == NULL) {
fprintf(stderr,"\nI/O error\n");
exit(1);
} else if (reply1->type == REDIS_REPLY_ERROR) {
fprintf(stderr, "RANDOMKEY error: %s\n",
reply1->str);
exit(1);
}
/* Get the key type */
reply2 = redisCommand(context,"TYPE %s",reply1->str);
assert(reply2 && reply2->type == REDIS_REPLY_STATUS);
samples++;
/* Get the key "size" */
if (!strcmp(reply2->str,"string")) {
sizecmd = "STRLEN";
type = TYPE_STRING;
} else if (!strcmp(reply2->str,"list")) {
sizecmd = "LLEN";
type = TYPE_LIST;
} else if (!strcmp(reply2->str,"set")) {
sizecmd = "SCARD";
type = TYPE_SET;
} else if (!strcmp(reply2->str,"hash")) {
sizecmd = "HLEN";
type = TYPE_HASH;
} else if (!strcmp(reply2->str,"zset")) {
sizecmd = "ZCARD";
type = TYPE_ZSET;
} else if (!strcmp(reply2->str,"none")) {
freeReplyObject(reply1);
freeReplyObject(reply2);
freeReplyObject(reply3);
continue;
} else {
fprintf(stderr, "Unknown key type '%s' for key '%s'\n",
reply2->str, reply1->str);
exit(1);
}
reply3 = redisCommand(context,"%s %s", sizecmd, reply1->str);
if (reply3 && reply3->type == REDIS_REPLY_INTEGER) {
if (biggest[type] < reply3->integer) {
printf("[%6s] %s | biggest so far with size %llu\n",
typename[type], reply1->str,
(unsigned long long) reply3->integer);
biggest[type] = reply3->integer;
}
}
if ((samples % 1000000) == 0)
printf("(%llu keys sampled)\n", samples);
if ((samples % 100) == 0 && config.interval)
usleep(config.interval);
freeReplyObject(reply1);
freeReplyObject(reply2);
if (reply3) freeReplyObject(reply3);
}
}
开发者ID:CNCBASHER,项目名称:linuxcnc-1,代码行数:74,代码来源:redis-cli.c
示例9: log_vgtp_pe_sync
/*
* === FUNCTION ======================================================================
* Name: int log_vgtp_pe_sync()
* Description: logging VGTP performance parameters
* =====================================================================================
*/
int log_vgtp_pe_sync(int s_id, char *s_desc, int data_len, char* data_val)
{
//Check the input parameters
DBG("Check the input parameters.\n");
if(0 > s_id){
printf("Input parameters error: s_id = %d.\n", s_id);
return -1;
}
if(NULL==s_desc){
printf("Input parameters error: s_desc = NULL.\n");
return -2;
}
if(0>=data_len || data_len >= REDIS_CMD_BUFFER_LEN){
printf("Input parameters error: data_len = %d.\n", data_len);
return -3;
}
if(NULL==data_val){
printf("Input parameters error: data_val = NULL.\n");
return -4;
}
if(data_len != (int)strlen(data_val) ){
printf("Input parameters error: len(data_val) = %d and data_len = %d.\n",
strlen(data_val), data_len);
return -5;
}
//Connect the Redis Database
DBG("Prepare Redis DB:\n");
redisContext *redis_con = NULL;
redisReply *redis_reply = NULL;
const char * redis_hostname = REDIS_SRV_IP;
int redis_port = REDIS_SRV_PORT;
struct timeval redis_timeout = {1, REDIS_TIMEOUT};
redis_con = redisConnectWithTimeout(redis_hostname, redis_port, redis_timeout);
if(NULL==redis_con || redis_con->err) {
if(redis_con) {
printf("Redis connection error: %s\n", redis_con->errstr);
redisFree(redis_con);
redis_con = NULL;
} else {
printf("Redis Connection error: can't allocate redis context.\n");
}
return -1;
} else {
DBG("Redis Connection Success.\n");
redis_reply = (redisReply*)redisCommand(redis_con, "Ping");
DBG("Ping: %s\n", redis_reply->str);
freeReplyObject(redis_reply);
redis_reply= NULL;
}
//Save the performance parameters into Redis DB.
char cmd_buffer[REDIS_CMD_BUFFER_LEN];
memset((void*)cmd_buffer, 0, REDIS_CMD_BUFFER_LEN);
sprintf(cmd_buffer, "ID:%d|DESC:%s|%s", s_id, s_desc, data_val);
DBG("cmd_buffer: %s\n", cmd_buffer);
redis_reply = (redisReply*)redisCommand(redis_con, "rpush %s %b",
REDIS_PE_STAT_LIST, cmd_buffer, (size_t)strlen(cmd_buffer));
if(NULL == redis_reply
||redis_reply->type == REDIS_REPLY_ERROR
||redis_reply->type == REDIS_REPLY_NIL) {
printf("RedisDB reply is NULL or ErrCode = |%s|", redis_reply->str);
return -1;
}
//free redis_reply objects
if(NULL != redis_reply) {
freeReplyObject(redis_reply);
redis_reply = NULL;
}
//free redis conn
if(NULL != redis_con){
redisFree(redis_con);
redis_con = NULL;
}
return 1;
}
开发者ID:ZhiweiYAN,项目名称:VGTP_PERFORMANCE_EVALUATION,代码行数:94,代码来源:log_vgtp_pe.c
示例10: print_key2
void print_key2(redis_instance* inst, char* key, size_t len)
{
long long size = 0;
int flag = get_key_type(inst, key, len);
long long pttl = get_key_pttl(inst, key, len);
printf("{key:%s, type:%s, pttl:%lldms, db:%lu,",
key, type_name[flag], pttl, inst->db);
switch (flag) {
case KSTRING: {
redisReply* kv = (redisReply*)redisCommand(inst->cxt, "get %b", key, len);
assert(kv != nil);
assert(kv->type == REDIS_REPLY_STRING);
assert(kv->len != 0);
pline(" value:%s}", kv->str);
freeReplyObject(kv);
}
break;
case KHASH: {
size = get_hashtable_size(inst, key, len);
printf(" size:%lld", size);
if (size) {
printf(",\n kvs:[");
print_hashtable2(inst, key, len);
pline("\b \n ]");
}
pline("}");
}
break;
case KLIST: {
size = get_list_size(inst, key, len);
printf(" size:%lld", size);
if (size) {
printf(",\n values:[");
print_list(inst, key, len);
pline("\b \n ]");
}
pline("}");
}
break;
case KSET: {
size = get_set_size(inst, key, len);
printf(" size:%lld", size);
if (size) {
printf(",\n values:[");
print_set2(inst, key, len);
pline("\b \n ]");
}
pline("}");
}
break;
case KSSET: {
size = get_sset_size(inst, key, len);
printf(" size:%lld", size);
if (size) {
printf(",\n values:[");
print_sset2(inst, key, len);
pline("\b \n ]");
}
pline("}");
}
break;
case KNONE: {
FATAL("none type of key:%s", key);
}
break;
case KUNKOWN: {
FATAL("unknown type of key:%s", key);
}
}
}
开发者ID:bugou,项目名称:test,代码行数:76,代码来源:tool.c
示例11: main
int main(int argc, char **argv) {
redisContext *c;
redisReply *reply;
const char *socket = NULL;
const char *ip = "127.0.0.1";
int port = 3388;
const char *topic = "loggen";
int num = -1;
int period = -1;
int i = 0;
void *kid = NULL;
char logbuf[10240];
int opt;
int quiet = 0;
int psub = 0;
const char* const short_options = "s:i:p:t:f:n:qbh";
const struct option long_options[] = {
{ "socket", required_argument, NULL, 's' },
{ "ip", required_argument, NULL, 'i' },
{ "port", required_argument, NULL, 'p' },
{ "topic", required_argument, NULL, 't' },
{ "psub", no_argument, NULL, 'b' },
{ "num", required_argument, NULL, 'n' },
{ "period", required_argument, NULL, 'r' },
{ "quiet", no_argument, NULL, 'q' },
{ "help", no_argument, NULL, 'h' },
{ NULL, 0, NULL, 0 },
};
while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) > 0) {
switch (opt) {
case 's':
socket = optarg;
break;
case 'i':
ip = optarg;
break;
case 'p':
port = atoi(optarg);
break;
case 't':
topic = optarg;
break;
case 'b':
psub = 1;
break;
case 'n':
num = atoi(optarg);
break;
case 'r':
period = atoi(optarg);
break;
case 'q':
quiet = 1;
break;
case 'h':
default:
Usage(argv[0]);
}
}
if (socket == NULL && ip == NULL) {
Usage(argv[0]);
}
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
if (socket) {
c = redisConnectUnixWithTimeout(socket, timeout);
} else {
c = redisConnectWithTimeout((char*)ip, port, timeout);
}
if (c->err) {
printf("Connection error: %s\n", c->errstr);
exit(1);
}
if (psub) reply = redisCommand(c,"PSUBSCRIBE %s", topic);
else reply = redisCommand(c,"SUBSCRIBE %s", topic);
if (reply) {
printf("SUBSCRIBE %s\n", reply->str);
freeReplyObject(reply);
}
while (1) {
if (!redisGetReply(c, (void*)&reply)) {
printf("%s %s %s", reply->element[0]->str, reply->element[1]->str, reply->element[2]->str);
if (psub) printf("%s", reply->element[3]->str);
printf("\n");
freeReplyObject(reply);
} else {
printf("get msg failed\n");
}
if (period != -1) {
usleep(period * 1000);
}
}
redisFree(c);
//.........这里部分代码省略.........
开发者ID:290420058,项目名称:kids,代码行数:101,代码来源:subscribe.c
示例12: modred_command
redisReply * modred_command(const char *command,redisContext *context)
{
redisReply * reply=redisCommand(context,command);
return reply;
}
开发者ID:StarLee,项目名称:apache_redis,代码行数:5,代码来源:redis_about.c
示例13: main
int main(int argc, char *argv[])
{
int ret = 1;
size_t bufSize = 8192;
int batchSize = 2000;
if (argc > 1) {
batchSize = atoi(argv[1]);
if (batchSize <= 0) {
fprintf(stderr, "Dodgy batch size\n");
exit(1);
}
}
char *buffer = calloc(bufSize, sizeof(char));
uint64_t cnt = 0;
redisReply *reply = NULL;
redisContext *c = redisConnectUnix("/var/lib/redis/redis.sock");
if (c != NULL && c->err) {
printf("Error: %s\n", c->errstr);
goto cleanup;
}
reply = redisCommand(c, "DEL testhll");
if (reply == NULL) {
printf("Failed: %s\n", c->errstr);
goto cleanup;
}
freeReplyObject(reply);
int batchPos = 0;
int len = 0;
while ((len = readln(stdin, '\n', &buffer, &bufSize)) > 0) {
cnt++;
redisAppendCommand(c, "PFADD testhll %s", buffer);
batchPos++;
if (batchSize == batchPos) {
batchPos = 0;
for (int j = 0; j < batchSize; j++) {
redisGetReply(c, (void **)&reply);
if (reply == NULL) {
printf("Failed: %s\n", c->errstr);
goto cleanup;
}
else if (reply->type == REDIS_REPLY_ERROR) {
printf("Failed: %s\n", reply->str);
goto cleanup;
}
freeReplyObject(reply);
}
}
}
if (batchPos > 0) {
for (int j = 0; j < batchPos; j++) {
redisGetReply(c, (void **)&reply);
if (reply == NULL) {
printf("Failed: %s\n", c->errstr);
goto cleanup;
}
else if (reply->type == REDIS_REPLY_ERROR) {
printf("Failed: %s\n", reply->str);
goto cleanup;
}
freeReplyObject(reply);
}
}
reply = redisCommand(c, "PFCOUNT testhll");
if (reply == NULL) {
printf("Failed: %s\n", c->errstr);
goto cleanup;
}
printf("%ld %lld\n", cnt, reply->integer);
ret = 0;
cleanup:
if (reply != NULL) freeReplyObject(reply);
free(buffer);
redisFree(c);
return ret;
}
开发者ID:shabbyrobe,项目名称:phphll,代码行数:91,代码来源:hllcnt-hiredis.c
示例14: main
int main(void) {
unsigned int j;
redisContext *c;
redisReply *reply;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout((char*)"127.0.0.1", 6379, timeout);
if (c->err) {
printf("Connection error: %s\n", c->errstr);
exit(1);
}
/* PING server */
reply = redisCommand(c,"PING");
printf("PING: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key */
reply = redisCommand(c,"SET %s %s", "foo", "hello world");
printf("SET: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key using binary safe API */
reply = redisCommand(c,"SET %b %b", "bar", (size_t)3, "hello", (size_t)5);
printf("SET (binary API): %s\n", reply->str);
freeReplyObject(reply);
/* Try a GET and two INCR */
reply = redisCommand(c,"GET foo");
printf("GET foo: %s\n", reply->str);
freeReplyObject(reply);
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* again ... */
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* Create a list of numbers, from 0 to 9 */
reply = redisCommand(c,"DEL mylist");
freeReplyObject(reply);
for (j = 0; j < 10; j++) {
char buf[64];
snprintf(buf,64,"%d",j);
reply = redisCommand(c,"LPUSH mylist element-%s", buf);
freeReplyObject(reply);
}
/* Let's check what we have inside the list */
reply = redisCommand(c,"LRANGE mylist 0 -1");
if (reply->type == REDIS_REPLY_ARRAY) {
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
}
}
freeReplyObject(reply);
return 0;
}
开发者ID:koenvandesande,项目名称:hiredis,代码行数:62,代码来源:example.c
示例15: test_nonblocking_connection
static void test_nonblocking_connection() {
redisContext *c;
int wdone = 0;
test("Calls command callback when command is issued: ");
c = __connect_nonblock();
redisSetCommandCallback(c,__test_callback,(void*)1);
redisCommand(c,"PING");
test_cond(__test_callback_flags == 1);
redisFree(c);
test("Calls disconnect callback on redisDisconnect: ");
c = __connect_nonblock();
redisSetDisconnectCallback(c,__test_callback,(void*)2);
redisDisconnect(c);
test_cond(__test_callback_flags == 2);
redisFree(c);
test("Calls disconnect callback and free callback on redisFree: ");
c = __connect_nonblock();
redisSetDisconnectCallback(c,__test_callback,(void*)2);
redisSetFreeCallback(c,__test_callback,(void*)4);
redisFree(c);
test_cond(__test_callback_flags == ((2 << 8) | 4));
test("redisBufferWrite against empty write buffer: ");
c = __connect_nonblock();
test_cond(redisBufferWrite(c,&wdone) == REDIS_OK && wdone == 1);
redisFree(c);
test("redisBufferWrite against not yet connected fd: ");
c = __connect_nonblock();
redisCommand(c,"PING");
test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
strncmp(c->error,"write:",6) == 0);
redisFree(c);
test("redisBufferWrite against closed fd: ");
c = __connect_nonblock();
redisCommand(c,"PING");
redisDisconnect(c);
test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
strncmp(c->error,"write:",6) == 0);
redisFree(c);
test("Process callbacks in the right sequence: ");
c = __connect_nonblock();
redisCommandWithCallback(c,__test_reply_callback,(void*)1,"PING");
redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
redisCommandWithCallback(c,__test_reply_callback,(void*)3,"PING");
/* Write output buffer */
wdone = 0;
while(!wdone) {
usleep(500);
redisBufferWrite(c,&wdone);
}
/* Read until at least one callback is executed (the 3 replies will
* arrive in a single packet, causing all callbacks to be executed in
* a single pass). */
while(__test_callback_flags == 0) {
assert(redisBufferRead(c) == REDIS_OK);
redisProcessCallbacks(c);
}
test_cond(__test_callback_flags == 0x010203);
redisFree(c);
test("redisDisconnect executes pending callbacks with NULL reply: ");
c = __connect_nonblock();
redisSetDisconnectCallback(c,__test_callback,(void*)1);
redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
redisDisconnect(c);
test_cond(__test_callback_flags == 0x0201);
redisFree(c);
}
开发者ID:doorhinges0,项目名称:doorhinges00,代码行数:76,代码来源:test.1.c
示例16: main
int main(int argc, char **argv){
int i, j, n, similarityFunc = 0;
int itemCount = 0;
char *itemID;
char *redisPrefix;
redisContext *c;
redisReply *all_items;
redisReply *reply;
int cur_batch_size;
char* cur_batch;
char *iikey;
int batch_size = 200; /* FIXPAUL: make option */
int maxItems = 50; /* FIXPAUL: make option */
struct {
char host[1024];
int port;
char db[64];
} redis_addr;
/* option parsing */
if(argc < 2)
return print_usage(argv[0]);
if(!strcmp(argv[1], "--version"))
return print_version();
if(!strcmp(argv[1], "--jaccard"))
similarityFunc = 1;
if(!strcmp(argv[1], "--cosine"))
similarityFunc = 2;
if(!similarityFunc){
printf("invalid option: %s\n", argv[1]);
return 1;
} else if(argc < 5 || argc > 6){
printf("wrong number of arguments\n");
print_usage(argv[0]);
return 1;
}
redisPrefix = argv[2];
itemID = argv[3];
redis_addr.host[0] = 0;
redis_addr.port = 0;
redis_addr.db[0] = 0;
/* configure redis location */
if(argc > 4){
char* has_port = strchr(argv[4], ':');
if(has_port){
strncpy(redis_addr.host, argv[4], strlen(argv[4]) - strlen(has_port));
redis_addr.host[strlen(argv[4]) - strlen(has_port)] = 0;
redis_addr.port = atoi(has_port + 1);
} else {
strncpy(redis_addr.host, argv[4], sizeof(redis_addr.host));
}
}
if(argc > 5){
strcpy(redis_addr.db, argv[5]);
} else {
strcpy(redis_addr.db, "0");
}
/* default redis location */
if(strlen(redis_addr.host) == 0)
strcpy(redis_addr.host, "localhost");
if(!redis_addr.port)
redis_addr.port = 6379;
/* connect to redis */
struct timeval timeout = { 1, 500000 };
c = redisConnectWithTimeout(redis_addr.host, redis_addr.port, timeout);
redisCommand(c, "SELECT %s", redis_addr.db);
if(c->err){
printf("connection to redis failed: %s\n", c->errstr);
return 1;
}
/* get item count */
reply = redisCommand(c,"HGET %s:items %s", redisPrefix, itemID);
if(reply->str){
itemCount = atoi(reply->str);
} else {
itemCount = 0;
}
freeReplyObject(reply);
if(itemCount < 2){
printf("exit: item count is zero or one\n");
return 0;
//.........这里部分代码省略.........
开发者ID:learnist,项目名称:recommendify,代码行数:101,代码来源:recommendify.c
示例17: redis_test
void redis_test(void)
{
unsigned int i;
redisReply *r;
redisContext *ctx;
struct timeval tv;
tv.tv_sec = 30;
tv.tv_usec = 0;
/* 1. 连接Redis服务器
* 带有超时的方式链接Redis服务器, 同时获取与Redis连接的上下文对象.
* 该对象将用于其后所有与Redis操作的函数. */
ctx = redisConnectWithTimeout(REDIS_SERVER_IP_ADDR, REDIS_SERVER_PORT, tv);
if (ctx->err)
{
fprintf(stderr, "Connect redis server failed! ip:%s port:%d",
REDIS_SERVER_IP_ADDR, REDIS_SERVER_PORT);
goto ERROR;
}
/* 2. 设置KEY-VALUE对
* 需要注意的是, 如果返回的对象是NULL, 则表示客户端和服务器之间出现严重错误,
* 必须重新链接. 这里只是举例说明, 简便起见, 后面的命令就不再做这样的判断了. */
const char *command1 = "set stest2 value2";
r = (redisReply *)redisCommand(ctx, command1);
if (NULL == r)
{
fprintf(stderr, "Execute [%s] failed
|
请发表评论