Пример #1
0
int test_range_long(int frompos, int slen, int count)
{
	int		fd;	
	int		endpos = frompos + slen;
	struct timeval start, end;
	redisReply *ret;

	ret = redisConnect(&fd, "127.0.0.1", 6379);
	if (NULL != ret) {
		DINFO("connect error! %s\n", ret->reply);
		return -1;
	}
	int  i;
	char *key = "haha";
	char val[32];
	char buf[128];

	gettimeofday(&start, NULL);	
	for (i = 0; i < count; i++) {
		sprintf(buf, "LRANGE %s %d %d", key, frompos, endpos - 1);
		//ret = redisCommand(fd, "LRANGE %s %d %d", key, frompos, slen);
		ret = redisCommand(fd, buf);
		if (ret->type != REDIS_REPLY_ARRAY) {
			DINFO("lrange error! %d, %s\n", ret->type, ret->reply);
			return -2;
		}
		if (ret->elements != slen) {
			DERROR("lrange count error: %d, len:%d\n", ret->elements, slen);
		}
		freeReplyObject(ret);
	}
	gettimeofday(&end, NULL);	

	unsigned int tmd = timediff(&start, &end);
	double speed = ((double)count / tmd) * 1000000;
	DINFO("range long use time: %u, speed: %.2f\n", tmd, speed);
	
	close(fd);
	return (int)speed;
}
Пример #2
0
long long _do_redis_command( const char ** args,const size_t * argvlen, size_t arg_count) {

    pthread_mutex_lock(&sredisContext_mutex);

    redisContext *c = NULL;
    redisReply *reply;


    c = (redisContext*)_redis_context_init();
    if (!c) {
	info_print("_redis_context_init return null, connect failed\n");
	pthread_mutex_unlock(&sredisContext_mutex);
	return -1;
    }

    debug_print("%s %s %s\n",args[0] ,args[1],args[2]);

    reply =  redisCommandArgv(c,arg_count,args,argvlen);
    if(!reply) {

    	c = (redisContext*)_redis_context_reinit();
        if (!c) {
            info_print("_do_redis_command, Cannot reconnect to redis\n ");
            pthread_mutex_unlock(&sredisContext_mutex);
            return -1;
        }
    	reply = redisCommandArgv(c,arg_count,args,argvlen);
        if (!reply) {
            info_print("_do_redis_command, reconnect to redis and re-execute redisCommandArgv failed\n ");
            pthread_mutex_unlock(&sredisContext_mutex);
            return -1;
        }
    }

	if(reply) {
	    freeReplyObject(reply);
	}
	pthread_mutex_unlock(&sredisContext_mutex);
    return 0;
}
Пример #3
0
//-------------------------------------------------------------------------------------
bool KBEEntityLogTableRedis::queryEntity(DBInterface * dbi, DBID dbid, EntityLog& entitylog, ENTITY_SCRIPT_UID entityType)
{
	/*
	kbe_entitylog:dbid:entityType = hashes(entityID, ip, port, componentID)
	*/
	redisReply* pRedisReply = NULL;

	try
	{
		static_cast<DBInterfaceRedis*>(dbi)->query(fmt::format("HMGET kbe_entitylog:{}:{} entityID ip port componentID",
			dbid, entityType), &pRedisReply, false);
	}
	catch(...)
	{
	}

	entitylog.dbid = dbid;
	entitylog.componentID = 0;
	entitylog.entityID = 0;
	entitylog.ip[0] = '\0';
	entitylog.port = 0;

	if(pRedisReply)
	{
		if(pRedisReply->type == REDIS_REPLY_ARRAY)
		{
			if(RedisHelper::check_array_results(pRedisReply))
			{
				StringConv::str2value(entitylog.entityID, pRedisReply->element[0]->str);
				kbe_snprintf(entitylog.ip, MAX_IP, "%s", pRedisReply->element[1]->str);
				StringConv::str2value(entitylog.port, pRedisReply->element[2]->str);
				StringConv::str2value(entitylog.componentID, pRedisReply->element[3]->str);
			}
		}
		
		freeReplyObject(pRedisReply); 
	}

	return entitylog.componentID > 0;
}
Пример #4
0
int redis_pull(char *redisqueuename, void *buf, 
		int maxload, size_t obj_size, int *numloaded, const char* cmd)
{
	assert(rctx);
	long elems_in_redis = redis_get_sizeof_list(redisqueuename);
	long num_to_add = MIN(elems_in_redis, maxload);
	log_info("redis", "INFO: redis load called on %s. Transfering %li "
			"of %li elements to in-memory queue.",
			redisqueuename,
			num_to_add, elems_in_redis);
	for(int i=0; i < num_to_add; i++) {
		redisAppendCommand(rctx, "%s %s", cmd, redisqueuename);
	}
	for(int i=0; i < num_to_add; i++) {
		redisReply *reply;
		int rc = redisGetReply(rctx, (void**) &reply);
		if (rc != REDIS_OK) {
			log_fatal("redis", "response from redis != REDIS_OK");
			return -1;
		}
		if (!reply) {
			log_fatal("redis", "no reply provided by redis.");
			return -1;
		}
		if (reply->type != REDIS_REPLY_STRING) {
			log_fatal("redis", 
					"unxpected reply type from redis.");
			return -1;
		}
		if ((size_t)reply->len != obj_size) {
			log_fatal("redis", "ERROR: unexpected lengthed "
					"object provided by redis.\n");
			return -1;
		}
		memcpy((void*)((intptr_t)buf+i*obj_size), reply->str, obj_size);
		freeReplyObject(reply);
	}
	*numloaded = num_to_add;
	return 0;
}
Пример #5
0
    // redis lrange: get list from start to end -- with R serialization
    Rcpp::List lrange(std::string key, int start, int end) {

        // uses binary protocol, see hiredis doc at github
        redisReply *reply = 
            static_cast<redisReply*>(redisCommand(prc_, "LRANGE %s %d %d", 
                                                  key.c_str(), start, end));

        unsigned int len = reply->elements;
        //Rcpp::Rcout << "Seeing " << len << " elements\n";
        Rcpp::List x(len);
        for (unsigned int i = 0; i < len; i++) {
            //Rcpp::Rcout << "  Seeing size " << reply->element[i]->len << "\n";
            int nc = reply->element[i]->len;
            Rcpp::RawVector res(nc);
            memcpy(res.begin(), reply->element[i]->str, nc);
            SEXP obj = unserializeFromRaw(res);
            x[i] = obj;
        }
                                               
        freeReplyObject(reply);
        return(x);
    }
Пример #6
0
int main()
{
    struct timeval timeout = {2, 0};
    redisContext *pRedisContext = (redisContext*)redisConnectWithTimeout("127.0.0.1", 6379, timeout);
    if((pRedisContext == NULL) || (pRedisContext->err))
    {
        if(pRedisContext)
        {
            std::cout << "connect error:" << pRedisContext->errstr << std::endl; 
        }else{
            std::cout << "connect error: can't allocate redis context" << std::endl;
        }
        return -1;
    }

    redisReply *pRedisReply = (redisReply*)redisCommand(pRedisContext, "INFO");
    std::cout << pRedisReply->str << std::endl;

    freeReplyObject(pRedisReply);
    
    return 0;
}
Пример #7
0
int main(int argc, char *argv[]) {
    unsigned int j;
    redisContext *c;
    redisReply *reply;

    struct timeval timeout = { 1, 500000 }; // 1.5 seconds
    c = redisConnectWithTimeout((char*)"127.0.0.2", 6379, timeout);
    if (c->err) {
        printf("Connection error: %s\n", c->errstr);
        exit(1);
    }


    for (int i=0; i < sizeof(testStrings)/sizeof(char*); i++) {
        double score = atof_raw(testStrings[i]);
        reply = redisCommand(c, "ZADD %s %.20e %s", "ascii|test", score, testStrings[i]);
        printf("result: %s\n", reply->str);
        freeReplyObject(reply);
    }
    
    return 0;
}
Пример #8
0
void *sumIntegerKeyProc(proxyContext *p, int argc, char **argv, redisKeyInfo *keyInfo){
    PROXY_NOTUSED(keyInfo);
    redisContext *c;
    redisReply *replyAll; 
    
    replyAll = createReplyObject(REDIS_REPLY_INTEGER);
    if( replyAll ){
        for( int i = 0; i < p->count; i++ ){
            redisReply *reply;
            c = getRedisContextWithIdx( p, i );
            reply = proxyCommandArgvList( p, c, argc, (const char **)argv );
            int value = 0;
            if( reply ) {
                value = reply->integer;
                freeReplyObject(reply);
            }
            
            replyAll->integer += value;
        }
    }
    return replyAll;
}
Пример #9
0
mrb_value mrb_redis_hkeys(mrb_state *mrb, mrb_value self)
{
    mrb_value key, array = mrb_nil_value();
    redisContext *rc = DATA_PTR(self);

    mrb_get_args(mrb, "o", &key);
    const char *argv[] = {"HKEYS", RSTRING_PTR(key)};
    size_t lens[] = {5, RSTRING_LEN(key)};
    redisReply *rr = redisCommandArgv(rc, 2, argv, lens);
    if (rr->type == REDIS_REPLY_ARRAY) {
        if (rr->elements > 0) {
            int i;

            array = mrb_ary_new(mrb);
            for (i = 0; i < rr->elements; i++) {
                mrb_ary_push(mrb, array, mrb_str_new(mrb, rr->element[i]->str, rr->element[i]->len));
            }
        }
    }
    freeReplyObject(rr);
    return array;
}
Пример #10
0
static void readHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
    client c = privdata;
    void *reply = NULL;
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(fd);
    REDIS_NOTUSED(mask);

    /* Calculate latency only for the first read event. This means that the
     * server already sent the reply and we need to parse it. Parsing overhead
     * is not part of the latency, so calculate it only once, here. */
    if (c->latency < 0) c->latency = ustime()-(c->start);

    if (redisBufferRead(c->context) != REDIS_OK) {
        fprintf(stderr,"Error: %s\n",c->context->errstr);
        exit(1);
    } else {
        while(c->pending) {
            if (redisGetReply(c->context,&reply) != REDIS_OK) {
                fprintf(stderr,"Error: %s\n",c->context->errstr);
                exit(1);
            }
            if (reply != NULL) {
                if (reply == (void*)REDIS_REPLY_ERROR) {
                    fprintf(stderr,"Unexpected error reply, exiting...\n");
                    exit(1);
                }

                freeReplyObject(reply);

                if (config.requests_finished < config.requests)
                    config.latency[config.requests_finished++] = c->latency;
                c->pending--;
                if (c->pending == 0) clientDone(c);
            } else {
                break;
            }
        }
    }
}
Пример #11
0
void keys(const char *pattern)
{
    int i;
    redisReply *reply;
    reply = redisCommand(ctx, "KEYS %s", pattern);
    if (reply == NULL)
    {
        log_error("keys fails: %s", ctx->errstr);
        // handle error
        return;
    }
    if (reply->type == REDIS_REPLY_ARRAY) {
        for (i = 0; i < reply->elements; i++) {
            log_debugv("%d) %s", i, reply->element[i]->str);
        }
    }
    else {
        log_warn("keys: unexpected reply type: %d", reply->type);
    }

    freeReplyObject(reply);
}
Пример #12
0
void set_int_ex_nx(const char *key, int val, int timeout)
{
    redisReply *reply;
    reply = redisCommand(ctx, "SET %s %d EX %d NX", key, val, timeout);
    if (reply == NULL)
    {
        log_error("set_int_ex_nx fails: %s", ctx->errstr);
        // handle error
        return;
    }
    if (reply->type == REDIS_REPLY_STATUS) {
        log_debugv("set_int_ex_nx %s %d %s", key, val, reply->str);
    }
    else if (reply->type == REDIS_REPLY_NIL) {
        log_debugv("set_int_ex_nx: %s exists", key);
    }
    else {
        log_warn("set_int_ex_nx: unexpected reply type: %d", reply->type);
    }

    freeReplyObject(reply);
}
Пример #13
0
int add_one(pyrebloomctxt *ctxt, const char *data, uint32_t data_size)
{
    uint32_t ct = 0, total = 0, count = 1;
    redisReply *reply = NULL;

    for (uint32_t i = 0; i < ctxt->hashes; ++i) {
        uint64_t hashed_data = hash(data, data_size, ctxt->seeds[i], ctxt->bits);
        redisAppendCommand(ctxt->ctxt, "SETBIT %s %lu 1",
            ctxt->keys[hashed_data / max_bits_per_key], hashed_data % max_bits_per_key);
    }

    for (uint32_t i = 0, ct = 0; i < ctxt->hashes; ++i) {
        /* Make sure that we were able to read a reply. Otherwise, provide
         * an error response */
        if (redisGetReply(ctxt->ctxt, (void**)(&reply)) == REDIS_ERR) {
            strncpy(ctxt->ctxt->errstr, "No pending replies", errstr_size);
            ctxt->ctxt->err = PYREBLOOM_ERROR;
            return PYREBLOOM_ERROR;
        }

        /* Consume and read the response */
        if (reply->type == REDIS_REPLY_ERROR) {
            ctxt->ctxt->err = PYREBLOOM_ERROR;
            strncpy(ctxt->ctxt->errstr, reply->str, errstr_size);
        } else {
            ct += reply->integer;
        }
        freeReplyObject(reply);
    }
    if (ct == ctxt->hashes) {
        total = 1;
    }

    if (ctxt->ctxt->err == PYREBLOOM_ERROR) {
        return PYREBLOOM_ERROR;
    }

    return count - total;
}
Пример #14
0
int hiredis_odb_backend__exists(git_odb_backend *_backend, const git_oid *oid)
{
	hiredis_odb_backend *backend;
	int found;
	redisReply *reply;
	char *str_id = calloc(GIT_OID_HEXSZ + 1, sizeof(char));

	assert(_backend && oid);

	backend = (hiredis_odb_backend *) _backend;
	found = 0;

	git_oid_tostr(str_id, GIT_OID_HEXSZ, oid);

	reply = redisCommand(backend->db, "exists %s:%s:odb:%s", backend->prefix, backend->repo_path, str_id);
	if (reply->type == REDIS_REPLY_INTEGER)
		found = reply->integer;

	free(str_id);
	freeReplyObject(reply);
	return found;
}
Пример #15
0
bool Redis::Delete(string &key)
{
    redisReply* reply = NULL;

    log4cpp::Category& _logger = log4cpp::Category::getInstance("MAIN_LOG");
    
    reply = (redisReply*)redisCommand(connect_, "del %s", key.c_str());

    if (!reply){
        ReConnect();

        reply = (redisReply*)redisCommand(connect_, "del %s", key.c_str());
        if (!reply){
            _logger.error("delete key %s from redis error", key.c_str());
            return RESULT_ERROR;
        }
    }

    _logger.info("delete key %s from redis OK", key.c_str());
    freeReplyObject(reply);
    return RESULT_OK;
}
Пример #16
0
static bool mapClient( disruptor* d, unsigned int id )
{
    assert( id < MAX_CONNECTIONS );
    if ( id >= MAX_CONNECTIONS )
        return false;

    unmapClient( d, id );

    {
        shmem* s;
        int64_t size;

        s = shmemOpen( 0, SHMEM_MUST_NOT_CREATE, "disruptor:%s:%d", d->address, id );
        if ( !s )
            return false;

        size = shmemGetSize( s );
        d->buffers[ id ].shmem = s;
        d->buffers[ id ].start = shmemGetPtr( s );
        d->buffers[ id ].end = ( d->buffers[ id ].start + size );
        d->buffers[ id ].tail = d->buffers[ id ].start;
        handleInfo( d, "for #%d: size=%u", id, (unsigned int)size );

        {
            redisContext* r = d->redis;
            redisReply* reply;

            reply = redisCommand( r, "GET disruptor:%s:%d:username", d->address, id );
            if ( reply->type == REDIS_REPLY_STRING )
                d->names[ id ] = strclone( reply->str );
            freeReplyObject( reply );
        }

        if ( !d->names[ id ] )
            return false;

        return true;
    }
}
Пример #17
0
static int llpush(lua_State *L){
    if (!lua_isuserdata(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L ,3)) {
        LOG_ERROR("arg error");
        return 0;
    }
    struct redisContext *c = lua_touserdata(L, 1);
    if (c == NULL) {
        LOG_ERROR("userdata is null");
        return 0;
    }
    const char *key = (const char *)lua_tostring(L, 2);
    size_t str_len;
    const char *str = (const char *)lua_tolstring(L, 3, &str_len);
    redisReply * reply = (redisReply *)redisCommand(c, "LPUSH %s %b", key, str, str_len);
    if (reply == NULL) {
        LOG_ERROR("lpush fail key:%s value:%s", key, str);
        return 0;
    }
    getCallback_push_reply(L, reply);
    freeReplyObject(reply);
    return 1;
}
static redisContext*
ngx_http_dynamic_redirect_redis_connect(ngx_http_dynamic_redirect_loc_conf_t* conf)
{
    if (!conf->redis_context) {
        conf->redis_context = ngx_palloc(ngx_cycle->pool, sizeof(redis_connection));

        if (!conf->redis_context) {
            return NULL;
        }
        ngx_queue_insert_tail(&redis_connection_queue->queue, &conf->redis_context->queue);
    }

    if (!conf->redis_context->redis_context || conf->redis_context->redis_context->err) {
        if (conf->redis_context->redis_context) {
            redisFree(conf->redis_context->redis_context);
        }

        conf->redis_context->redis_context = redisConnect((char *) conf->redis_hostname.data, conf->redis_port);

        if (!conf->redis_context->redis_context) {
            ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "Error connecting to Redis: cannot allocate redis context");
            return NULL;
        }

        redisReply* reply = redisCommand(conf->redis_context->redis_context, "SELECT %d", conf->redis_db);

        if (!reply || reply->type == REDIS_REPLY_ERROR) {
            ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "Error connecting to Redis: cannot select the correct database");
            return NULL;
        }

        if (reply->type == REDIS_REPLY_STRING) {
            ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0, "Redis database [%d] selected", conf->redis_db);
            freeReplyObject(reply);
        }
    }

    return conf->redis_context->redis_context;
}
Пример #19
0
int clear_key(char *key)
{
	int fd;
	redisReply *ret;

	ret = redisConnect(&fd, "127.0.0.1", 6379);
	if (NULL != ret) {
		DINFO("connect error! %s\n", ret->reply);
		return -1;
	}
	
	ret = redisCommand(fd, "DEL %s", key);
	if (ret->type != REDIS_REPLY_INTEGER) {
		DINFO("DEL %s error! ret: %d, %s\n", key, ret->type, ret->reply);
		return -2;
	}
	freeReplyObject(ret);
	
	close(fd);
	
	return 0;
}
Пример #20
0
int db_plugin_verify(char *pluginkey)
{
  redisReply *reply;
  bool valid = false;

  if (!rc)
    return (-1);

  reply = redisCommand(rc, "Exists %s", pluginkey);

  if (reply->type != REDIS_REPLY_INTEGER)
    LOG_WARNING("Redis failed to query plugin key existence: %s", reply->str);
  else
    valid = reply->integer == 1;

  freeReplyObject(reply);

  if (!valid)
    return (-1);

  return (0);
}
Пример #21
0
bool RTHiredis::CmdHGet(const std::string hid, const std::string key, std::string& value)
{

    if (!m_redisContext || hid.empty() || key.empty()) {
        return false;
    }
    redisReply* m_redisReply = (redisReply*)redisCommand(m_redisContext, "HGET %s %s", hid.c_str(), key.c_str());
    if (!m_redisReply || m_redisReply->type == REDIS_REPLY_ERROR) {
        LE("redis run error\n");
        if (m_redisReply) {
            LE("error::%s\n", m_redisReply->str);
        }
        return false;
    }
    std::list<const std::string> ulist;
    HandleHReply(m_redisReply, &ulist);
    if (ulist.size()>0) {
        value.assign(ulist.front());
    }
    freeReplyObject((void*)m_redisReply);
    return true;
}
Пример #22
0
Файл: tool.c Проект: bugou/test
void print_sset(redis_instance* inst, char* sset, size_t len)
{
    /*
    kv = (redisReply*)redisCommand(inst->cxt, "zrange %s 0 -1 withscores", key);
    assert (kv != nil);
    assert(kv->type == REDIS_REPLY_ARRAY);
    assert(kv->elements != 0);

    pline("{idx:%lu, sset:%s, member-score num:%lu,", index++, key, kv->elements);
    for (unsigned j = 0; j < kv->elements; j += 2) {
    pline("    {idx:%u, member:%s, score:%s},", j, kv->element[i]->str, kv->element[i + 1]->str);
    }
    pline("}\n");
    freeReplyObject(kv);
    */
    long index = 0;
    long long cursor = 0;
    redisReply* keys;
    do {
        redisReply* reply = (redisReply*)redisCommand(
                    inst->cxt, "zscan %b %lld count %lld",
                    sset, len, cursor, SCAN_INC);
        assert(reply != nil);
        assert(reply->type == REDIS_REPLY_ARRAY);
        assert(2 == reply->elements);
        assert(REDIS_REPLY_STRING == reply->element[0]->type);
        assert(REDIS_REPLY_ARRAY == reply->element[1]->type);

        redisReply *keys = reply->element[1];
        for (size_t i = 0; i < keys->elements; i += 2)  {
            printf("\n    [cursor:%u, key:%s, value:%s],",
                   index++, keys->element[i]->str, keys->element[i + 1]->str);
        }

        cursor = strtoll(reply->element[0]->str, (char**)nil, 10);
        freeReplyObject(reply);
    } while(cursor != 0);
}
RedisReply::RedisReply(DBConnector *db, string command, int exepectedType, bool isFormatted)
{
    SWSS_LOG_ENTER();

    SWSS_LOG_DEBUG("Redis reply command: %s", command.c_str());

    if (isFormatted)
    {
        redisAppendFormattedCommand(db->getContext(), command.c_str(), command.length());
        redisGetReply(db->getContext(), (void**)&m_reply);
    }
    else
    {
        m_reply = (redisReply *)redisCommand(db->getContext(), command.c_str());
    }

    if (!m_reply)
    {
        SWSS_LOG_ERROR("Redis reply is NULL, memory exception, command: %s", command.c_str());

        throw system_error(make_error_code(errc::not_enough_memory),
                           "Memory exception, reply is null");
    }

    if (m_reply->type != exepectedType)
    {
        const char *err = (m_reply->type == REDIS_REPLY_STRING || m_reply->type == REDIS_REPLY_ERROR) ?
            m_reply->str : "NON-STRING-REPLY";

        SWSS_LOG_ERROR("Expected to get redis type %d got type %d, command: %s, err: %s",
                      exepectedType, m_reply->type, command.c_str(), err);
        freeReplyObject(m_reply);
        m_reply = NULL; /* Some compilers call destructor in this case */

        throw system_error(make_error_code(errc::io_error),
                           "Wrong expected type of result");
    }
}
Пример #24
0
bool CRedisClient::TestOnline()
{
	m_locker->lock();
	std::string cmd = "PING";
	redisReply* pReply = (redisReply*)redisCommand( m_pRedisContext ,cmd.c_str() );
	if (pReply != NULL)
	{
		m_locker->unlock();
		freeReplyObject(pReply);
		pReply = NULL;
		return true;
	}
	else
	{//链接已经断开,开始重连计数,重连三次以后链接不上则认为此数据库已下线,将在client管理中进行剔除
		m_locker->unlock();
		if(ReConnect())
		{
			WLogInfo("CRedisClient::TestOnline::RedisClient Re Online! ip=%s, port=%d\n", m_address.c_str(), m_port);
			m_iReconnectCount = 0;
			return true;
		}
		else
		{
			m_iReconnectCount++;
			if (m_iReconnectCount > 3)
			{
				WLogError("CRedisClient::TestOnline::RedisClient Off! ip=%s, port=%d\n", m_address.c_str(), m_port);
				return false;
			}
			else
			{
				return true;
			}
		}
	}

	return false;
}
Пример #25
0
bool  QTSServerInterface::RedisTTL()//注意当网络在一段时间很差时可能会因为超时时间达到而导致key被删除,这时应该重新设置该key
{

	OSMutexLocker mutexLock(&fRedisMutex);

	bool bReval=false;
	if(!ConRedis())//每一次执行命令之前都先连接redis,如果当前redis还没有成功连接
		return false;

	char chTemp[128]={0};//注意128位是否足够
	sprintf(chTemp,"expire  %s:%d_Live 15",fCMSIP.c_str(),fCMSPort);//更改超时时间

	redisReply* reply = (redisReply*)redisCommand(fRedisCon,chTemp);
	//需要注意的是,如果返回的对象是NULL,则表示客户端和服务器之间出现严重错误,必须重新链接。
	if (NULL == reply) 
	{
		redisFree(fRedisCon);
		fIfConSucess=false;
		return false;
	}

	if(reply->type==REDIS_REPLY_INTEGER&&reply->integer==1)//正常情况
	{
		bReval=true;
	}
	else if(reply->type==REDIS_REPLY_INTEGER&&reply->integer==0)//说明当前key已经不存在了,那么我们需要重新生成该key
	{
		sprintf(chTemp,"setex %s:%d_Live 15 1",fCMSIP.c_str(),fCMSPort);
		bReval=RedisCommand(chTemp);
	}
	else//其他情况
	{
		//当redis服务器不具有写的权限,但配置文件配置了持久化时,可能出现这种情况
		Assert(0);
	}
	freeReplyObject(reply);
	return bReval;
}
Пример #26
0
bool RedisListModel::GetData( const std::string& key, RedisResult& results )
{
    bool retVal = false;
    ScopedRedisReply lenreply = GetClient()->Command("LLEN %s", key.c_str());
    if (lenreply.IsNull())
    {
        return false;
    }
    if (lenreply->type == REDIS_REPLY_INTEGER)
    {
         long long llen = lenreply->integer;
		 results.NewColumn("Value");
         for (int idx=0; idx<llen; )
         {
             redisReply* reply = GetClient()->Command("LRANGE %s %d %d", key.c_str(), idx, idx+1000 > llen ? idx+1000 : llen - idx);
             if (!reply)  return retVal;
            
             if (reply->type == REDIS_REPLY_ARRAY)
             {
                 std::size_t i = 0;
                 redisReply* tmpReply ;
                 while (i < reply->elements)
                 {
                     tmpReply = reply->element[i];
                     results.NewRow();
                     string& myvalue = results.Value(results.RowSize()-1, 0);
                     myvalue.assign(tmpReply->str, tmpReply->len);
                     i++;
                 }
                 retVal = true;
             }
             freeReplyObject(reply);
             idx+=1000;
         }
    }

    return retVal;
}
Пример #27
0
int redisc_destroy(void)
{
	redisc_reply_t *rpl, *next_rpl;

	redisc_server_t *rsrv=NULL;
	redisc_server_t *rsrv1=NULL;

	rpl = _redisc_rpl_list;
	while(rpl != NULL)
	{
		next_rpl = rpl->next;
		if(rpl->rplRedis)
			freeReplyObject(rpl->rplRedis);

		if(rpl->rname.s != NULL)
			pkg_free(rpl->rname.s);

		pkg_free(rpl);
		rpl = next_rpl;
	}
	_redisc_rpl_list = NULL;

	if(_redisc_srv_list==NULL)
		return -1;
	rsrv=_redisc_srv_list;
	while(rsrv!=NULL)
	{
		rsrv1 = rsrv;
		rsrv=rsrv->next;
		if(rsrv1->ctxRedis!=NULL)
			redisFree(rsrv1->ctxRedis);
		free_params(rsrv1->attrs);
		pkg_free(rsrv1);
	}
	_redisc_srv_list = NULL;

	return 0;
}
coo_matrix_t* load_coo_matrix (redisContext *c)
{
	redisReply *reply;
	size_t i;
	coo_matrix_t* coo;
	coo = malloc (sizeof (coo_matrix_t) );
	reply = redisCommand (c, "GET current_size");
	coo->current_size = atoi (reply->str);
	freeReplyObject (reply);
	reply = redisCommand (c, "GET size");
	coo->size = atoi (reply->str);
	coo->entries = malloc (coo->size * sizeof (coo_entry_t) );
	reply = redisCommand (c, "lrange coo_entries_column_j 0 -1");
	if (reply->type == REDIS_REPLY_ARRAY && reply->elements == coo->size)
	{
		for (i = 0; i < reply->elements; i++)
		{
			coo->entries[i].column_j = atoi (reply->element[i]->str);
		}
	}
	reply = redisCommand (c, "lrange coo_entries_row_i 0 -1");
	if (reply->type == REDIS_REPLY_ARRAY && reply->elements == coo->size)
	{
		for (i = 0; i < reply->elements; i++)
		{
			coo->entries[i].row_i = atoi (reply->element[i]->str);
		}
	}
	reply = redisCommand (c, "lrange coo_entries_value 0 -1");
	if (reply->type == REDIS_REPLY_ARRAY && reply->elements == coo->size)
	{
		for (i = 0; i < reply->elements ; i++)
		{
			coo->entries[i].value = atof (reply->element[i]->str);
		}
	}
	return coo;
}
Пример #29
0
EpochlibRedisExecute RedisConnector::execute(const char *format, ...) {
	this->_reconnect(0);

	va_list ap;
	EpochlibRedisExecute returnObj;
	redisReply *reply = NULL;

	while (reply == NULL) {
		// Lock, execute, unlock
		this->contextMutex.lock();
		va_start(ap, format);
		reply = (redisReply *)redisvCommand(this->context, format, ap);
		va_end(ap);
		this->contextMutex.unlock();

		if (reply->type == REDIS_REPLY_ERROR) {
			returnObj.success = false;
			returnObj.message = reply->str;
			this->config.logger->log("[Redis] Error command " + std::string(reply->str));
		}
		else {
			returnObj.success = true;

			if (reply->type == REDIS_REPLY_STRING) {
				returnObj.message = reply->str;
			}
			else if (reply->type == REDIS_REPLY_INTEGER) {
				std::stringstream IntToString;
				IntToString << reply->integer;
				returnObj.message = IntToString.str();
			}
		}
	}

	freeReplyObject(reply);

	return returnObj;
}
Пример #30
0
//-------------------------------------------------------------------------------------
bool KBEAccountTableRedis::queryAccountAllInfos(DBInterface * dbi, const std::string& name, ACCOUNT_INFOS& info)
{
	/*
	kbe_accountinfos:accountName = hashes(password, bindata, email, entityDBID, flags, deadline, regtime, lasttime, numlogin)
	*/
	redisReply* pRedisReply = NULL;

	try
	{
		static_cast<DBInterfaceRedis*>(dbi)->query(fmt::format("HMGET kbe_accountinfos:{} entityDBID password email flags deadline",
			name), &pRedisReply, false);
	}
	catch(...)
	{
	}
	
	info.dbid = 0;
	
	if(pRedisReply)
	{
		if(pRedisReply->type == REDIS_REPLY_ARRAY)
		{
			if(RedisHelper::check_array_results(pRedisReply))
			{			
				StringConv::str2value(info.dbid, pRedisReply->element[0]->str);
				info.name = name;
				info.password = pRedisReply->element[1]->str;
				info.email = pRedisReply->element[2]->str;
				StringConv::str2value(info.flags, pRedisReply->element[3]->str);
				StringConv::str2value(info.deadline, pRedisReply->element[4]->str);
			}
		}
		
		freeReplyObject(pRedisReply); 
	}

	return info.dbid > 0;
}