From 8298301e0afdade06971f1be1466d0d09ddc25e4 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 21:12:42 +0800 Subject: [PATCH 01/24] delete the interface and let external application reference one --- src/hiredis.h | 213 -------------------------------------------------- 1 file changed, 213 deletions(-) delete mode 100644 src/hiredis.h diff --git a/src/hiredis.h b/src/hiredis.h deleted file mode 100644 index c65098b..0000000 --- a/src/hiredis.h +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2009-2011, Salvatore Sanfilippo - * Copyright (c) 2010-2011, Pieter Noordhuis - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Redis nor the names of its contributors may be used - * to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __HIREDIS_H -#define __HIREDIS_H -#include /* for size_t */ -#include /* for va_list */ -#include /* for struct timeval */ - -#define HIREDIS_MAJOR 0 -#define HIREDIS_MINOR 11 -#define HIREDIS_PATCH 0 - -#define REDIS_ERR -1 -#define REDIS_OK 0 - -/* When an error occurs, the err flag in a context is set to hold the type of - * error that occured. REDIS_ERR_IO means there was an I/O error and you - * should use the "errno" variable to find out what is wrong. - * For other values, the "errstr" field will hold a description. */ -#define REDIS_ERR_IO 1 /* Error in read or write */ -#define REDIS_ERR_EOF 3 /* End of file */ -#define REDIS_ERR_PROTOCOL 4 /* Protocol error */ -#define REDIS_ERR_OOM 5 /* Out of memory */ -#define REDIS_ERR_OTHER 2 /* Everything else... */ - -/* Connection type can be blocking or non-blocking and is set in the - * least significant bit of the flags field in redisContext. */ -#define REDIS_BLOCK 0x1 - -/* Connection may be disconnected before being free'd. The second bit - * in the flags field is set when the context is connected. */ -#define REDIS_CONNECTED 0x2 - -/* The async API might try to disconnect cleanly and flush the output - * buffer and read all subsequent replies before disconnecting. - * This flag means no new commands can come in and the connection - * should be terminated once all replies have been read. */ -#define REDIS_DISCONNECTING 0x4 - -/* Flag specific to the async API which means that the context should be clean - * up as soon as possible. */ -#define REDIS_FREEING 0x8 - -/* Flag that is set when an async callback is executed. */ -#define REDIS_IN_CALLBACK 0x10 - -/* Flag that is set when the async context has one or more subscriptions. */ -#define REDIS_SUBSCRIBED 0x20 - -/* Flag that is set when monitor mode is active */ -#define REDIS_MONITORING 0x40 - -#define REDIS_REPLY_STRING 1 -#define REDIS_REPLY_ARRAY 2 -#define REDIS_REPLY_INTEGER 3 -#define REDIS_REPLY_NIL 4 -#define REDIS_REPLY_STATUS 5 -#define REDIS_REPLY_ERROR 6 - -#define REDIS_READER_MAX_BUF (1024*16) /* Default max unused reader buffer. */ - -#define REDIS_KEEPALIVE_INTERVAL 15 /* seconds */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* This is the reply object returned by redisCommand() */ -typedef struct redisReply { - int type; /* REDIS_REPLY_* */ - long long integer; /* The integer when type is REDIS_REPLY_INTEGER */ - int len; /* Length of string */ - char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */ - size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */ - struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */ -} redisReply; - -typedef struct redisReadTask { - int type; - int elements; /* number of elements in multibulk container */ - int idx; /* index in parent (array) object */ - void *obj; /* holds user-generated value for a read task */ - struct redisReadTask *parent; /* parent task */ - void *privdata; /* user-settable arbitrary field */ -} redisReadTask; - -typedef struct redisReplyObjectFunctions { - void *(*createString)(const redisReadTask*, char*, size_t); - void *(*createArray)(const redisReadTask*, int); - void *(*createInteger)(const redisReadTask*, long long); - void *(*createNil)(const redisReadTask*); - void (*freeObject)(void*); -} redisReplyObjectFunctions; - -/* State for the protocol parser */ -typedef struct redisReader { - int err; /* Error flags, 0 when there is no error */ - char errstr[128]; /* String representation of error when applicable */ - - char *buf; /* Read buffer */ - size_t pos; /* Buffer cursor */ - size_t len; /* Buffer length */ - size_t maxbuf; /* Max length of unused buffer */ - - redisReadTask rstack[9]; - int ridx; /* Index of current read task */ - void *reply; /* Temporary reply pointer */ - - redisReplyObjectFunctions *fn; - void *privdata; -} redisReader; - -/* Public API for the protocol parser. */ -redisReader *redisReaderCreate(void); -void redisReaderFree(redisReader *r); -int redisReaderFeed(redisReader *r, const char *buf, size_t len); -int redisReaderGetReply(redisReader *r, void **reply); - -/* Backwards compatibility, can be removed on big version bump. */ -#define redisReplyReaderCreate redisReaderCreate -#define redisReplyReaderFree redisReaderFree -#define redisReplyReaderFeed redisReaderFeed -#define redisReplyReaderGetReply redisReaderGetReply -#define redisReplyReaderSetPrivdata(_r, _p) (int)(((redisReader*)(_r))->privdata = (_p)) -#define redisReplyReaderGetObject(_r) (((redisReader*)(_r))->reply) -#define redisReplyReaderGetError(_r) (((redisReader*)(_r))->errstr) - -/* Function to free the reply objects hiredis returns by default. */ -void freeReplyObject(void *reply); - -/* Functions to format a command according to the protocol. */ -int redisvFormatCommand(char **target, const char *format, va_list ap); -int redisFormatCommand(char **target, const char *format, ...); -int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen); - -/* Context for a connection to Redis */ -typedef struct redisContext { - int err; /* Error flags, 0 when there is no error */ - char errstr[128]; /* String representation of error when applicable */ - int fd; - int flags; - char *obuf; /* Write buffer */ - redisReader *reader; /* Protocol reader */ -} redisContext; - -redisContext *redisConnect(const char *ip, int port); -redisContext *redisConnectWithTimeout(const char *ip, int port, const struct timeval tv); -redisContext *redisConnectNonBlock(const char *ip, int port); -redisContext *redisConnectUnix(const char *path); -redisContext *redisConnectUnixWithTimeout(const char *path, const struct timeval tv); -redisContext *redisConnectUnixNonBlock(const char *path); -int redisSetTimeout(redisContext *c, const struct timeval tv); -int redisEnableKeepAlive(redisContext *c); -void redisFree(redisContext *c); -int redisBufferRead(redisContext *c); -int redisBufferWrite(redisContext *c, int *done); - -/* In a blocking context, this function first checks if there are unconsumed - * replies to return and returns one if so. Otherwise, it flushes the output - * buffer to the socket and reads until it has a reply. In a non-blocking - * context, it will return unconsumed replies until there are no more. */ -int redisGetReply(redisContext *c, void **reply); -int redisGetReplyFromReader(redisContext *c, void **reply); - -/* Write a command to the output buffer. Use these functions in blocking mode - * to get a pipeline of commands. */ -int redisvAppendCommand(redisContext *c, const char *format, va_list ap); -int redisAppendCommand(redisContext *c, const char *format, ...); -int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); - -/* Issue a command to Redis. In a blocking context, it is identical to calling - * redisAppendCommand, followed by redisGetReply. The function will return - * NULL if there was an error in performing the request, otherwise it will - * return the reply. In a non-blocking context, it is identical to calling - * only redisAppendCommand and will always return NULL. */ -void *redisvCommand(redisContext *c, const char *format, va_list ap); -void *redisCommand(redisContext *c, const char *format, ...); -void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); - -#ifdef __cplusplus -} -#endif - -#endif From f7776fae82eb62948fa7f2daebc2627c497ac4ec Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 21:17:45 +0800 Subject: [PATCH 02/24] cpp lint --- {src => include/xredis}/xLock.h | 45 +- include/xredis/xRedisClient.h | 385 +++++++++++++++ {src => include/xredis}/xRedisClusterClient.h | 161 ++++--- include/xredis/xRedisPool.h | 181 +++++++ src/xRedisClient.cpp | 451 +++++++++++------- src/xRedisClient.h | 379 --------------- src/xRedisClient_connection.cpp | 25 +- src/xRedisClient_hashs.cpp | 56 ++- src/xRedisClient_keys.cpp | 126 +++-- src/xRedisClient_lists.cpp | 110 +++-- src/xRedisClient_pubsub.cpp | 66 +-- src/xRedisClient_sets.cpp | 162 ++++--- src/xRedisClient_sortedsets.cpp | 114 +++-- src/xRedisClient_strings.cpp | 140 +++--- src/xRedisClusterClient.cpp | 396 ++++++++------- src/xRedisPool.cpp | 377 +++++++++------ src/xRedisPool.h | 182 ------- 17 files changed, 1900 insertions(+), 1456 deletions(-) rename {src => include/xredis}/xLock.h (74%) create mode 100644 include/xredis/xRedisClient.h rename {src => include/xredis}/xRedisClusterClient.h (53%) create mode 100644 include/xredis/xRedisPool.h delete mode 100644 src/xRedisClient.h delete mode 100644 src/xRedisPool.h diff --git a/src/xLock.h b/include/xredis/xLock.h similarity index 74% rename from src/xLock.h rename to include/xredis/xLock.h index ceb78ed..33ae3f9 100644 --- a/src/xLock.h +++ b/include/xredis/xLock.h @@ -6,7 +6,6 @@ * ---------------------------------------------------------------------------- */ - #ifndef _XLOCK_H_ #define _XLOCK_H_ @@ -18,17 +17,18 @@ #include #endif - -class xLock { +class xLock +{ private: #ifdef WIN32 - CRITICAL_SECTION mSection; + CRITICAL_SECTION mSection; #else - pthread_mutex_t mMutex; + pthread_mutex_t mMutex; #endif - + public: - inline xLock() { + inline xLock() + { #ifdef WIN32 InitializeCriticalSection(&mSection); #else @@ -36,26 +36,30 @@ class xLock { pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); int ret = pthread_mutex_init(&mMutex, &attr); - if(ret != 0 ){ - fprintf(stderr,"pthread_mutex_init error %d \n\r",ret); + if (ret != 0) + { + fprintf(stderr, "pthread_mutex_init error %d \n\r", ret); } #endif }; - inline ~xLock() { + inline ~xLock() + { #ifdef WIN32 DeleteCriticalSection(&mSection); #else pthread_mutex_destroy(&mMutex); #endif } - inline void Enter() { + inline void Enter() + { #ifdef WIN32 EnterCriticalSection(&mSection); #else pthread_mutex_lock(&mMutex); #endif } - inline void Leave() { + inline void Leave() + { #ifdef WIN32 LeaveCriticalSection(&mSection); #else @@ -64,19 +68,22 @@ class xLock { }; }; -class CLockUser { +class CLockUser +{ public: - inline CLockUser(xLock& lock):mlock(lock) { + inline CLockUser(xLock &lock) : mlock(lock) + { mlock.Enter(); - }; - inline ~CLockUser(){ + }; + inline ~CLockUser() + { mlock.Leave(); } + private: - xLock& mlock; + xLock &mlock; }; #define XLOCK(T) CLockUser lock(T) -#endif - +#endif diff --git a/include/xredis/xRedisClient.h b/include/xredis/xRedisClient.h new file mode 100644 index 0000000..2388acb --- /dev/null +++ b/include/xredis/xRedisClient.h @@ -0,0 +1,385 @@ +/* + * ---------------------------------------------------------------------------- + * Copyright (c) 2013-2014, xSky + * All rights reserved. + * Distributed under GPL license. + * ---------------------------------------------------------------------------- + */ + +#ifndef _XREDIS_CLIENT_H_ +#define _XREDIS_CLIENT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrc +{ + +#define REDIS_REPLY_STRING 1 +#define REDIS_REPLY_ARRAY 2 +#define REDIS_REPLY_INTEGER 3 +#define REDIS_REPLY_NIL 4 +#define REDIS_REPLY_STATUS 5 +#define REDIS_REPLY_ERROR 6 + +#define MAX_ERR_STR_LEN 128 + +typedef std::string KEY; +typedef std::string VALUE; +typedef std::vector KEYS; +typedef KEYS FILEDS; +typedef std::vector VALUES; +typedef std::vector VDATA; + +typedef std::set SETDATA; + +typedef struct _REDIS_NODE_ +{ + uint32_t dbindex; // 节点编号索引,从0开始 + std::string host; // REDIS节点主机IP地址 + uint32_t port; // redis服务端口 + std::string passwd; // redis认证密码 + uint32_t poolsize; // 此节点上的连接池大小 + uint32_t timeout; // 连接超时时间 秒 + uint32_t role; // 节点角色 +} RedisNode; + +/* This is the reply object returned by redisCommand() */ +typedef struct rReply +{ + int32_t type; /* REDIS_REPLY_* */ + long long integer; /* The integer when type is REDIS_REPLY_INTEGER */ + int32_t len; /* Length of string */ + char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */ + size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */ + struct rReply **element; /* elements vector for REDIS_REPLY_ARRAY */ +} rReply; + +typedef uint32_t (*HASHFUN)(const char *); + +class RedisPool; +class xRedisClient; + +class RedisDBIdx +{ +public: + RedisDBIdx(); + RedisDBIdx(xRedisClient *xredisclient); + ~RedisDBIdx(); + + bool CreateDBIndex(const char *key, HASHFUN fun, uint32_t type); + bool CreateDBIndex(int64_t id, uint32_t type); + char *GetErrInfo() { return mStrerr; } + void SetIOMaster(); + +private: + bool SetErrInfo(const char *info, int32_t len); + void IOtype(uint32_t type); + friend class xRedisClient; + +private: + uint32_t mType; + uint32_t mIndex; + char *mStrerr; + xRedisClient *mClient; + uint32_t mIOtype; + bool mIOFlag; +}; + +typedef struct _DATA_ITEM_ +{ + int32_t type; + std::string str; + + _DATA_ITEM_ &operator=(const _DATA_ITEM_ &data) + { + type = data.type; + str = data.str; + return *this; + } +} DataItem; +typedef std::vector ReplyData; +typedef ReplyData ArrayReply; +typedef std::map ZSETDATA; +typedef std::vector DBIArray; + +typedef struct xRedisContext_ +{ + void *conn; +} xRedisContext; + +typedef enum _SET_TYPE_ +{ + TYPE_NONE = 0, + PX = 1, + EX = 2 +} SETPXEX; + +typedef enum _SET_TYPE_NXEX_ +{ + TNXXX_NONE = 0, + NX = 1, + XX = 2 +} SETNXXX; + +typedef enum _BIT_OP_ +{ + AND = 0, + OR = 1, + XOR = 2, + NOT = 3 +} BITOP; + +typedef enum _LIST_MODEL_ +{ + BEFORE = 0, + AFTER = 1 +} LMODEL; + +typedef enum _SORT_ORDER_ +{ + ASC = 0, + DESC = 1 +} SORTODER; + +typedef struct _SORT_LIMIT_ +{ + int32_t offset; + int32_t count; +} LIMIT; + +template +std::string toString(const T &t) +{ + std::ostringstream oss; + oss << t; + return oss.str(); +} + +typedef enum _REDIS_ROLE_ +{ + MASTER = 0, + SLAVE = 1 +} ROLE; + +#define SETDEFAULTIOTYPE(type) \ + if (!dbi.mIOFlag) \ + { \ + SetIOtype(dbi, type); \ + } + +class xRedisClient +{ +public: + xRedisClient(); + ~xRedisClient(); + + bool Init(uint32_t maxtype); + void Release(); + void Keepalive(); + inline RedisPool *GetRedisPool(); + static void FreeReply(const rReply *reply); + static int32_t GetReply(xRedisContext *ctx, ReplyData &vData); + bool GetxRedisContext(const RedisDBIdx &dbi, xRedisContext *ctx); + void FreexRedisContext(xRedisContext *ctx); + bool ConnectRedisCache(const RedisNode *redisnodelist, uint32_t nodecount, + uint32_t hashbase, uint32_t cachetype); + +public: + // Connection + /* AUTH */ /* nonsupport */ + /* ECHO */ bool echo(const RedisDBIdx &dbi, const std::string &str, std::string &value); + /* PING */ /* nonsupport */ + /* QUIT */ void quit(); + /* SELECT */ /* nonsupport */ + + // Commands operating on std::string values + /* APPEND */ bool append(const RedisDBIdx &dbi, const std::string &key, const std::string &value); + /* BITCOUNT */ bool bitcount(const RedisDBIdx &dbi, const std::string &key, int32_t &count, int32_t start = 0, int32_t end = 0); + /* BITOP */ bool bitop(const RedisDBIdx &dbi, const BITOP operation, const std::string &destkey, const KEYS &keys, int32_t &lenght); + /* BITPOS */ bool bitpos(const RedisDBIdx &dbi, const std::string &key, int32_t bit, int64_t &pos, int32_t start = 0, int32_t end = 0); + /* DECR */ bool decr(const RedisDBIdx &dbi, const std::string &key, int64_t &result); + /* DECRBY */ bool decrby(const RedisDBIdx &dbi, const std::string &key, int32_t by, int64_t &result); + /* GET */ bool get(const RedisDBIdx &dbi, const std::string &key, std::string &value); + /* GETBIT */ bool getbit(const RedisDBIdx &dbi, const std::string &key, int32_t &offset, int32_t &bit); + /* GETRANGE */ bool getrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, std::string &out); + /* GETSET */ bool getset(const RedisDBIdx &dbi, const std::string &key, const std::string &newValue, std::string &oldValue); + /* INCR */ bool incr(const RedisDBIdx &dbi, const std::string &key, int64_t &result); + /* INCRBY */ bool incrby(const RedisDBIdx &dbi, const std::string &key, int32_t by, int64_t &result); + /* INCRBYFLOAT */ + /* MGET */ bool mget(const DBIArray &dbi, const KEYS &keys, ReplyData &vDdata); + /* MSET */ bool mset(const DBIArray &dbi, const VDATA &data); + /* MSETNX */ + /* PSETEX */ bool psetex(const RedisDBIdx &dbi, const std::string &key, int32_t milliseconds, const std::string &value); + /* SET */ bool set(const RedisDBIdx &dbi, const std::string &key, const std::string &value); + /* SET */ bool set(const RedisDBIdx &dbi, const std::string &key, const char *value, int32_t len, int32_t second); + /* SET */ bool set(const RedisDBIdx &dbi, const std::string &key, const std::string &value, + SETPXEX pxex, int32_t expiretime, SETNXXX nxxx); + /* SETBIT */ bool setbit(const RedisDBIdx &dbi, const std::string &key, int32_t offset, int64_t newbitValue, int64_t oldbitValue); + /* SETEX */ bool setex(const RedisDBIdx &dbi, const std::string &key, int32_t seconds, const std::string &value); + /* SETNX */ bool setnx(const RedisDBIdx &dbi, const std::string &key, const std::string &value); + /* SETRANGE */ bool setrange(const RedisDBIdx &dbi, const std::string &key, int32_t offset, const std::string &value, int32_t &length); + /* STRLEN */ bool strlen(const RedisDBIdx &dbi, const std::string &key, int32_t &length); + + /* DEL */ bool del(const RedisDBIdx &dbi, const std::string &key); + bool del(const DBIArray &dbi, const KEYS &vkey, int64_t &count); + /* DUMP */ + /* EXISTS */ bool exists(const RedisDBIdx &dbi, const std::string &key); + /* EXPIRE */ bool expire(const RedisDBIdx &dbi, const std::string &key, uint32_t second); + /* EXPIREAT */ bool expireat(const RedisDBIdx &dbi, const std::string &key, uint32_t timestamp); + /* KEYS */ + /* MIGRATE */ + /* MOVE */ + /* OBJECT */ + /* PERSIST */ bool persist(const RedisDBIdx &dbi, const std::string &key); + /* PEXPIRE */ bool pexpire(const RedisDBIdx &dbi, const std::string &key, uint32_t milliseconds); + /* PEXPIREAT */ bool pexpireat(const RedisDBIdx &dbi, const std::string &key, uint32_t millisecondstimestamp); + /* PTTL */ bool pttl(const RedisDBIdx &dbi, const std::string &key, int64_t &milliseconds); + /* RANDOMKEY */ bool randomkey(const RedisDBIdx &dbi, KEY &key); + /* RENAME */ + /* RENAMENX */ + /* RESTORE */ + /* SCAN */ bool scan(const RedisDBIdx &dbi, int64_t &cursor, + const char *pattern, uint32_t count, ArrayReply &array, xRedisContext &ctx); + + /* SORT */ bool sort(const RedisDBIdx &dbi, ArrayReply &array, const std::string &key, const char *by = NULL, + LIMIT *limit = NULL, bool alpha = false, const FILEDS *get = NULL, + const SORTODER order = ASC, const char *destination = NULL); + + /* TTL */ bool ttl(const RedisDBIdx &dbi, const std::string &key, int64_t &seconds); + /* TYPE */ bool type(const RedisDBIdx &dbi, const std::string &key, std::string &value); + + /* HDEL */ bool hdel(const RedisDBIdx &dbi, const std::string &key, const std::string &field, int64_t &num); + bool hdel(const RedisDBIdx &dbi, const std::string &key, const KEYS &vfiled, int64_t &num); + /* HEXISTS */ bool hexist(const RedisDBIdx &dbi, const std::string &key, const std::string &field); + /* HGET */ bool hget(const RedisDBIdx &dbi, const std::string &key, const std::string &field, std::string &value); + /* HGETALL */ bool hgetall(const RedisDBIdx &dbi, const std::string &key, ArrayReply &array); + /* HINCRBY */ bool hincrby(const RedisDBIdx &dbi, const std::string &key, const std::string &field, int64_t increment, int64_t &value); + /* HINCRBYFLOAT */ bool hincrbyfloat(const RedisDBIdx &dbi, const std::string &key, const std::string &field, const float increment, float &value); + /* HKEYS */ bool hkeys(const RedisDBIdx &dbi, const std::string &key, KEYS &keys); + /* HLEN */ bool hlen(const RedisDBIdx &dbi, const std::string &key, int64_t &count); + /* HMGET */ bool hmget(const RedisDBIdx &dbi, const std::string &key, const KEYS &field, ArrayReply &array); + /* HMSET */ bool hmset(const RedisDBIdx &dbi, const std::string &key, const VDATA &vData); + /* HSCAN */ bool hscan(const RedisDBIdx &dbi, const std::string &key, int64_t &cursor, + const char *pattern, uint32_t count, ArrayReply &array, xRedisContext &ctx); + /* HSET */ bool hset(const RedisDBIdx &dbi, const std::string &key, const std::string &field, const std::string &value, int64_t &retval); + /* HSETNX */ bool hsetnx(const RedisDBIdx &dbi, const std::string &key, const std::string &field, const std::string &value); + /* HVALS */ bool hvals(const RedisDBIdx &dbi, const std::string &key, VALUES &values); + + /* BLPOP */ bool blPop(const RedisDBIdx &dbi, const std::string &key, VALUES &vValues, int64_t timeout); + /* BRPOP */ bool brPop(const RedisDBIdx &dbi, const std::string &key, VALUES &vValues, int64_t timeout); + /* BRPOPLPUSH */ bool brPoplpush(const RedisDBIdx &dbi, const std::string &key, std::string &targetkey, VALUE &value, int64_t timeout); + /* LINDEX */ bool lindex(const RedisDBIdx &dbi, const std::string &key, int64_t index, VALUE &value); + /* LINSERT */ bool linsert(const RedisDBIdx &dbi, const std::string &key, LMODEL mod, const std::string &pivot, const std::string &value, int64_t &retval); + /* LLEN */ bool llen(const RedisDBIdx &dbi, const std::string &key, int64_t &len); + /* LPOP */ bool lpop(const RedisDBIdx &dbi, const std::string &key, std::string &value); + /* LPUSH */ bool lpush(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &length); + /* LPUSHX */ bool lpushx(const RedisDBIdx &dbi, const std::string &key, const std::string &value, int64_t &length); + /* LRANGE */ bool lrange(const RedisDBIdx &dbi, const std::string &key, int64_t start, int64_t end, ArrayReply &array); + /* LREM */ bool lrem(const RedisDBIdx &dbi, const std::string &key, int32_t count, const std::string &value, int64_t num); + /* LSET */ bool lset(const RedisDBIdx &dbi, const std::string &key, int32_t index, const std::string &value); + /* LTRIM */ bool ltrim(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end); + /* RPOP */ bool rpop(const RedisDBIdx &dbi, const std::string &key, std::string &value); + /* RPOPLPUSH */ bool rpoplpush(const RedisDBIdx &dbi, const std::string &key_src, const std::string &key_dest, std::string &value); + /* RPUSH */ bool rpush(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &length); + /* RPUSHX */ bool rpushx(const RedisDBIdx &dbi, const std::string &key, const std::string &value, int64_t &length); + + /* SADD */ bool sadd(const RedisDBIdx &dbi, const KEY &key, const VALUES &vValue, int64_t &count); + /* SCARD */ bool scard(const RedisDBIdx &dbi, const KEY &key, int64_t &count); + /* SDIFF */ bool sdiff(const DBIArray &dbi, const KEYS &vKkey, VALUES &vValue); + /* SDIFFSTORE */ bool sdiffstore(const RedisDBIdx &dbi, const KEY &destinationkey, const DBIArray &vdbi, const KEYS &vkey, int64_t &count); + /* SINTER */ bool sinter(const DBIArray &dbi, const KEYS &vkey, VALUES &vValue); + /* SINTERSTORE */ bool sinterstore(const RedisDBIdx &dbi, const KEY &destinationkey, const DBIArray &vdbi, const KEYS &vkey, int64_t &count); + /* SISMEMBER */ bool sismember(const RedisDBIdx &dbi, const KEY &key, const VALUE &member); + /* SMEMBERS */ bool smembers(const RedisDBIdx &dbi, const KEY &key, VALUES &vValue); + /* SMOVE */ bool smove(const RedisDBIdx &dbi, const KEY &srckey, const KEY &deskey, const VALUE &member); + /* SPOP */ bool spop(const RedisDBIdx &dbi, const KEY &key, VALUE &member); + /* SRANDMEMBER */ bool srandmember(const RedisDBIdx &dbi, const KEY &key, VALUES &vmember, int32_t num = 0); + /* SREM */ bool srem(const RedisDBIdx &dbi, const KEY &key, const VALUES &vmembers, int64_t &count); + /* SSCAN */ bool sscan(const RedisDBIdx &dbi, const std::string &key, int64_t &cursor, + const char *pattern, uint32_t count, ArrayReply &array, xRedisContext &ctx); + /* SUNION */ bool sunion(const DBIArray &dbi, const KEYS &vkey, VALUES &vValue); + /* SUNIONSTORE */ bool sunionstore(const RedisDBIdx &dbi, const KEY &deskey, const DBIArray &vdbi, const KEYS &vkey, int64_t &count); + + /* ZADD */ bool zadd(const RedisDBIdx &dbi, const KEY &deskey, const VALUES &vValues, int64_t &count); + /* ZCARD */ bool zscrad(const RedisDBIdx &dbi, const std::string &key, int64_t &num); + /* ZCOUNT */ + /* ZINCRBY */ bool zincrby(const RedisDBIdx &dbi, const std::string &key, const double &increment, const std::string &member, std::string &value); + /* ZINTERSTORE */ + /* ZRANGE */ bool zrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, VALUES &vValues, bool withscore = false); + /* ZRANGEBYSCORE */ bool zrangebyscore(const RedisDBIdx &dbi, const std::string &key, const std::string &min, + const std::string &max, VALUES &vValues, bool withscore = false, LIMIT *limit = NULL); + /* ZRANK */ bool zrank(const RedisDBIdx &dbi, const std::string &key, const std::string &member, int64_t &rank); + /* ZREM */ bool zrem(const RedisDBIdx &dbi, const KEY &key, const VALUES &vmembers, int64_t &num); + /* ZREMRANGEBYRANK */ bool zremrangebyrank(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t stop, int64_t &num); + /* ZREMRANGEBYSCORE */ bool zremrangebyscore(const RedisDBIdx &dbi, const KEY &key, double min, double max, int64_t &count); + /* ZREVRANGE */ bool zrevrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, VALUES &vValues, bool withscore = false); + /* ZREVRANGEBYLEX */ bool zrevrangebylex(const RedisDBIdx &dbi, const std::string &key, std::string &start, std::string &end, VALUES &vValues, int32_t offset = 0, int32_t count = 0); + /* ZREVRANGEBYSCORE */ + /* ZREVRANK */ bool zrevrank(const RedisDBIdx &dbi, const std::string &key, const std::string &member, int64_t &rank); + /* ZSCAN */ bool zscan(const RedisDBIdx &dbi, const std::string &key, int64_t &cursor, const char *pattern, + uint32_t count, ArrayReply &array, xRedisContext &ctx); + /* ZSCORE */ bool zscore(const RedisDBIdx &dbi, const std::string &key, const std::string &member, std::string &score); + /* ZUNIONSTORE */ + + /* 注意: 使用下面的 pub/sub 命令时,一定要保证数据都在同一个REDIS实例里,xredis目前的pub/sub命令实现不支持多节点数据分布的场景。 */ + /* PSUBSCRIBE */ bool psubscribe(const RedisDBIdx &dbi, const KEYS &patterns, xRedisContext &ctx); + /* PUBLISH */ bool publish(const RedisDBIdx &dbi, const KEY &channel, const std::string &message, int64_t &count); + /* PUBSUB */ bool pubsub_channels(const RedisDBIdx &dbi, const std::string &pattern, ArrayReply &reply); + bool pubsub_numsub(const RedisDBIdx &dbi, const KEYS &keys, ArrayReply &reply); + bool pubsub_numpat(const RedisDBIdx &dbi, int64_t &count); + /* PUNSUBSCRIBE */ bool punsubscribe(const RedisDBIdx &dbi, const KEYS &patterns, xRedisContext &ctx); + /* SUBSCRIBE */ bool subscribe(const RedisDBIdx &dbi, const KEYS &channels, xRedisContext &ctx); + /* UNSUBSCRIBE */ bool unsubscribe(const RedisDBIdx &dbi, const KEYS &channels, xRedisContext &ctx); + + /* DISCARD */ + /* EXEC */ + /* MULTI */ + /* UNWATCH */ + /* WATCH */ + +private: + void addparam(VDATA &vDes, const VDATA &vSrc) + { + for (VDATA::const_iterator iter = vSrc.begin(); iter != vSrc.end(); ++iter) + { + vDes.push_back(*iter); + } + } + void SetErrInfo(const RedisDBIdx &dbi, void *p); + void SetErrString(const RedisDBIdx &dbi, const char *str, int32_t len); + void SetErrMessage(const RedisDBIdx &dbi, const char *fmt, ...); + void SetIOtype(const RedisDBIdx &dbi, uint32_t iotype, bool ioflag = false); + bool ScanFun(const char *cmd, const RedisDBIdx &dbi, const std::string *key, int64_t &cursor, + const char *pattern, uint32_t count, ArrayReply &array, xRedisContext &ctx); + +public: + bool command_bool(const RedisDBIdx &dbi, const char *cmd, ...); + bool command_status(const RedisDBIdx &dbi, const char *cmd, ...); + bool command_integer(const RedisDBIdx &dbi, int64_t &intval, const char *cmd, ...); + bool command_string(const RedisDBIdx &dbi, std::string &data, const char *cmd, ...); + bool command_list(const RedisDBIdx &dbi, VALUES &vValue, const char *cmd, ...); + bool command_array(const RedisDBIdx &dbi, ArrayReply &array, const char *cmd, ...); + rReply *command(const RedisDBIdx &dbi, const char *cmd); + +private: + bool commandargv_bool(const RedisDBIdx &dbi, const VDATA &vData); + bool commandargv_status(const RedisDBIdx &dbi, const VDATA &vData); + bool commandargv_array(const RedisDBIdx &dbi, const VDATA &vDataIn, ArrayReply &array); + bool commandargv_array(const RedisDBIdx &dbi, const VDATA &vDataIn, VALUES &array); + bool commandargv_integer(const RedisDBIdx &dbi, const VDATA &vDataIn, int64_t &retval); + bool commandargv_array_ex(const RedisDBIdx &dbi, const VDATA &vDataIn, xRedisContext &ctx); + +private: + RedisPool *mRedisPool; +}; + +} // namespace xrc + +#endif diff --git a/src/xRedisClusterClient.h b/include/xredis/xRedisClusterClient.h similarity index 53% rename from src/xRedisClusterClient.h rename to include/xredis/xRedisClusterClient.h index d5d63b5..86b85ae 100644 --- a/src/xRedisClusterClient.h +++ b/include/xredis/xRedisClusterClient.h @@ -7,63 +7,80 @@ #include #include #include -#include "hiredis.h" +#include #include "xLock.h" namespace xrc { #define MAX_REDIS_POOLSIZE 128 -#define MAX_TIME_OUT 5 +#define MAX_TIME_OUT 5 -typedef std::vector VSTRING; +typedef std::vector VSTRING; - -class RedisResult { +class RedisResult +{ public: - RedisResult(){} - ~RedisResult() { if (Reply.reply) { freeReplyObject((void*)Reply.reply); } + RedisResult() {} + ~RedisResult() + { + if (Reply.reply) + { + freeReplyObject((void *)Reply.reply); + } } - + public: - class RedisReply { + class RedisReply + { public: - RedisReply(redisReply *r) { reply = r;} + RedisReply(redisReply *r) { reply = r; } RedisReply() { reply = NULL; } ~RedisReply() {} - + int32_t type() const { return reply->type; } - long long integer() const {return reply->integer; } + long long integer() const { return reply->integer; } int32_t len() const { return reply->len; } - char* str() const { return reply->str; } + char *str() const { return reply->str; } size_t elements() const { return reply->elements; } RedisReply element(uint32_t index) const { return RedisReply(reply->element[index]); } - private: + + private: friend class RedisResult; redisReply *reply; }; - - void Init(redisReply *r) { if (Reply.reply) { freeReplyObject((void*)Reply.reply);} Reply.reply = r; } + + void Init(redisReply *r) + { + if (Reply.reply) + { + freeReplyObject((void *)Reply.reply); + } + Reply.reply = r; + } int32_t type() const { return Reply.type(); } - long long integer() const {return Reply.integer(); } + long long integer() const { return Reply.integer(); } int32_t len() const { return Reply.len(); } - char* str() const { return Reply.str(); } + char *str() const { return Reply.str(); } size_t elements() const { return Reply.elements(); } RedisReply element(uint32_t index) const { return Reply.element(index); } + private: RedisReply Reply; }; -typedef struct _REDISCONN_ { - _REDISCONN_() { +typedef struct _REDISCONN_ +{ + _REDISCONN_() + { mCtx = NULL; mHost = NULL; mPort = 0; mPoolSize = 0; } - ~_REDISCONN_(){} - - redisContext * ConnectWithTimeout() + ~_REDISCONN_() {} + + redisContext *ConnectWithTimeout() { struct timeval timeoutVal; timeoutVal.tv_sec = MAX_TIME_OUT; @@ -71,12 +88,15 @@ typedef struct _REDISCONN_ { redisContext *ctx = NULL; ctx = redisConnectWithTimeout(mHost, mPort, timeoutVal); - if (NULL == ctx || ctx->err) { - if (NULL != ctx) { + if (NULL == ctx || ctx->err) + { + if (NULL != ctx) + { redisFree(ctx); ctx = NULL; - } else { - + } + else + { } } @@ -84,18 +104,18 @@ typedef struct _REDISCONN_ { } redisContext *mCtx; - const char *mHost; - uint32_t mPort; - uint32_t mPoolSize; - uint32_t mIndex; -}RedisConnection; + const char *mHost; + uint32_t mPort; + uint32_t mPoolSize; + uint32_t mIndex; +} RedisConnection; -typedef std::list RedisConnectionList; -typedef std::list ::iterator RedisConnectionIter; +typedef std::list RedisConnectionList; +typedef std::list::iterator RedisConnectionIter; class xRedisClusterClient { - public: +public: xRedisClusterClient(); ~xRedisClusterClient(); @@ -103,26 +123,28 @@ class xRedisClusterClient struct NodeInfo { std::string strinfo; - std::string id; // The node ID, a 40 characters random string generated when a node is created and never changed again (unless CLUSTER RESET HARD is used) - std::string ip; // The node IP - uint16_t port; // The node port - std::string flags; // A list of comma separated flags: myself, master, slave, fail?, fail, handshake, noaddr, noflags + std::string id; // The node ID, a 40 characters random string generated when a node is created and never changed again (unless CLUSTER RESET HARD is used) + std::string ip; // The node IP + uint16_t port; // The node port + std::string flags; // A list of comma separated flags: myself, master, slave, fail?, fail, handshake, noaddr, noflags bool is_fail; - bool is_master; // true if node is master, false if node is salve + bool is_master; // true if node is master, false if node is salve bool is_slave; - std::string master_id; // The replication master - int32_t ping_sent; // Milliseconds unix time at which the currently active ping was sent, or zero if there are no pending pings - int32_t pong_recv; // Milliseconds unix time the last pong was received - int32_t epoch; // The configuration epoch (or version) of the current node (or of the current master if the node is a slave). Each time there is a failover, a new, unique, monotonically increasing configuration epoch is created. If multiple nodes claim to serve the same hash slots, the one with higher configuration epoch wins - bool connected; // The state of the link used for the node-to-node cluster bus - std::vector > mSlots; // A hash slot number or range + std::string master_id; // The replication master + int32_t ping_sent; // Milliseconds unix time at which the currently active ping was sent, or zero if there are no pending pings + int32_t pong_recv; // Milliseconds unix time the last pong was received + int32_t epoch; // The configuration epoch (or version) of the current node (or of the current master if the node is a slave). Each time there is a failover, a new, unique, monotonically increasing configuration epoch is created. If multiple nodes claim to serve the same hash slots, the one with higher configuration epoch wins + bool connected; // The state of the link used for the node-to-node cluster bus + std::vector> mSlots; // A hash slot number or range bool CheckSlot(uint32_t slotindex) { - std::vector >::const_iterator citer = mSlots.begin(); - for (; citer != mSlots.end(); ++citer) { + std::vector>::const_iterator citer = mSlots.begin(); + for (; citer != mSlots.end(); ++citer) + { //printf("check %u [%u, %u]\n", slotindex, iter->first, iter->second); - if ((slotindex >= citer->first) && (slotindex <= citer->second)) { + if ((slotindex >= citer->first) && (slotindex <= citer->second)) + { return true; } } @@ -132,9 +154,12 @@ class xRedisClusterClient bool ParseNodeString(const std::string &nodeString) { std::string::size_type ColonPos = nodeString.find(':'); - if (ColonPos == std::string::npos) { + if (ColonPos == std::string::npos) + { return false; - } else { + } + else + { const std::string port_str = nodeString.substr(ColonPos + 1); port = atoi(port_str.c_str()); ip = nodeString.substr(0, ColonPos); @@ -147,10 +172,13 @@ class xRedisClusterClient uint32_t StartSlot = 0; uint32_t EndSlot = 0; std::string::size_type BarPos = SlotString.find('-'); - if (BarPos == std::string::npos) { + if (BarPos == std::string::npos) + { StartSlot = atoi(SlotString.c_str()); EndSlot = StartSlot; - } else { + } + else + { const std::string EndSlotStr = SlotString.substr(BarPos + 1); EndSlot = atoi(EndSlotStr.c_str()); StartSlot = atoi(SlotString.substr(0, BarPos).c_str()); @@ -163,18 +191,19 @@ class xRedisClusterClient public: void Init(); - + bool ConnectRedis(const char *host, uint32_t port, uint32_t poolsize); bool ReConnectRedis(RedisConnection *pConn); void Keepalive(); - bool RedisCommandArgv(const VSTRING& vDataIn, RedisResult &result); + bool RedisCommandArgv(const VSTRING &vDataIn, RedisResult &result); bool RedisCommand(RedisResult &result, const char *format, ...); private: static uint16_t crc16(const char *buf, int32_t len); static bool CheckReply(const redisReply *reply); static void FreeReply(const redisReply *reply); - static int32_t Str2Vect(const char* pSrc, std::vector &vDest, const char *pSep = ","); + static int32_t Str2Vect(const char *pSrc, std::vector &vDest, const char *pSep = ","); + private: void Release(); bool ConnectRedisNode(int32_t idx, const char *host, uint32_t port, uint32_t poolsize); @@ -183,21 +212,21 @@ class xRedisClusterClient bool ClusterEnabled(redisContext *ctx); bool ClusterInfo(redisContext *ctx); RedisConnection *GetConnection(uint32_t idx); - void FreeConnection(RedisConnection * pRedis); + void FreeConnection(RedisConnection *pRedis); uint32_t FindNodeIndex(uint32_t slot); - uint32_t GetKeySlotIndex(const char* key); + uint32_t GetKeySlotIndex(const char *key); RedisConnection *FindNodeConnection(const char *key); bool GetClusterNodes(redisContext *ctx); + private: - RedisConnectionList *mRedisConnList; - xLock *mLock; - uint32_t mPoolSize; - NODELIST vNodes; - bool mClusterEnabled; - RedisConnection mConn; + RedisConnectionList *mRedisConnList; + xLock *mLock; + uint32_t mPoolSize; + NODELIST vNodes; + bool mClusterEnabled; + RedisConnection mConn; }; -} +} // namespace xrc #endif - diff --git a/include/xredis/xRedisPool.h b/include/xredis/xRedisPool.h new file mode 100644 index 0000000..022779b --- /dev/null +++ b/include/xredis/xRedisPool.h @@ -0,0 +1,181 @@ +/* + * ---------------------------------------------------------------------------- + * Copyright (c) 2013-2014, xSky + * All rights reserved. + * Distributed under GPL license. + * ---------------------------------------------------------------------------- + */ + +#ifndef _XREDIS_POOL_H_ +#define _XREDIS_POOL_H_ + +#include +#include "xLock.h" +#include +#include +#include +#include "xRedisClient.h" + +namespace xrc +{ + +#define MAX_REDIS_CONN_POOLSIZE 128 // 每个DB最大连接数 +#define MAX_REDIS_CACHE_TYPE 128 // 最大支持的CACHE种类数 +#define MAX_REDIS_DB_HASHBASE 128 // 最大HASH分库基数 + +#define GET_CONNECT_ERROR "get connection error" +#define CONNECT_CLOSED_ERROR "redis connection be closed" + +#ifdef WIN32 +#define strcasecmp stricmp +#define strncasecmp strnicmp +#endif + +enum +{ + REDISDB_UNCONN, + REDISDB_WORKING, + REDISDB_DEAD +}; + +class RedisConn +{ +public: + RedisConn(); + ~RedisConn(); + + void Init(uint32_t cahcetype, + uint32_t dbindex, + const std::string &host, + uint32_t port, + const std::string &pass, + uint32_t poolsize, + uint32_t timeout, + uint32_t role, + uint32_t slaveidx); + + bool RedisConnect(); + bool RedisReConnect(); + bool Ping(); + + redisContext *getCtx() const { return mCtx; } + uint32_t getdbindex() const { return mDbindex; } + uint32_t GetType() const { return mType; } + uint32_t GetRole() const { return mRole; } + uint32_t GetSlaveIdx() const { return mSlaveIdx; } + bool GetConnstatus() const { return mConnStatus; } + +private: + bool auth(); + redisContext *ConnectWithTimeout(); + +private: + // redis connector context + redisContext *mCtx; + std::string mHost; // redis host + uint32_t mPort; // redis sever port + std::string mPass; // redis server password + uint32_t mTimeout; // connect timeout second + uint32_t mPoolsize; // connect pool size for each redis DB + uint32_t mType; // redis cache pool type + uint32_t mDbindex; // redis DB index + uint32_t mRole; // redis role + uint32_t mSlaveIdx; // the index in the slave group + bool mConnStatus; // redis connection status +}; + +typedef std::list RedisConnPool; +typedef std::list::iterator RedisConnIter; + +typedef std::vector RedisSlaveGroup; +typedef std::vector::iterator RedisSlaveGroupIter; + +typedef struct _RedisDBSlice_Conn_ +{ + RedisConnPool RedisMasterConn; + RedisSlaveGroup RedisSlaveConn; + xLock MasterLock; + xLock SlaveLock; +} RedisSliceConn; + +class RedisDBSlice +{ +public: + RedisDBSlice(); + ~RedisDBSlice(); + + void Init(uint32_t cahcetype, uint32_t dbindex); + // 连到到一个REDIS服务节点 + bool ConnectRedisNodes(uint32_t cahcetype, uint32_t dbindex, + const std::string &host, uint32_t port, const std::string &passwd, + uint32_t poolsize, uint32_t timeout, int32_t role); + + RedisConn *GetMasterConn(); + RedisConn *GetSlaveConn(); + RedisConn *GetConn(int32_t ioRole); + void FreeConn(RedisConn *redisconn); + void CloseConnPool(); + void ConnPoolPing(); + uint32_t GetStatus() const; + +private: + RedisSliceConn mSliceConn; + bool mHaveSlave; + uint32_t mType; // redis cache pool type + uint32_t mDbindex; // redis slice index + uint32_t mStatus; // redis DB status +}; + +class RedisCache +{ +public: + RedisCache(); + virtual ~RedisCache(); + + bool InitDB(uint32_t cachetype, uint32_t hashbase); + bool ConnectRedisDB(uint32_t cahcetype, uint32_t dbindex, + const std::string &host, uint32_t port, const std::string &passwd, + uint32_t poolsize, uint32_t timeout, uint32_t role); + + RedisConn *GetConn(uint32_t dbindex, uint32_t ioRole); + void FreeConn(RedisConn *redisconn); + void ClosePool(); + void KeepAlive(); + uint32_t GetDBStatus(uint32_t dbindex); + uint32_t GetHashBase() const; + +private: + RedisDBSlice *mDBList; + uint32_t mCachetype; + uint32_t mHashbase; +}; + +class RedisPool +{ +public: + RedisPool(); + ~RedisPool(); + + bool Init(uint32_t typesize); + bool setHashBase(uint32_t cachetype, uint32_t hashbase); + uint32_t getHashBase(uint32_t cachetype); + bool ConnectRedisDB(uint32_t cachetype, uint32_t dbindex, + const std::string &host, uint32_t port, const std::string &passwd, + uint32_t poolsize, uint32_t timeout, uint32_t role); + static bool CheckReply(const redisReply *reply); + static void FreeReply(const redisReply *reply); + + RedisConn *GetConnection(uint32_t cachetype, uint32_t index, uint32_t ioType = MASTER); + void FreeConnection(RedisConn *redisconn); + + void Keepalive(); + void Release(); + +private: + RedisCache *mRedisCacheList; + uint32_t mTypeSize; +}; + +} // namespace xrc + +#endif diff --git a/src/xRedisClient.cpp b/src/xRedisClient.cpp index 2f1de92..040d9e9 100644 --- a/src/xRedisClient.cpp +++ b/src/xRedisClient.cpp @@ -5,13 +5,14 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ - + #include "xRedisClient.h" #include "xRedisPool.h" #include using namespace xrc; -RedisDBIdx::RedisDBIdx() { +RedisDBIdx::RedisDBIdx() +{ mType = 0; mIndex = 0; mStrerr = NULL; @@ -20,7 +21,8 @@ RedisDBIdx::RedisDBIdx() { mIOFlag = false; } -RedisDBIdx::RedisDBIdx(xRedisClient *xredisclient) { +RedisDBIdx::RedisDBIdx(xRedisClient *xredisclient) +{ mType = 0; mIndex = 0; mStrerr = NULL; @@ -28,34 +30,41 @@ RedisDBIdx::RedisDBIdx(xRedisClient *xredisclient) { mIOtype = MASTER; mIOFlag = false; } -RedisDBIdx::~RedisDBIdx() { - if (NULL != mStrerr){ +RedisDBIdx::~RedisDBIdx() +{ + if (NULL != mStrerr) + { delete[] mStrerr; mStrerr = NULL; } } -bool RedisDBIdx::CreateDBIndex(const char *key, HASHFUN fun, const uint32_t type) { +bool RedisDBIdx::CreateDBIndex(const char *key, HASHFUN fun, const uint32_t type) +{ uint32_t hashbase = mClient->GetRedisPool()->getHashBase(type); - if ((NULL!=fun) && (hashbase>0)) { - mIndex = fun(key)%hashbase; - mType = type; + if ((NULL != fun) && (hashbase > 0)) + { + mIndex = fun(key) % hashbase; + mType = type; return true; } return false; } -bool RedisDBIdx::CreateDBIndex(const int64_t id, const uint32_t type) { +bool RedisDBIdx::CreateDBIndex(const int64_t id, const uint32_t type) +{ uint32_t hashbase = mClient->GetRedisPool()->getHashBase(type); - if (hashbase>0) { - mType = type; - mIndex = id%hashbase; + if (hashbase > 0) + { + mType = type; + mIndex = id % hashbase; return true; } return false; } -void RedisDBIdx::IOtype(uint32_t type) { +void RedisDBIdx::IOtype(uint32_t type) +{ mIOtype = type; } @@ -65,14 +74,18 @@ void RedisDBIdx::SetIOMaster() mIOFlag = true; } -bool RedisDBIdx::SetErrInfo(const char *info, int32_t len) { - if (NULL == info) { +bool RedisDBIdx::SetErrInfo(const char *info, int32_t len) +{ + if (NULL == info) + { return false; } - if (NULL == mStrerr){ + if (NULL == mStrerr) + { mStrerr = new char[len + 1]; } - if (NULL != mStrerr) { + if (NULL != mStrerr) + { strncpy(mStrerr, info, len); mStrerr[len] = '\0'; return true; @@ -85,65 +98,78 @@ xRedisClient::xRedisClient() mRedisPool = NULL; } - xRedisClient::~xRedisClient() { Release(); } -bool xRedisClient::Init(uint32_t maxtype) { - if(NULL==mRedisPool) { +bool xRedisClient::Init(uint32_t maxtype) +{ + if (NULL == mRedisPool) + { mRedisPool = new RedisPool; - if (NULL==mRedisPool) { + if (NULL == mRedisPool) + { return false; } - + return mRedisPool->Init(maxtype); } return false; } -void xRedisClient::Release() { - if (NULL!=mRedisPool) { +void xRedisClient::Release() +{ + if (NULL != mRedisPool) + { mRedisPool->Release(); delete mRedisPool; mRedisPool = NULL; } } -void xRedisClient::Keepalive() { - if (NULL!=mRedisPool) { +void xRedisClient::Keepalive() +{ + if (NULL != mRedisPool) + { mRedisPool->Keepalive(); } } -inline RedisPool *xRedisClient::GetRedisPool() { +inline RedisPool *xRedisClient::GetRedisPool() +{ return mRedisPool; } -void xRedisClient::FreeReply(const rReply* reply) +void xRedisClient::FreeReply(const rReply *reply) { - RedisPool::FreeReply((redisReply*)reply); + RedisPool::FreeReply((redisReply *)reply); } -bool xRedisClient::ConnectRedisCache(const RedisNode *redisnodelist, uint32_t nodecount, uint32_t hashbase, uint32_t cachetype) { - if (NULL==mRedisPool) { +bool xRedisClient::ConnectRedisCache(const RedisNode *redisnodelist, uint32_t nodecount, uint32_t hashbase, uint32_t cachetype) +{ + if (NULL == mRedisPool) + { return false; } - - if (!mRedisPool->setHashBase(cachetype, hashbase)) { + + if (!mRedisPool->setHashBase(cachetype, hashbase)) + { return false; } - - for (uint32_t n = 0; nConnectRedisDB(cachetype, pNode->dbindex, pNode->host, pNode->port, - pNode->passwd, pNode->poolsize, pNode->timeout, pNode->role); - if (!bRet) { + bool bRet = mRedisPool->ConnectRedisDB(cachetype, pNode->dbindex, pNode->host, pNode->port, + pNode->passwd, pNode->poolsize, pNode->timeout, pNode->role); + if (!bRet) + { return false; } } @@ -151,30 +177,35 @@ bool xRedisClient::ConnectRedisCache(const RedisNode *redisnodelist, uint32_t no return true; } - -void xRedisClient::SetErrInfo(const RedisDBIdx& dbi, void *p) { - if (NULL==p){ +void xRedisClient::SetErrInfo(const RedisDBIdx &dbi, void *p) +{ + if (NULL == p) + { SetErrString(dbi, CONNECT_CLOSED_ERROR, ::strlen(CONNECT_CLOSED_ERROR)); - } else { - redisReply *reply = (redisReply*)p; + } + else + { + redisReply *reply = (redisReply *)p; SetErrString(dbi, reply->str, reply->len); } } -void xRedisClient::SetErrString(const RedisDBIdx& dbi, const char *str, int32_t len) { - RedisDBIdx &dbindex = const_cast(dbi); +void xRedisClient::SetErrString(const RedisDBIdx &dbi, const char *str, int32_t len) +{ + RedisDBIdx &dbindex = const_cast(dbi); dbindex.SetErrInfo(str, len); } -void xRedisClient::SetIOtype(const RedisDBIdx& dbi, uint32_t iotype, bool ioflag) { - RedisDBIdx &dbindex = const_cast(dbi); +void xRedisClient::SetIOtype(const RedisDBIdx &dbi, uint32_t iotype, bool ioflag) +{ + RedisDBIdx &dbindex = const_cast(dbi); dbindex.IOtype(iotype); dbindex.mIOFlag = ioflag; } -void xRedisClient::SetErrMessage(const RedisDBIdx& dbi, const char* fmt, ...) +void xRedisClient::SetErrMessage(const RedisDBIdx &dbi, const char *fmt, ...) { - char szBuf[128] = { 0 }; + char szBuf[128] = {0}; va_list va; va_start(va, fmt); vsnprintf(szBuf, sizeof(szBuf), fmt, va); @@ -182,10 +213,11 @@ void xRedisClient::SetErrMessage(const RedisDBIdx& dbi, const char* fmt, ...) SetErrString(dbi, szBuf, ::strlen(szBuf)); } -rReply *xRedisClient::command(const RedisDBIdx& dbi, const char* cmd) +rReply *xRedisClient::command(const RedisDBIdx &dbi, const char *cmd) { RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return NULL; } @@ -195,10 +227,12 @@ rReply *xRedisClient::command(const RedisDBIdx& dbi, const char* cmd) return reply; } -bool xRedisClient::command_bool(const RedisDBIdx& dbi, const char *cmd, ...) { +bool xRedisClient::command_bool(const RedisDBIdx &dbi, const char *cmd, ...) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } @@ -208,13 +242,19 @@ bool xRedisClient::command_bool(const RedisDBIdx& dbi, const char *cmd, ...) { redisReply *reply = static_cast(redisvCommand(pRedisConn->getCtx(), cmd, args)); va_end(args); - if (RedisPool::CheckReply(reply)) { - if (REDIS_REPLY_STATUS==reply->type) { + if (RedisPool::CheckReply(reply)) + { + if (REDIS_REPLY_STATUS == reply->type) + { bRet = true; - } else { + } + else + { bRet = (reply->integer == 1) ? true : false; } - } else { + } + else + { SetErrInfo(dbi, reply); } @@ -224,10 +264,12 @@ bool xRedisClient::command_bool(const RedisDBIdx& dbi, const char *cmd, ...) { return bRet; } -bool xRedisClient::command_status(const RedisDBIdx& dbi, const char* cmd, ...) { +bool xRedisClient::command_status(const RedisDBIdx &dbi, const char *cmd, ...) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } @@ -237,29 +279,36 @@ bool xRedisClient::command_status(const RedisDBIdx& dbi, const char* cmd, ...) { redisReply *reply = static_cast(redisvCommand(pRedisConn->getCtx(), cmd, args)); va_end(args); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { // Assume good reply until further inspection bRet = true; - - if (REDIS_REPLY_STRING == reply->type) { - if (!reply->len || !reply->str || strcasecmp(reply->str, "OK") != 0) { + + if (REDIS_REPLY_STRING == reply->type) + { + if (!reply->len || !reply->str || strcasecmp(reply->str, "OK") != 0) + { bRet = false; } } - } else { + } + else + { SetErrInfo(dbi, reply); } - + RedisPool::FreeReply(reply); mRedisPool->FreeConnection(pRedisConn); return bRet; } -bool xRedisClient::command_integer(const RedisDBIdx& dbi, int64_t &retval, const char* cmd, ...) { +bool xRedisClient::command_integer(const RedisDBIdx &dbi, int64_t &retval, const char *cmd, ...) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } @@ -268,10 +317,13 @@ bool xRedisClient::command_integer(const RedisDBIdx& dbi, int64_t &retval, const va_start(args, cmd); redisReply *reply = static_cast(redisvCommand(pRedisConn->getCtx(), cmd, args)); va_end(args); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { retval = reply->integer; bRet = true; - } else { + } + else + { SetErrInfo(dbi, reply); } @@ -281,10 +333,12 @@ bool xRedisClient::command_integer(const RedisDBIdx& dbi, int64_t &retval, const return bRet; } -bool xRedisClient::command_string(const RedisDBIdx& dbi, std::string &data, const char* cmd, ...) { +bool xRedisClient::command_string(const RedisDBIdx &dbi, std::string &data, const char *cmd, ...) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } @@ -293,10 +347,13 @@ bool xRedisClient::command_string(const RedisDBIdx& dbi, std::string &data, cons va_start(args, cmd); redisReply *reply = static_cast(redisvCommand(pRedisConn->getCtx(), cmd, args)); va_end(args); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { data.assign(reply->str, reply->len); bRet = true; - } else { + } + else + { SetErrInfo(dbi, reply); } @@ -306,10 +363,12 @@ bool xRedisClient::command_string(const RedisDBIdx& dbi, std::string &data, cons return bRet; } -bool xRedisClient::command_list(const RedisDBIdx& dbi, VALUES &vValue, const char* cmd, ...) { +bool xRedisClient::command_list(const RedisDBIdx &dbi, VALUES &vValue, const char *cmd, ...) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } @@ -318,12 +377,16 @@ bool xRedisClient::command_list(const RedisDBIdx& dbi, VALUES &vValue, const cha va_start(args, cmd); redisReply *reply = static_cast(redisvCommand(pRedisConn->getCtx(), cmd, args)); va_end(args); - if (RedisPool::CheckReply(reply)) { - for (size_t i = 0; ielements; i++) { + if (RedisPool::CheckReply(reply)) + { + for (size_t i = 0; i < reply->elements; i++) + { vValue.push_back(std::string(reply->element[i]->str, reply->element[i]->len)); } - bRet = true; - } else { + bRet = true; + } + else + { SetErrInfo(dbi, reply); } @@ -333,10 +396,12 @@ bool xRedisClient::command_list(const RedisDBIdx& dbi, VALUES &vValue, const cha return bRet; } -bool xRedisClient::command_array(const RedisDBIdx& dbi, ArrayReply& array, const char* cmd, ...){ +bool xRedisClient::command_array(const RedisDBIdx &dbi, ArrayReply &array, const char *cmd, ...) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } @@ -345,15 +410,19 @@ bool xRedisClient::command_array(const RedisDBIdx& dbi, ArrayReply& array, con va_start(args, cmd); redisReply *reply = static_cast(redisvCommand(pRedisConn->getCtx(), cmd, args)); va_end(args); - if (RedisPool::CheckReply(reply)) { - for (size_t i = 0; ielements; i++) { + if (RedisPool::CheckReply(reply)) + { + for (size_t i = 0; i < reply->elements; i++) + { DataItem item; item.type = reply->element[i]->type; item.str.assign(reply->element[i]->str, reply->element[i]->len); array.push_back(item); } - bRet = true; - } else { + bRet = true; + } + else + { SetErrInfo(dbi, reply); } @@ -362,25 +431,31 @@ bool xRedisClient::command_array(const RedisDBIdx& dbi, ArrayReply& array, con return bRet; } -bool xRedisClient::commandargv_array_ex(const RedisDBIdx& dbi, const VDATA& vDataIn, xRedisContext& ctx){ +bool xRedisClient::commandargv_array_ex(const RedisDBIdx &dbi, const VDATA &vDataIn, xRedisContext &ctx) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } - std::vector argv(vDataIn.size()); + std::vector argv(vDataIn.size()); std::vector argvlen(vDataIn.size()); uint32_t j = 0; - for (VDATA::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j) { + for (VDATA::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { bRet = true; - } else { + } + else + { SetErrInfo(dbi, reply); } @@ -389,15 +464,17 @@ bool xRedisClient::commandargv_array_ex(const RedisDBIdx& dbi, const VDATA& vDat return bRet; } -int32_t xRedisClient::GetReply(xRedisContext* ctx, ReplyData& vData) +int32_t xRedisClient::GetReply(xRedisContext *ctx, ReplyData &vData) { //vData.clear(); //ReplyData(vData).swap(vData); redisReply *reply; RedisConn *pRedisConn = static_cast(ctx->conn); - int32_t ret = redisGetReply(pRedisConn->getCtx(), (void**)&reply); - if (0==ret) { - for (size_t i = 0; i < reply->elements; i++) { + int32_t ret = redisGetReply(pRedisConn->getCtx(), (void **)&reply); + if (0 == ret) + { + for (size_t i = 0; i < reply->elements; i++) + { DataItem item; item.type = reply->element[i]->type; item.str.assign(reply->element[i]->str, reply->element[i]->len); @@ -408,28 +485,31 @@ int32_t xRedisClient::GetReply(xRedisContext* ctx, ReplyData& vData) return ret; } -bool xRedisClient::GetxRedisContext(const RedisDBIdx& dbi, xRedisContext* ctx) +bool xRedisClient::GetxRedisContext(const RedisDBIdx &dbi, xRedisContext *ctx) { RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { return false; } ctx->conn = pRedisConn; return true; } -void xRedisClient::FreexRedisContext(xRedisContext* ctx) +void xRedisClient::FreexRedisContext(xRedisContext *ctx) { RedisConn *pRedisConn = static_cast(ctx->conn); redisReply *reply = static_cast(redisCommand(pRedisConn->getCtx(), "unsubscribe")); RedisPool::FreeReply(reply); - mRedisPool->FreeConnection((RedisConn*)ctx->conn); + mRedisPool->FreeConnection((RedisConn *)ctx->conn); } -bool xRedisClient::commandargv_bool(const RedisDBIdx& dbi, const VDATA& vData) { +bool xRedisClient::commandargv_bool(const RedisDBIdx &dbi, const VDATA &vData) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return bRet; } @@ -437,14 +517,18 @@ bool xRedisClient::commandargv_bool(const RedisDBIdx& dbi, const VDATA& vData) { std::vector argv(vData.size()); std::vector argvlen(vData.size()); uint32_t j = 0; - for ( VDATA::const_iterator i = vData.begin(); i != vData.end(); ++i, ++j ) { + for (VDATA::const_iterator i = vData.begin(); i != vData.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { - bRet = (reply->integer==1)?true:false; - } else { + if (RedisPool::CheckReply(reply)) + { + bRet = (reply->integer == 1) ? true : false; + } + else + { SetErrInfo(dbi, reply); } @@ -454,66 +538,81 @@ bool xRedisClient::commandargv_bool(const RedisDBIdx& dbi, const VDATA& vData) { return bRet; } -bool xRedisClient::commandargv_status(const RedisDBIdx& dbi, const VDATA& vData) { +bool xRedisClient::commandargv_status(const RedisDBIdx &dbi, const VDATA &vData) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return bRet; } - std::vector argv( vData.size() ); - std::vector argvlen( vData.size() ); + std::vector argv(vData.size()); + std::vector argvlen(vData.size()); uint32_t j = 0; - for ( VDATA::const_iterator i = vData.begin(); i != vData.end(); ++i, ++j ) { + for (VDATA::const_iterator i = vData.begin(); i != vData.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { // Assume good reply until further inspection bRet = true; - - if (REDIS_REPLY_STRING == reply->type) { - if (!reply->len || !reply->str || strcasecmp(reply->str, "OK") != 0) { + + if (REDIS_REPLY_STRING == reply->type) + { + if (!reply->len || !reply->str || strcasecmp(reply->str, "OK") != 0) + { bRet = false; } } - } else { + } + else + { SetErrInfo(dbi, reply); } - + RedisPool::FreeReply(reply); mRedisPool->FreeConnection(pRedisConn); return bRet; } -bool xRedisClient::commandargv_array(const RedisDBIdx& dbi, const VDATA& vDataIn, ArrayReply& array){ +bool xRedisClient::commandargv_array(const RedisDBIdx &dbi, const VDATA &vDataIn, ArrayReply &array) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } - std::vector argv( vDataIn.size() ); - std::vector argvlen( vDataIn.size() ); + std::vector argv(vDataIn.size()); + std::vector argvlen(vDataIn.size()); uint32_t j = 0; - for ( VDATA::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j ) { + for (VDATA::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { - for (size_t i = 0; ielements; i++) { + if (RedisPool::CheckReply(reply)) + { + for (size_t i = 0; i < reply->elements; i++) + { DataItem item; item.type = reply->element[i]->type; item.str.assign(reply->element[i]->str, reply->element[i]->len); array.push_back(item); } - bRet = true; - } else { + bRet = true; + } + else + { SetErrInfo(dbi, reply); } @@ -522,29 +621,36 @@ bool xRedisClient::commandargv_array(const RedisDBIdx& dbi, const VDATA& vDataIn return bRet; } -bool xRedisClient::commandargv_array(const RedisDBIdx& dbi, const VDATA& vDataIn, VALUES& array){ +bool xRedisClient::commandargv_array(const RedisDBIdx &dbi, const VDATA &vDataIn, VALUES &array) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } - std::vector argv( vDataIn.size() ); - std::vector argvlen( vDataIn.size() ); + std::vector argv(vDataIn.size()); + std::vector argvlen(vDataIn.size()); uint32_t j = 0; - for ( VDATA::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j ) { + for (VDATA::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { - for (size_t i = 0; ielements; i++) { + if (RedisPool::CheckReply(reply)) + { + for (size_t i = 0; i < reply->elements; i++) + { std::string str(reply->element[i]->str, reply->element[i]->len); array.push_back(str); } - bRet = true; - } else { + bRet = true; + } + else + { SetErrInfo(dbi, reply); } @@ -553,26 +659,32 @@ bool xRedisClient::commandargv_array(const RedisDBIdx& dbi, const VDATA& vDataIn return bRet; } -bool xRedisClient::commandargv_integer(const RedisDBIdx& dbi, const VDATA& vDataIn, int64_t& retval){ +bool xRedisClient::commandargv_integer(const RedisDBIdx &dbi, const VDATA &vDataIn, int64_t &retval) +{ bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex, dbi.mIOtype); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } - std::vector argv( vDataIn.size() ); - std::vector argvlen( vDataIn.size() ); + std::vector argv(vDataIn.size()); + std::vector argvlen(vDataIn.size()); uint32_t j = 0; - for ( VDATA::const_iterator iter = vDataIn.begin(); iter != vDataIn.end(); ++iter, ++j ) { + for (VDATA::const_iterator iter = vDataIn.begin(); iter != vDataIn.end(); ++iter, ++j) + { argv[j] = iter->c_str(), argvlen[j] = iter->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { retval = reply->integer; - bRet = true; - } else { + bRet = true; + } + else + { SetErrInfo(dbi, reply); } @@ -581,50 +693,60 @@ bool xRedisClient::commandargv_integer(const RedisDBIdx& dbi, const VDATA& vData return bRet; } -bool xRedisClient::ScanFun(const char* cmd, const RedisDBIdx& dbi, const std::string *key, - int64_t &cursor, const char* pattern, uint32_t count, ArrayReply& array, xRedisContext& ctx) +bool xRedisClient::ScanFun(const char *cmd, const RedisDBIdx &dbi, const std::string *key, + int64_t &cursor, const char *pattern, uint32_t count, ArrayReply &array, xRedisContext &ctx) { SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; vCmdData.push_back(cmd); - if (NULL != key) { + if (NULL != key) + { vCmdData.push_back(*key); } vCmdData.push_back(toString(cursor)); - if (NULL != pattern) { + if (NULL != pattern) + { vCmdData.push_back("MATCH"); vCmdData.push_back(pattern); } - if (0 != count) { + if (0 != count) + { vCmdData.push_back("COUNT"); vCmdData.push_back(toString(count)); } bool bRet = false; RedisConn *pRedisConn = static_cast(ctx.conn); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } - std::vector argv(vCmdData.size()); + std::vector argv(vCmdData.size()); std::vector argvlen(vCmdData.size()); uint32_t j = 0; - for (VDATA::const_iterator i = vCmdData.begin(); i != vCmdData.end(); ++i, ++j) { + for (VDATA::const_iterator i = vCmdData.begin(); i != vCmdData.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { - if (0 == reply->elements){ + if (RedisPool::CheckReply(reply)) + { + if (0 == reply->elements) + { cursor = 0; - } else { + } + else + { cursor = atoi(reply->element[0]->str); redisReply **replyData = reply->element[1]->element; - for (size_t i = 0; i < reply->element[1]->elements; i++) { + for (size_t i = 0; i < reply->element[1]->elements; i++) + { DataItem item; item.type = replyData[i]->type; item.str.assign(replyData[i]->str, replyData[i]->len); @@ -632,22 +754,11 @@ bool xRedisClient::ScanFun(const char* cmd, const RedisDBIdx& dbi, const std::st } } bRet = true; - } else { + } + else + { SetErrInfo(dbi, reply); } RedisPool::FreeReply(reply); return bRet; } - - - - - - - - - - - - - diff --git a/src/xRedisClient.h b/src/xRedisClient.h deleted file mode 100644 index 5c0c647..0000000 --- a/src/xRedisClient.h +++ /dev/null @@ -1,379 +0,0 @@ -/* - * ---------------------------------------------------------------------------- - * Copyright (c) 2013-2014, xSky - * All rights reserved. - * Distributed under GPL license. - * ---------------------------------------------------------------------------- - */ - -#ifndef _XREDIS_CLIENT_H_ -#define _XREDIS_CLIENT_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace xrc -{ - -#define REDIS_REPLY_STRING 1 -#define REDIS_REPLY_ARRAY 2 -#define REDIS_REPLY_INTEGER 3 -#define REDIS_REPLY_NIL 4 -#define REDIS_REPLY_STATUS 5 -#define REDIS_REPLY_ERROR 6 - - -#define MAX_ERR_STR_LEN 128 - -typedef std::string KEY; -typedef std::string VALUE; -typedef std::vector KEYS; -typedef KEYS FILEDS; -typedef std::vector VALUES; -typedef std::vector VDATA; - -typedef std::set SETDATA; - -typedef struct _REDIS_NODE_{ - uint32_t dbindex; // 节点编号索引,从0开始 - std::string host; // REDIS节点主机IP地址 - uint32_t port; // redis服务端口 - std::string passwd; // redis认证密码 - uint32_t poolsize; // 此节点上的连接池大小 - uint32_t timeout; // 连接超时时间 秒 - uint32_t role; // 节点角色 -}RedisNode; - -/* This is the reply object returned by redisCommand() */ -typedef struct rReply { - int32_t type; /* REDIS_REPLY_* */ - long long integer; /* The integer when type is REDIS_REPLY_INTEGER */ - int32_t len; /* Length of string */ - char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */ - size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */ - struct rReply **element; /* elements vector for REDIS_REPLY_ARRAY */ -} rReply; - - - -typedef uint32_t (*HASHFUN)(const char *); - -class RedisPool; -class xRedisClient; - -class RedisDBIdx { -public: - RedisDBIdx(); - RedisDBIdx(xRedisClient *xredisclient); - ~RedisDBIdx(); - - bool CreateDBIndex(const char *key, HASHFUN fun, uint32_t type); - bool CreateDBIndex(int64_t id, uint32_t type); - char *GetErrInfo() {return mStrerr;} - void SetIOMaster(); - -private: - bool SetErrInfo(const char *info, int32_t len); - void IOtype(uint32_t type); - friend class xRedisClient; - -private: - uint32_t mType; - uint32_t mIndex; - char *mStrerr; - xRedisClient *mClient; - uint32_t mIOtype; - bool mIOFlag; -}; - -typedef struct _DATA_ITEM_{ - int32_t type; - std::string str; - - _DATA_ITEM_ & operator=(const _DATA_ITEM_ &data) { - type = data.type; - str = data.str; - return *this; - } -}DataItem; -typedef std::vector ReplyData; -typedef ReplyData ArrayReply; -typedef std::map ZSETDATA; -typedef std::vector DBIArray; - -typedef struct xRedisContext_{ - void* conn; -}xRedisContext; - -typedef enum _SET_TYPE_{ - TYPE_NONE = 0, - PX = 1, - EX = 2 -}SETPXEX; - -typedef enum _SET_TYPE_NXEX_{ - TNXXX_NONE = 0, - NX = 1, - XX = 2 -}SETNXXX; - -typedef enum _BIT_OP_{ - AND = 0, - OR = 1, - XOR = 2, - NOT = 3 -}BITOP; - -typedef enum _LIST_MODEL_{ - BEFORE = 0, - AFTER = 1 -}LMODEL; - - -typedef enum _SORT_ORDER_{ - ASC = 0, - DESC = 1 -}SORTODER; - -typedef struct _SORT_LIMIT_ -{ - int32_t offset; - int32_t count; -}LIMIT; - -template -std::string toString(const T &t) { - std::ostringstream oss; - oss << t; - return oss.str(); -} - -typedef enum _REDIS_ROLE_{ - MASTER = 0, - SLAVE = 1 -}ROLE; - -#define SETDEFAULTIOTYPE(type) if (!dbi.mIOFlag) {SetIOtype(dbi, type);} - -class xRedisClient{ -public: - xRedisClient(); - ~xRedisClient(); - - bool Init(uint32_t maxtype); - void Release(); - void Keepalive(); - inline RedisPool *GetRedisPool(); - static void FreeReply(const rReply* reply); - static int32_t GetReply(xRedisContext* ctx, ReplyData& vData); - bool GetxRedisContext(const RedisDBIdx& dbi, xRedisContext* ctx); - void FreexRedisContext(xRedisContext* ctx); - bool ConnectRedisCache(const RedisNode *redisnodelist, uint32_t nodecount, - uint32_t hashbase, uint32_t cachetype); - -public: - - // Connection - /* AUTH */ /* nonsupport */ - /* ECHO */ bool echo(const RedisDBIdx& dbi, const std::string& str, std::string &value); - /* PING */ /* nonsupport */ - /* QUIT */ void quit(); - /* SELECT */ /* nonsupport */ - - // Commands operating on std::string values - /* APPEND */ bool append(const RedisDBIdx& dbi, const std::string& key, const std::string& value); - /* BITCOUNT */ bool bitcount(const RedisDBIdx& dbi,const std::string& key, int32_t& count, int32_t start=0, int32_t end=0); - /* BITOP */ bool bitop(const RedisDBIdx& dbi, const BITOP operation, const std::string& destkey, const KEYS& keys, int32_t& lenght); - /* BITPOS */ bool bitpos(const RedisDBIdx& dbi, const std::string& key, int32_t bit, int64_t& pos, int32_t start=0, int32_t end=0); - /* DECR */ bool decr(const RedisDBIdx& dbi, const std::string& key, int64_t& result); - /* DECRBY */ bool decrby(const RedisDBIdx& dbi, const std::string& key, int32_t by, int64_t& result); - /* GET */ bool get(const RedisDBIdx& dbi, const std::string& key, std::string& value); - /* GETBIT */ bool getbit(const RedisDBIdx& dbi, const std::string& key, int32_t& offset, int32_t& bit); - /* GETRANGE */ bool getrange(const RedisDBIdx& dbi,const std::string& key, int32_t start, int32_t end, std::string& out); - /* GETSET */ bool getset(const RedisDBIdx& dbi, const std::string& key, const std::string& newValue, std::string& oldValue); - /* INCR */ bool incr(const RedisDBIdx& dbi, const std::string& key, int64_t& result); - /* INCRBY */ bool incrby(const RedisDBIdx& dbi, const std::string& key, int32_t by, int64_t& result); - /* INCRBYFLOAT */ - /* MGET */ bool mget(const DBIArray& dbi, const KEYS & keys, ReplyData& vDdata); - /* MSET */ bool mset(const DBIArray& dbi, const VDATA& data); - /* MSETNX */ - /* PSETEX */ bool psetex(const RedisDBIdx& dbi, const std::string& key, int32_t milliseconds, const std::string& value); - /* SET */ bool set(const RedisDBIdx& dbi, const std::string& key, const std::string& value); - /* SET */ bool set(const RedisDBIdx& dbi, const std::string& key, const char *value, int32_t len, int32_t second); - /* SET */ bool set(const RedisDBIdx& dbi, const std::string& key, const std::string& value, - SETPXEX pxex, int32_t expiretime, SETNXXX nxxx); - /* SETBIT */ bool setbit(const RedisDBIdx& dbi, const std::string& key, int32_t offset, int64_t newbitValue, int64_t oldbitValue); - /* SETEX */ bool setex(const RedisDBIdx& dbi, const std::string& key, int32_t seconds, const std::string& value); - /* SETNX */ bool setnx(const RedisDBIdx& dbi, const std::string& key, const std::string& value); - /* SETRANGE */ bool setrange(const RedisDBIdx& dbi,const std::string& key, int32_t offset, const std::string& value, int32_t& length); - /* STRLEN */ bool strlen(const RedisDBIdx& dbi, const std::string& key, int32_t& length); - - - /* DEL */ bool del(const RedisDBIdx& dbi, const std::string& key); - bool del(const DBIArray& dbi, const KEYS & vkey, int64_t& count); - /* DUMP */ - /* EXISTS */ bool exists(const RedisDBIdx& dbi, const std::string& key); - /* EXPIRE */ bool expire(const RedisDBIdx& dbi, const std::string& key, uint32_t second); - /* EXPIREAT */ bool expireat(const RedisDBIdx& dbi, const std::string& key, uint32_t timestamp); - /* KEYS */ - /* MIGRATE */ - /* MOVE */ - /* OBJECT */ - /* PERSIST */ bool persist(const RedisDBIdx& dbi, const std::string& key); - /* PEXPIRE */ bool pexpire(const RedisDBIdx& dbi, const std::string& key, uint32_t milliseconds); - /* PEXPIREAT */ bool pexpireat(const RedisDBIdx& dbi, const std::string& key, uint32_t millisecondstimestamp); - /* PTTL */ bool pttl(const RedisDBIdx& dbi, const std::string& key, int64_t &milliseconds); - /* RANDOMKEY */ bool randomkey(const RedisDBIdx& dbi, KEY& key); - /* RENAME */ - /* RENAMENX */ - /* RESTORE */ - /* SCAN */ bool scan(const RedisDBIdx& dbi, int64_t &cursor, - const char *pattern, uint32_t count, ArrayReply& array, xRedisContext& ctx); - - - /* SORT */ bool sort(const RedisDBIdx& dbi, ArrayReply& array, const std::string& key, const char* by = NULL, - LIMIT *limit = NULL, bool alpha = false, const FILEDS* get = NULL, - const SORTODER order = ASC, const char* destination = NULL); - - /* TTL */ bool ttl(const RedisDBIdx& dbi, const std::string& key, int64_t& seconds); - /* TYPE */ bool type(const RedisDBIdx& dbi, const std::string& key, std::string& value); - - - /* HDEL */ bool hdel(const RedisDBIdx& dbi, const std::string& key, const std::string& field, int64_t& num); - bool hdel(const RedisDBIdx& dbi, const std::string& key, const KEYS& vfiled, int64_t& num); - /* HEXISTS */ bool hexist(const RedisDBIdx& dbi, const std::string& key, const std::string& field); - /* HGET */ bool hget(const RedisDBIdx& dbi, const std::string& key, const std::string& field, std::string& value); - /* HGETALL */ bool hgetall(const RedisDBIdx& dbi, const std::string& key, ArrayReply& array); - /* HINCRBY */ bool hincrby(const RedisDBIdx& dbi, const std::string& key, const std::string& field, int64_t increment ,int64_t& value); - /* HINCRBYFLOAT */ bool hincrbyfloat(const RedisDBIdx& dbi, const std::string& key, const std::string& field, const float increment, float& value); - /* HKEYS */ bool hkeys(const RedisDBIdx& dbi, const std::string& key, KEYS& keys); - /* HLEN */ bool hlen(const RedisDBIdx& dbi, const std::string& key, int64_t& count); - /* HMGET */ bool hmget(const RedisDBIdx& dbi, const std::string& key, const KEYS& field, ArrayReply& array); - /* HMSET */ bool hmset(const RedisDBIdx& dbi, const std::string& key, const VDATA& vData); - /* HSCAN */ bool hscan(const RedisDBIdx& dbi, const std::string& key, int64_t &cursor, - const char *pattern, uint32_t count, ArrayReply& array, xRedisContext& ctx); - /* HSET */ bool hset(const RedisDBIdx& dbi, const std::string& key, const std::string& field, const std::string& value, int64_t& retval); - /* HSETNX */ bool hsetnx(const RedisDBIdx& dbi, const std::string& key, const std::string& field, const std::string& value); - /* HVALS */ bool hvals(const RedisDBIdx& dbi, const std::string& key, VALUES& values); - - /* BLPOP */ bool blPop(const RedisDBIdx& dbi, const std::string& key, VALUES& vValues, int64_t timeout); - /* BRPOP */ bool brPop(const RedisDBIdx& dbi, const std::string& key, VALUES& vValues, int64_t timeout); - /* BRPOPLPUSH */ bool brPoplpush(const RedisDBIdx& dbi, const std::string& key, std::string& targetkey, VALUE& value, int64_t timeout); - /* LINDEX */ bool lindex(const RedisDBIdx& dbi, const std::string& key, int64_t index, VALUE& value); - /* LINSERT */ bool linsert(const RedisDBIdx& dbi, const std::string& key, LMODEL mod, const std::string& pivot, const std::string& value, int64_t& retval); - /* LLEN */ bool llen(const RedisDBIdx& dbi, const std::string& key, int64_t& len); - /* LPOP */ bool lpop(const RedisDBIdx& dbi, const std::string& key, std::string& value); - /* LPUSH */ bool lpush(const RedisDBIdx& dbi, const std::string& key, const VALUES& vValue, int64_t& length); - /* LPUSHX */ bool lpushx(const RedisDBIdx& dbi, const std::string& key, const std::string& value, int64_t& length); - /* LRANGE */ bool lrange(const RedisDBIdx& dbi, const std::string& key, int64_t start, int64_t end, ArrayReply& array); - /* LREM */ bool lrem(const RedisDBIdx& dbi, const std::string& key, int32_t count, const std::string& value, int64_t num); - /* LSET */ bool lset(const RedisDBIdx& dbi, const std::string& key, int32_t index, const std::string& value); - /* LTRIM */ bool ltrim(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t end); - /* RPOP */ bool rpop(const RedisDBIdx& dbi, const std::string& key, std::string& value); - /* RPOPLPUSH */ bool rpoplpush(const RedisDBIdx& dbi,const std::string& key_src, const std::string& key_dest, std::string& value); - /* RPUSH */ bool rpush(const RedisDBIdx& dbi, const std::string& key, const VALUES& vValue, int64_t& length); - /* RPUSHX */ bool rpushx(const RedisDBIdx& dbi, const std::string& key, const std::string& value, int64_t& length); - - /* SADD */ bool sadd(const RedisDBIdx& dbi, const KEY& key, const VALUES& vValue, int64_t& count); - /* SCARD */ bool scard(const RedisDBIdx& dbi, const KEY& key, int64_t& count); - /* SDIFF */ bool sdiff(const DBIArray& dbi, const KEYS& vKkey, VALUES& vValue); - /* SDIFFSTORE */ bool sdiffstore(const RedisDBIdx& dbi, const KEY& destinationkey, const DBIArray& vdbi, const KEYS& vkey, int64_t& count); - /* SINTER */ bool sinter(const DBIArray& dbi, const KEYS& vkey, VALUES& vValue); - /* SINTERSTORE */ bool sinterstore(const RedisDBIdx& dbi, const KEY& destinationkey, const DBIArray& vdbi, const KEYS& vkey, int64_t& count); - /* SISMEMBER */ bool sismember(const RedisDBIdx& dbi, const KEY& key, const VALUE& member); - /* SMEMBERS */ bool smembers(const RedisDBIdx& dbi, const KEY& key, VALUES& vValue); - /* SMOVE */ bool smove(const RedisDBIdx& dbi, const KEY& srckey, const KEY& deskey, const VALUE& member); - /* SPOP */ bool spop(const RedisDBIdx& dbi, const KEY& key, VALUE& member); - /* SRANDMEMBER */ bool srandmember(const RedisDBIdx& dbi, const KEY& key, VALUES& vmember, int32_t num=0); - /* SREM */ bool srem(const RedisDBIdx& dbi, const KEY& key, const VALUES& vmembers, int64_t& count); - /* SSCAN */ bool sscan(const RedisDBIdx& dbi, const std::string& key, int64_t &cursor, - const char *pattern, uint32_t count, ArrayReply& array, xRedisContext& ctx); - /* SUNION */ bool sunion(const DBIArray& dbi, const KEYS& vkey, VALUES& vValue); - /* SUNIONSTORE */ bool sunionstore(const RedisDBIdx& dbi, const KEY& deskey, const DBIArray& vdbi, const KEYS& vkey, int64_t& count); - - /* ZADD */ bool zadd(const RedisDBIdx& dbi, const KEY& deskey, const VALUES& vValues, int64_t& count); - /* ZCARD */ bool zscrad(const RedisDBIdx& dbi, const std::string& key, int64_t& num); - /* ZCOUNT */ - /* ZINCRBY */ bool zincrby(const RedisDBIdx& dbi, const std::string& key, const double &increment, const std::string& member, std::string& value ); - /* ZINTERSTORE */ - /* ZRANGE */ bool zrange(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t end, VALUES& vValues, bool withscore=false); - /* ZRANGEBYSCORE */ bool zrangebyscore(const RedisDBIdx& dbi, const std::string& key, const std::string& min, - const std::string& max, VALUES& vValues, bool withscore=false, LIMIT *limit = NULL); - /* ZRANK */ bool zrank(const RedisDBIdx& dbi, const std::string& key, const std::string& member, int64_t &rank); - /* ZREM */ bool zrem(const RedisDBIdx& dbi, const KEY& key, const VALUES& vmembers, int64_t &num); - /* ZREMRANGEBYRANK */ bool zremrangebyrank(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t stop, int64_t& num); - /* ZREMRANGEBYSCORE */ bool zremrangebyscore(const RedisDBIdx& dbi, const KEY& key, double min, double max, int64_t& count); - /* ZREVRANGE */ bool zrevrange(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t end, VALUES& vValues, bool withscore=false); - /* ZREVRANGEBYLEX */ bool zrevrangebylex(const RedisDBIdx& dbi, const std::string& key, std::string& start, std::string& end, VALUES& vValues, int32_t offset = 0, int32_t count = 0); - /* ZREVRANGEBYSCORE */ - /* ZREVRANK */ bool zrevrank(const RedisDBIdx& dbi, const std::string& key, const std::string &member, int64_t& rank); - /* ZSCAN */ bool zscan(const RedisDBIdx& dbi, const std::string& key, int64_t &cursor, const char *pattern, - uint32_t count, ArrayReply& array, xRedisContext& ctx); - /* ZSCORE */ bool zscore(const RedisDBIdx& dbi, const std::string& key, const std::string &member, std::string& score); - /* ZUNIONSTORE */ - - /* 注意: 使用下面的 pub/sub 命令时,一定要保证数据都在同一个REDIS实例里,xredis目前的pub/sub命令实现不支持多节点数据分布的场景。 */ - /* PSUBSCRIBE */ bool psubscribe(const RedisDBIdx& dbi, const KEYS& patterns, xRedisContext& ctx); - /* PUBLISH */ bool publish(const RedisDBIdx& dbi, const KEY& channel, const std::string& message, int64_t& count); - /* PUBSUB */ bool pubsub_channels(const RedisDBIdx& dbi, const std::string &pattern, ArrayReply &reply); - bool pubsub_numsub(const RedisDBIdx& dbi, const KEYS &keys, ArrayReply &reply); - bool pubsub_numpat(const RedisDBIdx& dbi, int64_t& count); - /* PUNSUBSCRIBE */ bool punsubscribe(const RedisDBIdx& dbi, const KEYS& patterns, xRedisContext& ctx); - /* SUBSCRIBE */ bool subscribe(const RedisDBIdx& dbi, const KEYS& channels, xRedisContext& ctx); - /* UNSUBSCRIBE */ bool unsubscribe(const RedisDBIdx& dbi, const KEYS& channels, xRedisContext& ctx); - - - /* DISCARD */ - /* EXEC */ - /* MULTI */ - /* UNWATCH */ - /* WATCH */ - - -private: - void addparam(VDATA& vDes, const VDATA& vSrc) { - for (VDATA::const_iterator iter=vSrc.begin(); iter!=vSrc.end();++iter) { - vDes.push_back(*iter); - } - } - void SetErrInfo(const RedisDBIdx& dbi, void *p); - void SetErrString(const RedisDBIdx& dbi, const char *str, int32_t len); - void SetErrMessage(const RedisDBIdx& dbi, const char* fmt, ...); - void SetIOtype(const RedisDBIdx& dbi, uint32_t iotype, bool ioflag = false); - bool ScanFun(const char* cmd, const RedisDBIdx& dbi, const std::string *key, int64_t &cursor, - const char* pattern, uint32_t count, ArrayReply& array, xRedisContext& ctx); - -public: - - bool command_bool(const RedisDBIdx& dbi, const char* cmd, ...); - bool command_status(const RedisDBIdx& dbi, const char* cmd, ...); - bool command_integer(const RedisDBIdx& dbi, int64_t &intval, const char* cmd, ...); - bool command_string(const RedisDBIdx& dbi, std::string &data, const char* cmd, ...); - bool command_list(const RedisDBIdx& dbi, VALUES &vValue, const char* cmd, ...); - bool command_array(const RedisDBIdx& dbi, ArrayReply& array, const char* cmd, ...); - rReply *command(const RedisDBIdx& dbi, const char* cmd); -private: - bool commandargv_bool(const RedisDBIdx& dbi, const VDATA& vData); - bool commandargv_status(const RedisDBIdx& dbi, const VDATA& vData); - bool commandargv_array(const RedisDBIdx& dbi, const VDATA& vDataIn, ArrayReply& array); - bool commandargv_array(const RedisDBIdx& dbi, const VDATA& vDataIn, VALUES& array); - bool commandargv_integer(const RedisDBIdx& dbi,const VDATA& vDataIn, int64_t& retval); - bool commandargv_array_ex(const RedisDBIdx& dbi, const VDATA& vDataIn, xRedisContext& ctx); -private: - RedisPool *mRedisPool; -}; - -} - -#endif - - - - - diff --git a/src/xRedisClient_connection.cpp b/src/xRedisClient_connection.cpp index 5ee66e3..461bd7e 100644 --- a/src/xRedisClient_connection.cpp +++ b/src/xRedisClient_connection.cpp @@ -10,30 +10,17 @@ #include using namespace xrc; -void xRedisClient::quit(){ - Release(); +void xRedisClient::quit() +{ + Release(); } - -bool xRedisClient::echo(const RedisDBIdx& dbi, const std::string& str, std::string &value) +bool xRedisClient::echo(const RedisDBIdx &dbi, const std::string &str, std::string &value) { - if (0==str.length()) { + if (0 == str.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_string(dbi, value, "echo %s", str.c_str()); } - - - - - - - - - - - - - - diff --git a/src/xRedisClient_hashs.cpp b/src/xRedisClient_hashs.cpp index 3f51b6d..3bdeb0e 100644 --- a/src/xRedisClient_hashs.cpp +++ b/src/xRedisClient_hashs.cpp @@ -12,12 +12,14 @@ #include using namespace xrc; -bool xRedisClient::hdel(const RedisDBIdx& dbi, const std::string& key, const std::string& field, int64_t& count) { +bool xRedisClient::hdel(const RedisDBIdx &dbi, const std::string &key, const std::string &field, int64_t &count) +{ SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, count, "HDEL %s %s", key.c_str(), field.c_str()); } -bool xRedisClient::hdel(const RedisDBIdx& dbi, const std::string& key, const KEYS& vfiled, int64_t& count) { +bool xRedisClient::hdel(const RedisDBIdx &dbi, const std::string &key, const KEYS &vfiled, int64_t &count) +{ VDATA vCmdData; vCmdData.push_back("HDEL"); vCmdData.push_back(key); @@ -26,36 +28,43 @@ bool xRedisClient::hdel(const RedisDBIdx& dbi, const std::string& key, const KEY return commandargv_integer(dbi, vCmdData, count); } -bool xRedisClient::hexist(const RedisDBIdx& dbi, const std::string& key, const std::string& field){ +bool xRedisClient::hexist(const RedisDBIdx &dbi, const std::string &key, const std::string &field) +{ SETDEFAULTIOTYPE(SLAVE); - return command_bool(dbi,"HEXISTS %s %s", key.c_str(), field.c_str()); + return command_bool(dbi, "HEXISTS %s %s", key.c_str(), field.c_str()); } -bool xRedisClient::hget(const RedisDBIdx& dbi, const std::string& key, const std::string& field, std::string& value) { +bool xRedisClient::hget(const RedisDBIdx &dbi, const std::string &key, const std::string &field, std::string &value) +{ SETDEFAULTIOTYPE(SLAVE); return command_string(dbi, value, "HGET %s %s", key.c_str(), field.c_str()); } -bool xRedisClient::hgetall(const RedisDBIdx& dbi, const std::string& key, ArrayReply& array){ +bool xRedisClient::hgetall(const RedisDBIdx &dbi, const std::string &key, ArrayReply &array) +{ SETDEFAULTIOTYPE(SLAVE); return command_array(dbi, array, "HGETALL %s", key.c_str()); } -bool xRedisClient::hincrby(const RedisDBIdx& dbi, const std::string& key, const std::string& field, int64_t increment, int64_t& num) { +bool xRedisClient::hincrby(const RedisDBIdx &dbi, const std::string &key, const std::string &field, int64_t increment, int64_t &num) +{ SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, num, "HINCRBY %s %s %lld", key.c_str(),field.c_str(), increment); + return command_integer(dbi, num, "HINCRBY %s %s %lld", key.c_str(), field.c_str(), increment); } -bool xRedisClient::hincrbyfloat(const RedisDBIdx& dbi, const std::string& key, const std::string& field, float increment, float& value) { +bool xRedisClient::hincrbyfloat(const RedisDBIdx &dbi, const std::string &key, const std::string &field, float increment, float &value) +{ SETDEFAULTIOTYPE(MASTER); bool bRet = false; RedisConn *pRedisConn = mRedisPool->GetConnection(dbi.mType, dbi.mIndex); - if (NULL==pRedisConn) { + if (NULL == pRedisConn) + { return false; } redisReply *reply = static_cast(redisCommand(pRedisConn->getCtx(), "HINCRBYFLOAT %s %s %f", key.c_str(), field.c_str(), increment)); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { value = atof(reply->str); bRet = true; } @@ -65,17 +74,20 @@ bool xRedisClient::hincrbyfloat(const RedisDBIdx& dbi, const std::string& key, c return bRet; } -bool xRedisClient::hkeys(const RedisDBIdx& dbi, const std::string& key, KEYS& keys){ +bool xRedisClient::hkeys(const RedisDBIdx &dbi, const std::string &key, KEYS &keys) +{ SETDEFAULTIOTYPE(SLAVE); return command_list(dbi, keys, "HKEYS %s", key.c_str()); } -bool xRedisClient::hlen(const RedisDBIdx& dbi, const std::string& key, int64_t& count){ +bool xRedisClient::hlen(const RedisDBIdx &dbi, const std::string &key, int64_t &count) +{ SETDEFAULTIOTYPE(SLAVE); return command_integer(dbi, count, "HLEN %s", key.c_str()); } -bool xRedisClient::hmget(const RedisDBIdx& dbi, const std::string& key, const KEYS& field, ArrayReply& array){ +bool xRedisClient::hmget(const RedisDBIdx &dbi, const std::string &key, const KEYS &field, ArrayReply &array) +{ VDATA vCmdData; vCmdData.push_back("HMGET"); vCmdData.push_back(key); @@ -84,7 +96,8 @@ bool xRedisClient::hmget(const RedisDBIdx& dbi, const std::string& key, const KE return commandargv_array(dbi, vCmdData, array); } -bool xRedisClient::hmset(const RedisDBIdx& dbi, const std::string& key, const VDATA& vData){ +bool xRedisClient::hmset(const RedisDBIdx &dbi, const std::string &key, const VDATA &vData) +{ VDATA vCmdData; vCmdData.push_back("HMSET"); vCmdData.push_back(key); @@ -93,12 +106,13 @@ bool xRedisClient::hmset(const RedisDBIdx& dbi, const std::string& key, const VD return commandargv_status(dbi, vCmdData); } -bool xRedisClient::hscan(const RedisDBIdx& dbi, const std::string& key, int64_t &cursor, const char *pattern, uint32_t count, ArrayReply& array, xRedisContext& ctx) +bool xRedisClient::hscan(const RedisDBIdx &dbi, const std::string &key, int64_t &cursor, const char *pattern, uint32_t count, ArrayReply &array, xRedisContext &ctx) { return ScanFun("HSCAN", dbi, &key, cursor, pattern, count, array, ctx); } -bool xRedisClient::hset(const RedisDBIdx& dbi, const std::string& key, const std::string& field, const std::string& value, int64_t& retval){ +bool xRedisClient::hset(const RedisDBIdx &dbi, const std::string &key, const std::string &field, const std::string &value, int64_t &retval) +{ SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; vCmdData.push_back("HSET"); @@ -109,14 +123,14 @@ bool xRedisClient::hset(const RedisDBIdx& dbi, const std::string& key, const std //return command_integer(dbi, retval, "HSET %s %s %s", key.c_str(), field.c_str(), value.c_str()); } -bool xRedisClient::hsetnx(const RedisDBIdx& dbi, const std::string& key, const std::string& field, const std::string& value){ +bool xRedisClient::hsetnx(const RedisDBIdx &dbi, const std::string &key, const std::string &field, const std::string &value) +{ SETDEFAULTIOTYPE(MASTER); return command_bool(dbi, "HSETNX %s %s %s", key.c_str(), field.c_str(), value.c_str()); } -bool xRedisClient::hvals(const RedisDBIdx& dbi, const std::string& key, VALUES& values) { +bool xRedisClient::hvals(const RedisDBIdx &dbi, const std::string &key, VALUES &values) +{ SETDEFAULTIOTYPE(SLAVE); return command_list(dbi, values, "HVALS %s", key.c_str()); } - - diff --git a/src/xRedisClient_keys.cpp b/src/xRedisClient_keys.cpp index 6c38a88..be79d80 100644 --- a/src/xRedisClient_keys.cpp +++ b/src/xRedisClient_keys.cpp @@ -11,8 +11,10 @@ #include using namespace xrc; -bool xRedisClient::del(const RedisDBIdx& dbi, const std::string& key) { - if (0==key.length()) { +bool xRedisClient::del(const RedisDBIdx &dbi, const std::string &key) +{ + if (0 == key.length()) + { return false; } @@ -20,156 +22,182 @@ bool xRedisClient::del(const RedisDBIdx& dbi, const std::string& key) { return command_bool(dbi, "DEL %s", key.c_str()); } -bool xRedisClient::del(const DBIArray& vdbi, const KEYS & vkey, int64_t& count) { +bool xRedisClient::del(const DBIArray &vdbi, const KEYS &vkey, int64_t &count) +{ count = 0; - if (vdbi.size()!=vkey.size()) { + if (vdbi.size() != vkey.size()) + { return false; } DBIArray::const_iterator iter_dbi = vdbi.begin(); - KEYS::const_iterator iter_key = vkey.begin(); - for(;iter_key!=vkey.end();++iter_key, ++iter_dbi) { + KEYS::const_iterator iter_key = vkey.begin(); + for (; iter_key != vkey.end(); ++iter_key, ++iter_dbi) + { const RedisDBIdx &dbi = (*iter_dbi); const std::string &key = (*iter_key); - if (del(dbi, key)) { + if (del(dbi, key)) + { count++; } } return true; } -bool xRedisClient::exists(const RedisDBIdx& dbi, const std::string& key) { - if (0==key.length()) { +bool xRedisClient::exists(const RedisDBIdx &dbi, const std::string &key) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_bool(dbi, "EXISTS %s", key.c_str()); } -bool xRedisClient::expire(const RedisDBIdx& dbi, const std::string& key, uint32_t second) { - if (0==key.length()) { +bool xRedisClient::expire(const RedisDBIdx &dbi, const std::string &key, uint32_t second) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); int64_t ret = -1; - if (!command_integer(dbi, ret, "EXPIRE %s %u", key.c_str(), second)) { + if (!command_integer(dbi, ret, "EXPIRE %s %u", key.c_str(), second)) + { return false; } - if (1==ret) { + if (1 == ret) + { return true; - } else { + } + else + { SetErrMessage(dbi, "expire return %ld ", ret); return false; } } -bool xRedisClient::expireat(const RedisDBIdx& dbi, const std::string& key, uint32_t timestamp) { - if (0==key.length()) { +bool xRedisClient::expireat(const RedisDBIdx &dbi, const std::string &key, uint32_t timestamp) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_bool(dbi, "EXPIREAT %s %u", key.c_str(), timestamp); } -bool xRedisClient::persist(const RedisDBIdx& dbi, const std::string& key) { - if (0==key.length()) { +bool xRedisClient::persist(const RedisDBIdx &dbi, const std::string &key) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_bool(dbi, "PERSIST %s %u", key.c_str()); } -bool xRedisClient::pexpire(const RedisDBIdx& dbi, const std::string& key, uint32_t milliseconds) { - if (0==key.length()) { +bool xRedisClient::pexpire(const RedisDBIdx &dbi, const std::string &key, uint32_t milliseconds) +{ + if (0 == key.length()) + { return false; } return command_bool(dbi, "PEXPIRE %s %u", key.c_str(), milliseconds); } -bool xRedisClient::pexpireat(const RedisDBIdx& dbi, const std::string& key, uint32_t millisecondstimestamp) { - if (0==key.length()) { +bool xRedisClient::pexpireat(const RedisDBIdx &dbi, const std::string &key, uint32_t millisecondstimestamp) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_bool(dbi, "PEXPIREAT %s %u", key.c_str(), millisecondstimestamp); } -bool xRedisClient::pttl(const RedisDBIdx& dbi, const std::string& key, int64_t &milliseconds) { - if (0==key.length()) { +bool xRedisClient::pttl(const RedisDBIdx &dbi, const std::string &key, int64_t &milliseconds) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, milliseconds, "PTTL %s", key.c_str()); } -bool xRedisClient::ttl(const RedisDBIdx& dbi, const std::string& key, int64_t &seconds) { - if (0==key.length()) { +bool xRedisClient::ttl(const RedisDBIdx &dbi, const std::string &key, int64_t &seconds) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); return command_integer(dbi, seconds, "TTL %s", key.c_str()); } -bool xRedisClient::type(const RedisDBIdx& dbi, const std::string& key, std::string& value){ +bool xRedisClient::type(const RedisDBIdx &dbi, const std::string &key, std::string &value) +{ SETDEFAULTIOTYPE(MASTER); return command_string(dbi, value, "TYPE %s", key.c_str()); } -bool xRedisClient::randomkey(const RedisDBIdx& dbi, KEY& key){ +bool xRedisClient::randomkey(const RedisDBIdx &dbi, KEY &key) +{ SETDEFAULTIOTYPE(SLAVE); return command_string(dbi, key, "RANDOMKEY"); } -bool xRedisClient::scan(const RedisDBIdx& dbi, int64_t &cursor, const char *pattern, - uint32_t count, ArrayReply& array, xRedisContext& ctx) +bool xRedisClient::scan(const RedisDBIdx &dbi, int64_t &cursor, const char *pattern, + uint32_t count, ArrayReply &array, xRedisContext &ctx) { - return ScanFun("SCAN",dbi, NULL, cursor, pattern, count, array, ctx); + return ScanFun("SCAN", dbi, NULL, cursor, pattern, count, array, ctx); } -bool xRedisClient::sort(const RedisDBIdx& dbi, ArrayReply& array, const std::string& key, const char* by, - LIMIT *limit /*= NULL*/, bool alpha /*= false*/, const FILEDS* get /*= NULL*/, - const SORTODER order /*= ASC*/, const char* destination ) +bool xRedisClient::sort(const RedisDBIdx &dbi, ArrayReply &array, const std::string &key, const char *by, + LIMIT *limit /*= NULL*/, bool alpha /*= false*/, const FILEDS *get /*= NULL*/, + const SORTODER order /*= ASC*/, const char *destination) { - static const char *sort_order[3] = { "ASC", "DESC" }; - if (0 == key.length()) { + static const char *sort_order[3] = {"ASC", "DESC"}; + if (0 == key.length()) + { return false; } - VDATA vCmdData; vCmdData.push_back("sort"); vCmdData.push_back(key); - if (NULL != by) { + if (NULL != by) + { vCmdData.push_back("by"); vCmdData.push_back(by); } - if (NULL != limit) { + if (NULL != limit) + { vCmdData.push_back("LIMIT"); vCmdData.push_back(toString(limit->offset)); vCmdData.push_back(toString(limit->count)); } - if (alpha) { + if (alpha) + { vCmdData.push_back("ALPHA"); } - if (NULL != get) { - for (FILEDS::const_iterator iter = get->begin(); iter != get->end(); ++iter) { + if (NULL != get) + { + for (FILEDS::const_iterator iter = get->begin(); iter != get->end(); ++iter) + { vCmdData.push_back("get"); vCmdData.push_back(*iter); } } vCmdData.push_back(sort_order[order]); - if (destination) { + if (destination) + { vCmdData.push_back(destination); } SETDEFAULTIOTYPE(MASTER); return commandargv_array(dbi, vCmdData, array); } - - - - - - diff --git a/src/xRedisClient_lists.cpp b/src/xRedisClient_lists.cpp index 7a90e66..c77bfee 100644 --- a/src/xRedisClient_lists.cpp +++ b/src/xRedisClient_lists.cpp @@ -6,76 +6,89 @@ * ---------------------------------------------------------------------------- */ -#include +#include #include "xRedisClient.h" #include using namespace xrc; -bool xRedisClient::lindex(const RedisDBIdx& dbi, const std::string& key, int64_t index, VALUE& value){ - if (0==key.length()) { +bool xRedisClient::lindex(const RedisDBIdx &dbi, const std::string &key, int64_t index, VALUE &value) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); return command_string(dbi, value, "LINDEX %s %lld", key.c_str(), index); } -bool xRedisClient::linsert(const RedisDBIdx& dbi, const std::string& key, const LMODEL mod, const std::string& pivot, const std::string& value, int64_t& retval){ - static const char *lmodel[2]= {"BEFORE","AFTER"}; - if (0==key.length()) { +bool xRedisClient::linsert(const RedisDBIdx &dbi, const std::string &key, const LMODEL mod, const std::string &pivot, const std::string &value, int64_t &retval) +{ + static const char *lmodel[2] = {"BEFORE", "AFTER"}; + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, retval, "LINSERT %s %s %s %s", key.c_str(), lmodel[mod], pivot.c_str(), value.c_str()); } -bool xRedisClient::llen(const RedisDBIdx& dbi, const std::string& key, int64_t& retval){ - if (0==key.length()) { +bool xRedisClient::llen(const RedisDBIdx &dbi, const std::string &key, int64_t &retval) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); return command_integer(dbi, retval, "LLEN %s", key.c_str()); } -bool xRedisClient::blPop(const RedisDBIdx& dbi, const std::string& key, VALUES& vValues, int64_t timeout) +bool xRedisClient::blPop(const RedisDBIdx &dbi, const std::string &key, VALUES &vValues, int64_t timeout) { - if (0==key.length()) { + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); - return command_list(dbi, vValues, "BLPOP %s %d", key.c_str(), (int32_t)timeout); + return command_list(dbi, vValues, "BLPOP %s %d", key.c_str(), (int32_t)timeout); } -bool xRedisClient::brPop(const RedisDBIdx& dbi, const std::string& key, VALUES& vValues, int64_t timeout) +bool xRedisClient::brPop(const RedisDBIdx &dbi, const std::string &key, VALUES &vValues, int64_t timeout) { - if (0==key.length()) { + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); - return command_list(dbi, vValues, "BRPOP %s %d", key.c_str(), (int32_t)timeout); + return command_list(dbi, vValues, "BRPOP %s %d", key.c_str(), (int32_t)timeout); } -bool xRedisClient::brPoplpush(const RedisDBIdx& dbi, const std::string& key, std::string& targetkey, VALUE& value, int64_t timeout) +bool xRedisClient::brPoplpush(const RedisDBIdx &dbi, const std::string &key, std::string &targetkey, VALUE &value, int64_t timeout) { - if (0==key.length()) { + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "BRPOPLPUSH %s %s %d", key.c_str(), targetkey.c_str(), (int32_t)timeout); + return command_string(dbi, value, "BRPOPLPUSH %s %s %d", key.c_str(), targetkey.c_str(), (int32_t)timeout); } -bool xRedisClient::lpop(const RedisDBIdx& dbi, const std::string& key, std::string& value){ - if (0==key.length()) { +bool xRedisClient::lpop(const RedisDBIdx &dbi, const std::string &key, std::string &value) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_string(dbi, value, "LPOP %s", key.c_str()); } -bool xRedisClient::lpush(const RedisDBIdx& dbi, const std::string& key, const VALUES& vValue, int64_t& length){ - if (0==key.length()) { +bool xRedisClient::lpush(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &length) +{ + if (0 == key.length()) + { return false; } - VDATA vCmdData; + VDATA vCmdData; vCmdData.push_back("LPUSH"); vCmdData.push_back(key); addparam(vCmdData, vValue); @@ -83,59 +96,73 @@ bool xRedisClient::lpush(const RedisDBIdx& dbi, const std::string& key, const VA return commandargv_integer(dbi, vCmdData, length); } -bool xRedisClient::lrange(const RedisDBIdx& dbi, const std::string& key, int64_t start, int64_t end, ArrayReply& array){ - if (0==key.length()) { +bool xRedisClient::lrange(const RedisDBIdx &dbi, const std::string &key, int64_t start, int64_t end, ArrayReply &array) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); - return command_array(dbi, array, "LRANGE %s %lld %lld", key.c_str(), start, end); + return command_array(dbi, array, "LRANGE %s %lld %lld", key.c_str(), start, end); } -bool xRedisClient::lrem(const RedisDBIdx& dbi, const std::string& key, int32_t count, const std::string& value, int64_t num){ - if (0==key.length()) { +bool xRedisClient::lrem(const RedisDBIdx &dbi, const std::string &key, int32_t count, const std::string &value, int64_t num) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, num, "LREM %s %d %s", key.c_str(), count, value.c_str()); } -bool xRedisClient::lset(const RedisDBIdx& dbi, const std::string& key, int32_t index, const std::string& value){ - if (0==key.length()) { +bool xRedisClient::lset(const RedisDBIdx &dbi, const std::string &key, int32_t index, const std::string &value) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_status(dbi, "LSET %s %d %s", key.c_str(), index, value.c_str()); } -bool xRedisClient::ltrim(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t end){ - if (0==key.length()) { +bool xRedisClient::ltrim(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_status(dbi, "LTRIM %s %d %d", key.c_str(), start, end); } -bool xRedisClient::rpop(const RedisDBIdx& dbi, const std::string& key, std::string& value){ - if (0==key.length()) { +bool xRedisClient::rpop(const RedisDBIdx &dbi, const std::string &key, std::string &value) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_string(dbi, value, "RPOP %s", key.c_str()); } -bool xRedisClient::rpoplpush(const RedisDBIdx& dbi, const std::string& key_src, const std::string& key_dest, std::string& value){ - if ((0 == key_src.length()) || (0==key_dest.length())) { +bool xRedisClient::rpoplpush(const RedisDBIdx &dbi, const std::string &key_src, const std::string &key_dest, std::string &value) +{ + if ((0 == key_src.length()) || (0 == key_dest.length())) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_string(dbi, value, "RPOPLPUSH %s %s", key_src.c_str(), key_dest.c_str()); } -bool xRedisClient::rpush(const RedisDBIdx& dbi, const std::string& key, const VALUES& vValue, int64_t& length){ - if (0==key.length()) { +bool xRedisClient::rpush(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &length) +{ + if (0 == key.length()) + { return false; } - VDATA vCmdData; + VDATA vCmdData; vCmdData.push_back("RPUSH"); vCmdData.push_back(key); addparam(vCmdData, vValue); @@ -143,11 +170,12 @@ bool xRedisClient::rpush(const RedisDBIdx& dbi, const std::string& key, const VA return commandargv_integer(dbi, vCmdData, length); } -bool xRedisClient::rpushx(const RedisDBIdx& dbi, const std::string& key, const std::string& value, int64_t& length){ - if (0==key.length()) { +bool xRedisClient::rpushx(const RedisDBIdx &dbi, const std::string &key, const std::string &value, int64_t &length) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, length, "RPUSHX %s %s", key.c_str(), value.c_str()); } - diff --git a/src/xRedisClient_pubsub.cpp b/src/xRedisClient_pubsub.cpp index 6210dff..9ebb397 100644 --- a/src/xRedisClient_pubsub.cpp +++ b/src/xRedisClient_pubsub.cpp @@ -11,7 +11,8 @@ #include using namespace xrc; -bool xRedisClient::psubscribe(const RedisDBIdx& dbi, const KEYS& patterns, xRedisContext& ctx) { +bool xRedisClient::psubscribe(const RedisDBIdx &dbi, const KEYS &patterns, xRedisContext &ctx) +{ SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; vCmdData.push_back("PSUBSCRIBE"); @@ -19,7 +20,8 @@ bool xRedisClient::psubscribe(const RedisDBIdx& dbi, const KEYS& patterns, xRedi return commandargv_array_ex(dbi, vCmdData, ctx); } -bool xRedisClient::publish(const RedisDBIdx& dbi, const KEY& channel, const std::string& message, int64_t& count) { +bool xRedisClient::publish(const RedisDBIdx &dbi, const KEY &channel, const std::string &message, int64_t &count) +{ //SETDEFAULTIOTYPE(MASTER); //return command_integer(dbi, count, "PUBLISH %s %s", channel.c_str(), message.c_str(), count); @@ -31,12 +33,14 @@ bool xRedisClient::publish(const RedisDBIdx& dbi, const KEY& channel, const std return commandargv_integer(dbi, vCmdData, count); } -bool xRedisClient::pubsub_channels(const RedisDBIdx& dbi, const std::string &pattern, ArrayReply &reply) { +bool xRedisClient::pubsub_channels(const RedisDBIdx &dbi, const std::string &pattern, ArrayReply &reply) +{ SETDEFAULTIOTYPE(MASTER); return command_array(dbi, reply, "pubsub channels %s", pattern.c_str()); } -bool xRedisClient::pubsub_numsub(const RedisDBIdx& dbi, const KEYS &keys, ArrayReply &reply) { +bool xRedisClient::pubsub_numsub(const RedisDBIdx &dbi, const KEYS &keys, ArrayReply &reply) +{ SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; vCmdData.push_back("pubsub"); @@ -45,12 +49,14 @@ bool xRedisClient::pubsub_numsub(const RedisDBIdx& dbi, const KEYS &keys, ArrayR return commandargv_array(dbi, vCmdData, reply); } -bool xRedisClient::pubsub_numpat(const RedisDBIdx& dbi, int64_t& count) { +bool xRedisClient::pubsub_numpat(const RedisDBIdx &dbi, int64_t &count) +{ SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, count, "pubsub numpat"); } -bool xRedisClient::punsubscribe(const RedisDBIdx& dbi, const KEYS& patterns, xRedisContext& ctx) { +bool xRedisClient::punsubscribe(const RedisDBIdx &dbi, const KEYS &patterns, xRedisContext &ctx) +{ SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; vCmdData.push_back("PUNSUBSCRIBE"); @@ -58,30 +64,35 @@ bool xRedisClient::punsubscribe(const RedisDBIdx& dbi, const KEYS& patterns, xRe bool bRet = false; RedisConn *pRedisConn = static_cast(ctx.conn); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } - std::vector argv(vCmdData.size()); + std::vector argv(vCmdData.size()); std::vector argvlen(vCmdData.size()); uint32_t j = 0; - for (VDATA::const_iterator i = vCmdData.begin(); i != vCmdData.end(); ++i, ++j) { + for (VDATA::const_iterator i = vCmdData.begin(); i != vCmdData.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { bRet = true; } - else { + else + { SetErrInfo(dbi, reply); } RedisPool::FreeReply(reply); return bRet; } -bool xRedisClient::subscribe(const RedisDBIdx& dbi, const KEYS& channels, xRedisContext& ctx) { +bool xRedisClient::subscribe(const RedisDBIdx &dbi, const KEYS &channels, xRedisContext &ctx) +{ SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; vCmdData.push_back("SUBSCRIBE"); @@ -89,7 +100,8 @@ bool xRedisClient::subscribe(const RedisDBIdx& dbi, const KEYS& channels, xRedis return commandargv_array_ex(dbi, vCmdData, ctx); } -bool xRedisClient::unsubscribe(const RedisDBIdx& dbi, const KEYS& channels, xRedisContext& ctx) { +bool xRedisClient::unsubscribe(const RedisDBIdx &dbi, const KEYS &channels, xRedisContext &ctx) +{ SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; vCmdData.push_back("UNSUBSCRIBE"); @@ -97,37 +109,29 @@ bool xRedisClient::unsubscribe(const RedisDBIdx& dbi, const KEYS& channels, xRed bool bRet = false; RedisConn *pRedisConn = static_cast(ctx.conn); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { SetErrString(dbi, GET_CONNECT_ERROR, ::strlen(GET_CONNECT_ERROR)); return false; } - std::vector argv(vCmdData.size()); + std::vector argv(vCmdData.size()); std::vector argvlen(vCmdData.size()); uint32_t j = 0; - for (VDATA::const_iterator i = vCmdData.begin(); i != vCmdData.end(); ++i, ++j) { + for (VDATA::const_iterator i = vCmdData.begin(); i != vCmdData.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->getCtx(), argv.size(), &(argv[0]), &(argvlen[0]))); - if (RedisPool::CheckReply(reply)) { + if (RedisPool::CheckReply(reply)) + { bRet = true; - } else { + } + else + { SetErrInfo(dbi, reply); } RedisPool::FreeReply(reply); return bRet; } - - - - - - - - - - - - - diff --git a/src/xRedisClient_sets.cpp b/src/xRedisClient_sets.cpp index 18f8050..3ab5d1f 100644 --- a/src/xRedisClient_sets.cpp +++ b/src/xRedisClient_sets.cpp @@ -9,7 +9,8 @@ #include "xRedisClient.h" using namespace xrc; -bool xRedisClient::sadd(const RedisDBIdx& dbi, const std::string& key, const VALUES& vValue, int64_t& count){ +bool xRedisClient::sadd(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &count) +{ VDATA vCmdData; vCmdData.push_back("SADD"); vCmdData.push_back(key); @@ -18,130 +19,158 @@ bool xRedisClient::sadd(const RedisDBIdx& dbi, const std::string& key, const return commandargv_integer(dbi, vCmdData, count); } -bool xRedisClient::scard(const RedisDBIdx& dbi, const std::string& key, int64_t& count){ - if (0==key.length()) { +bool xRedisClient::scard(const RedisDBIdx &dbi, const std::string &key, int64_t &count) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); return command_integer(dbi, count, "SCARD %s", key.c_str()); } -bool xRedisClient::sdiff(const DBIArray& vdbi, const KEYS& vkey, VALUES& sValue){ - size_t size = vkey.size(); - if (0 == size) { +bool xRedisClient::sdiff(const DBIArray &vdbi, const KEYS &vkey, VALUES &sValue) +{ + size_t size = vkey.size(); + if (0 == size) + { return false; } VALUES *setData = new VALUES[size]; VALUES::iterator endpos; DBIArray::const_iterator iter_dbi = vdbi.begin(); - KEYS::const_iterator iter_key = vkey.begin(); - int32_t i=0; - for (; iter_key!=vkey.end(); ++iter_key, ++iter_dbi, ++i) { + KEYS::const_iterator iter_key = vkey.begin(); + int32_t i = 0; + for (; iter_key != vkey.end(); ++iter_key, ++iter_dbi, ++i) + { const std::string &key = *iter_key; const RedisDBIdx &dbi = *iter_dbi; - if (!smembers(dbi, key, setData[i])) { - delete [] setData; + if (!smembers(dbi, key, setData[i])) + { + delete[] setData; return false; } } - size_t n=0; - while(n++ using namespace xrc; -bool xRedisClient::zadd(const RedisDBIdx& dbi, const KEY& key, const VALUES& vValues, int64_t& count){ +bool xRedisClient::zadd(const RedisDBIdx &dbi, const KEY &key, const VALUES &vValues, int64_t &count) +{ VDATA vCmdData; vCmdData.push_back("ZADD"); vCmdData.push_back(key); @@ -19,36 +20,45 @@ bool xRedisClient::zadd(const RedisDBIdx& dbi, const KEY& key, const VALUES& v return commandargv_integer(dbi, vCmdData, count); } -bool xRedisClient::zscrad(const RedisDBIdx& dbi, const std::string& key, int64_t& count){ - if (0==key.length()) { +bool xRedisClient::zscrad(const RedisDBIdx &dbi, const std::string &key, int64_t &count) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); return command_integer(dbi, count, "ZSCRAD %s", key.c_str()); } -bool xRedisClient::zincrby(const RedisDBIdx& dbi, const std::string& key, const double &increment, const std::string& member, std::string& value) { - if (0==key.length()) { +bool xRedisClient::zincrby(const RedisDBIdx &dbi, const std::string &key, const double &increment, const std::string &member, std::string &value) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_string(dbi, value, "ZINCRBY %s %f %s", key.c_str(), increment, member.c_str()); } -bool xRedisClient::zrange(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t end, VALUES& vValues, bool withscore) { - if (0==key.length()) { +bool xRedisClient::zrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, VALUES &vValues, bool withscore) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); - if (withscore) { + if (withscore) + { return command_list(dbi, vValues, "ZRANGE %s %d %d %s", key.c_str(), start, end, "WITHSCORES"); } return command_list(dbi, vValues, "ZRANGE %s %d %d", key.c_str(), start, end); } -bool xRedisClient::zrangebyscore(const RedisDBIdx& dbi, const std::string& key, const std::string& min, - const std::string& max, VALUES& vValues, bool withscore, LIMIT *limit /*= NULL*/) { - if (0==key.length()) { +bool xRedisClient::zrangebyscore(const RedisDBIdx &dbi, const std::string &key, const std::string &min, + const std::string &max, VALUES &vValues, bool withscore, LIMIT *limit /*= NULL*/) +{ + if (0 == key.length()) + { return false; } @@ -58,11 +68,13 @@ bool xRedisClient::zrangebyscore(const RedisDBIdx& dbi, const std::string& key, vCmdData.push_back(min); vCmdData.push_back(max); - if (withscore) { - vCmdData.push_back("WITHSCORES"); + if (withscore) + { + vCmdData.push_back("WITHSCORES"); } - if (NULL != limit) { + if (NULL != limit) + { vCmdData.push_back("LIMIT"); vCmdData.push_back(toString(limit->offset)); vCmdData.push_back(toString(limit->count)); @@ -72,15 +84,18 @@ bool xRedisClient::zrangebyscore(const RedisDBIdx& dbi, const std::string& key, return commandargv_array(dbi, vCmdData, vValues); } -bool xRedisClient::zrank(const RedisDBIdx& dbi, const std::string& key, const std::string& member, int64_t &rank) { - if (0==key.length()) { +bool xRedisClient::zrank(const RedisDBIdx &dbi, const std::string &key, const std::string &member, int64_t &rank) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, rank, "ZRANK %s %s", key.c_str(), member.c_str()); } -bool xRedisClient::zrem(const RedisDBIdx& dbi, const KEY& key, const VALUES& vmembers, int64_t &count) { +bool xRedisClient::zrem(const RedisDBIdx &dbi, const KEY &key, const VALUES &vmembers, int64_t &count) +{ VDATA vCmdData; vCmdData.push_back("ZREM"); vCmdData.push_back(key); @@ -89,52 +104,61 @@ bool xRedisClient::zrem(const RedisDBIdx& dbi, const KEY& key, const VALU return commandargv_integer(dbi, vCmdData, count); } -bool xRedisClient::zremrangebyrank(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t stop, int64_t& count) { - if (0==key.length()) { +bool xRedisClient::zremrangebyrank(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t stop, int64_t &count) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, count, "ZREMRANGEBYRANK %s %d %d", key.c_str(), start, stop); } -bool xRedisClient::zremrangebyscore(const RedisDBIdx& dbi, const KEY& key, double min, double max, int64_t& count){ - if (0==key.length()) { +bool xRedisClient::zremrangebyscore(const RedisDBIdx &dbi, const KEY &key, double min, double max, int64_t &count) +{ + if (0 == key.length()) + { return false; } SETDEFAULTIOTYPE(SLAVE); return command_integer(dbi, count, "ZREMRANGEBYSCORE %s %d %d", key.c_str(), min, max); } -bool xRedisClient::zrevrange(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t end, VALUES& vValues, bool withscore) { - if (0==key.length()) { +bool xRedisClient::zrevrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, VALUES &vValues, bool withscore) +{ + if (0 == key.length()) + { return false; } - if (withscore) { + if (withscore) + { return command_list(dbi, vValues, "ZREVRANGE %s %d %d %s", key.c_str(), start, end, "WITHSCORES"); } return command_list(dbi, vValues, "ZREVRANGE %s %d %d", key.c_str(), start, end); } -bool xRedisClient::zrevrank(const RedisDBIdx& dbi, const std::string& key, const std::string &member, int64_t& rank){ - if (0==key.length()) { - return false; - } - SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, rank, "ZREVRANK %s %s", key.c_str(), member.c_str()); - } - - bool xRedisClient::zscan(const RedisDBIdx& dbi, const std::string& key, int64_t &cursor, const char *pattern, - uint32_t count, ArrayReply& array, xRedisContext& ctx) - { - return ScanFun("ZSCAN", dbi, &key, cursor, pattern, count, array, ctx); - } - - bool xRedisClient::zscore(const RedisDBIdx& dbi, const std::string& key, const std::string &member, std::string& score){ - if (0==key.length()) { - return false; - } - SETDEFAULTIOTYPE(SLAVE); - return command_string(dbi, score, "ZSCORE %s %s", key.c_str(), member.c_str()); - } +bool xRedisClient::zrevrank(const RedisDBIdx &dbi, const std::string &key, const std::string &member, int64_t &rank) +{ + if (0 == key.length()) + { + return false; + } + SETDEFAULTIOTYPE(SLAVE); + return command_integer(dbi, rank, "ZREVRANK %s %s", key.c_str(), member.c_str()); +} +bool xRedisClient::zscan(const RedisDBIdx &dbi, const std::string &key, int64_t &cursor, const char *pattern, + uint32_t count, ArrayReply &array, xRedisContext &ctx) +{ + return ScanFun("ZSCAN", dbi, &key, cursor, pattern, count, array, ctx); +} +bool xRedisClient::zscore(const RedisDBIdx &dbi, const std::string &key, const std::string &member, std::string &score) +{ + if (0 == key.length()) + { + return false; + } + SETDEFAULTIOTYPE(SLAVE); + return command_string(dbi, score, "ZSCORE %s %s", key.c_str(), member.c_str()); +} diff --git a/src/xRedisClient_strings.cpp b/src/xRedisClient_strings.cpp index f5f93f8..3c9b024 100644 --- a/src/xRedisClient_strings.cpp +++ b/src/xRedisClient_strings.cpp @@ -6,18 +6,20 @@ * ---------------------------------------------------------------------------- */ -#include "hiredis.h" +#include #include "xRedisClient.h" #include "xRedisPool.h" #include using namespace xrc; -bool xRedisClient::psetex(const RedisDBIdx& dbi, const std::string& key, int32_t milliseconds, const std::string& value) { +bool xRedisClient::psetex(const RedisDBIdx &dbi, const std::string &key, int32_t milliseconds, const std::string &value) +{ SETDEFAULTIOTYPE(MASTER); return command_bool(dbi, "PSETEX %s %d %s", key.c_str(), milliseconds, value.c_str()); } -bool xRedisClient::append(const RedisDBIdx& dbi, const std::string& key, const std::string& value) { +bool xRedisClient::append(const RedisDBIdx &dbi, const std::string &key, const std::string &value) +{ VDATA vCmdData; vCmdData.push_back("APPEND"); vCmdData.push_back(key); @@ -26,7 +28,8 @@ bool xRedisClient::append(const RedisDBIdx& dbi, const std::string& key, const s return commandargv_status(dbi, vCmdData); } -bool xRedisClient::set(const RedisDBIdx& dbi, const std::string& key, const std::string& value) { +bool xRedisClient::set(const RedisDBIdx &dbi, const std::string &key, const std::string &value) +{ VDATA vCmdData; vCmdData.push_back("SET"); vCmdData.push_back(key); @@ -35,8 +38,9 @@ bool xRedisClient::set(const RedisDBIdx& dbi, const std::string& key, const std: return commandargv_status(dbi, vCmdData); } -bool xRedisClient::set(const RedisDBIdx& dbi, const std::string& key, const std::string& value, SETPXEX pxex, int32_t expiretime, SETNXXX nxxx) { - static const char* pXflag[]={"px","ex","nx","xx"}; +bool xRedisClient::set(const RedisDBIdx &dbi, const std::string &key, const std::string &value, SETPXEX pxex, int32_t expiretime, SETNXXX nxxx) +{ + static const char *pXflag[] = {"px", "ex", "nx", "xx"}; SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; @@ -44,38 +48,47 @@ bool xRedisClient::set(const RedisDBIdx& dbi, const std::string& key, const std: vCmdData.push_back(key); vCmdData.push_back(value); - if (pxex>0) { + if (pxex > 0) + { vCmdData.push_back((pxex == PX) ? pXflag[0] : pXflag[1]); vCmdData.push_back(toString(expiretime)); } - if (nxxx>0){ + if (nxxx > 0) + { vCmdData.push_back((nxxx == NX) ? pXflag[2] : pXflag[3]); } return commandargv_status(dbi, vCmdData); } -bool xRedisClient::set(const RedisDBIdx& dbi, const std::string& key, const char *value, int32_t len, int32_t second) { +bool xRedisClient::set(const RedisDBIdx &dbi, const std::string &key, const char *value, int32_t len, int32_t second) +{ SETDEFAULTIOTYPE(MASTER); - if (0==second) { + if (0 == second) + { return command_bool(dbi, "set %s %b", key.c_str(), value, len); - } else { + } + else + { return command_bool(dbi, "set %s %b EX %d", key.c_str(), value, len, second); } } -bool xRedisClient::setbit(const RedisDBIdx& dbi, const std::string& key, int32_t offset, int64_t newbitValue, int64_t oldbitValue) { +bool xRedisClient::setbit(const RedisDBIdx &dbi, const std::string &key, int32_t offset, int64_t newbitValue, int64_t oldbitValue) +{ SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, oldbitValue, "SETBIT %s %d %lld", key.c_str(), offset, newbitValue); } -bool xRedisClient::get(const RedisDBIdx& dbi, const std::string& key, std::string& value) { +bool xRedisClient::get(const RedisDBIdx &dbi, const std::string &key, std::string &value) +{ SETDEFAULTIOTYPE(SLAVE); return command_string(dbi, value, "GET %s", key.c_str()); } -bool xRedisClient::getbit(const RedisDBIdx& dbi, const std::string& key, int32_t& offset, int32_t& bit) { +bool xRedisClient::getbit(const RedisDBIdx &dbi, const std::string &key, int32_t &offset, int32_t &bit) +{ SETDEFAULTIOTYPE(SLAVE); int64_t intval = 0; bool bRet = command_integer(dbi, intval, "GETBIT %s %d", key.c_str(), offset); @@ -83,36 +96,45 @@ bool xRedisClient::getbit(const RedisDBIdx& dbi, const std::string& key, int32_t return bRet; } -bool xRedisClient::getrange(const RedisDBIdx& dbi, const std::string& key, int32_t start, int32_t end, std::string& out) { +bool xRedisClient::getrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, std::string &out) +{ SETDEFAULTIOTYPE(SLAVE); return command_string(dbi, out, "GETRANGE %s %d %d", key.c_str(), start, end); } -bool xRedisClient::getset(const RedisDBIdx& dbi, const std::string& key, const std::string& newValue, std::string& oldValue) { +bool xRedisClient::getset(const RedisDBIdx &dbi, const std::string &key, const std::string &newValue, std::string &oldValue) +{ SETDEFAULTIOTYPE(MASTER); return command_string(dbi, oldValue, "GETSET %s %s", key.c_str(), newValue.c_str()); } -bool xRedisClient::mget(const DBIArray &vdbi, const KEYS & keys, ReplyData& vDdata) { +bool xRedisClient::mget(const DBIArray &vdbi, const KEYS &keys, ReplyData &vDdata) +{ bool bRet = false; size_t n = vdbi.size(); - if (n!=keys.size()) { + if (n != keys.size()) + { return bRet; } DataItem item; DBIArray::const_iterator iter_dbi = vdbi.begin(); KEYS::const_iterator iter_key = keys.begin(); - for (;iter_key!=keys.end();++iter_key, ++iter_dbi) { - const RedisDBIdx& dbi = *iter_dbi; + for (; iter_key != keys.end(); ++iter_key, ++iter_dbi) + { + const RedisDBIdx &dbi = *iter_dbi; SETDEFAULTIOTYPE(SLAVE); const std::string &key = *iter_key; - if (key.length()>0) { + if (key.length() > 0) + { bool ret = command_string(*iter_dbi, item.str, "GET %s", key.c_str()); - if (!ret) { + if (!ret) + { item.type = REDIS_REPLY_NIL; - item.str = ""; - } else { + item.str = ""; + } + else + { item.type = REDIS_REPLY_STRING; bRet = true; } @@ -122,20 +144,23 @@ bool xRedisClient::mget(const DBIArray &vdbi, const KEYS & keys, ReplyData& v return bRet; } -bool xRedisClient::mset(const DBIArray& vdbi, const VDATA& vData) { +bool xRedisClient::mset(const DBIArray &vdbi, const VDATA &vData) +{ DBIArray::const_iterator iter_dbi = vdbi.begin(); VDATA::const_iterator iter_data = vData.begin(); - for (; iter_data != vData.end(); iter_dbi++) { + for (; iter_data != vData.end(); iter_dbi++) + { const std::string &key = (*iter_data++); const std::string &value = (*iter_data++); - const RedisDBIdx& dbi = *iter_dbi; + const RedisDBIdx &dbi = *iter_dbi; SETDEFAULTIOTYPE(SLAVE); command_status(dbi, "SET %s %s", key.c_str(), value.c_str()); } return true; } -bool xRedisClient::setex(const RedisDBIdx& dbi, const std::string& key, int32_t seconds, const std::string& value) { +bool xRedisClient::setex(const RedisDBIdx &dbi, const std::string &key, int32_t seconds, const std::string &value) +{ VDATA vCmdData; vCmdData.push_back("SETEX"); @@ -146,7 +171,8 @@ bool xRedisClient::setex(const RedisDBIdx& dbi, const std::string& key, int32_t return commandargv_status(dbi, vCmdData); } -bool xRedisClient::setnx(const RedisDBIdx& dbi, const std::string& key, const std::string& value) { +bool xRedisClient::setnx(const RedisDBIdx &dbi, const std::string &key, const std::string &value) +{ VDATA vCmdData; vCmdData.push_back("SETNX"); vCmdData.push_back(key); @@ -155,7 +181,8 @@ bool xRedisClient::setnx(const RedisDBIdx& dbi, const std::string& key, const st return commandargv_bool(dbi, vCmdData); } -bool xRedisClient::setrange(const RedisDBIdx& dbi, const std::string& key, int32_t offset, const std::string& value, int32_t& length) { +bool xRedisClient::setrange(const RedisDBIdx &dbi, const std::string &key, int32_t offset, const std::string &value, int32_t &length) +{ int64_t intval = 0; SETDEFAULTIOTYPE(MASTER); bool bRet = command_integer(dbi, intval, "setrange %s %d %s", key.c_str(), offset, value.c_str()); @@ -163,7 +190,8 @@ bool xRedisClient::setrange(const RedisDBIdx& dbi, const std::string& key, int32 return bRet; } -bool xRedisClient::strlen(const RedisDBIdx& dbi, const std::string& key, int32_t& length) { +bool xRedisClient::strlen(const RedisDBIdx &dbi, const std::string &key, int32_t &length) +{ int64_t intval = 0; SETDEFAULTIOTYPE(SLAVE); bool bRet = command_integer(dbi, intval, "STRLEN %s", key.c_str()); @@ -171,24 +199,30 @@ bool xRedisClient::strlen(const RedisDBIdx& dbi, const std::string& key, int32_t return bRet; } -bool xRedisClient::incr(const RedisDBIdx& dbi, const std::string& key, int64_t& result) { +bool xRedisClient::incr(const RedisDBIdx &dbi, const std::string &key, int64_t &result) +{ SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, result, "INCR %s", key.c_str()); } -bool xRedisClient::incrby(const RedisDBIdx& dbi, const std::string& key, int32_t by, int64_t& result) { +bool xRedisClient::incrby(const RedisDBIdx &dbi, const std::string &key, int32_t by, int64_t &result) +{ SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, result, "INCRBY %s %d", key.c_str(), by); } -bool xRedisClient::bitcount(const RedisDBIdx& dbi, const std::string& key, int32_t& count, int32_t start, int32_t end) { +bool xRedisClient::bitcount(const RedisDBIdx &dbi, const std::string &key, int32_t &count, int32_t start, int32_t end) +{ int64_t intval = 0; bool bRet = false; SETDEFAULTIOTYPE(SLAVE); - if ( (start!=0)||(end!=0) ) { + if ((start != 0) || (end != 0)) + { bRet = command_integer(dbi, intval, "bitcount %s %d %d", key.c_str(), start, end); - } else { - bRet = command_integer(dbi, intval, "bitcount %s", key.c_str()); + } + else + { + bRet = command_integer(dbi, intval, "bitcount %s", key.c_str()); } count = (int32_t)intval; return bRet; @@ -209,38 +243,24 @@ bool xRedisClient::bitcount(const RedisDBIdx& dbi, const std::string& key, int32 // return bRet; //} -bool xRedisClient::bitpos(const RedisDBIdx& dbi, const std::string& key, int32_t bit, int64_t& pos, int32_t start, int32_t end) { +bool xRedisClient::bitpos(const RedisDBIdx &dbi, const std::string &key, int32_t bit, int64_t &pos, int32_t start, int32_t end) +{ SETDEFAULTIOTYPE(SLAVE); - if ( (start!=0)||(end!=0) ) { + if ((start != 0) || (end != 0)) + { return command_integer(dbi, pos, "BITPOS %s %d %d %d", key.c_str(), bit, start, end); } return command_integer(dbi, pos, "BITPOS %s %d", key.c_str(), bit); } -bool xRedisClient::decr(const RedisDBIdx& dbi, const std::string& key, int64_t& result) { +bool xRedisClient::decr(const RedisDBIdx &dbi, const std::string &key, int64_t &result) +{ SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi,result,"decr %s", key.c_str()); + return command_integer(dbi, result, "decr %s", key.c_str()); } -bool xRedisClient::decrby(const RedisDBIdx& dbi, const std::string& key, int32_t by, int64_t& result) { +bool xRedisClient::decrby(const RedisDBIdx &dbi, const std::string &key, int32_t by, int64_t &result) +{ SETDEFAULTIOTYPE(MASTER); return command_integer(dbi, result, "decrby %s %d", key.c_str(), by); } - - - - - - - - - - - - - - - - - - diff --git a/src/xRedisClusterClient.cpp b/src/xRedisClusterClient.cpp index 933267a..e741d32 100644 --- a/src/xRedisClusterClient.cpp +++ b/src/xRedisClusterClient.cpp @@ -2,74 +2,84 @@ using namespace xrc; -static const uint16_t crc16tab[256]= { - 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7, - 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef, - 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6, - 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de, - 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485, - 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d, - 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4, - 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc, - 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823, - 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b, - 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12, - 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a, - 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41, - 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49, - 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70, - 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78, - 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f, - 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067, - 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e, - 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256, - 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d, - 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405, - 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c, - 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634, - 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab, - 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3, - 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a, - 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92, - 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9, - 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1, - 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8, - 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0 -}; - - uint16_t xRedisClusterClient::crc16(const char *buf, int32_t len) { +static const uint16_t crc16tab[256] = { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0}; + +uint16_t xRedisClusterClient::crc16(const char *buf, int32_t len) +{ int32_t counter; uint16_t crc = 0; for (counter = 0; counter < len; counter++) - crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *buf++)&0x00FF]; + crc = (crc << 8) ^ crc16tab[((crc >> 8) ^ *buf++) & 0x00FF]; return crc; } - bool xRedisClusterClient::CheckReply(const redisReply *reply){ - if (NULL == reply) { +bool xRedisClusterClient::CheckReply(const redisReply *reply) +{ + if (NULL == reply) + { return false; } - switch (reply->type){ - case REDIS_REPLY_STRING:{ + switch (reply->type) + { + case REDIS_REPLY_STRING: + { return true; } - case REDIS_REPLY_ARRAY:{ + case REDIS_REPLY_ARRAY: + { return true; } - case REDIS_REPLY_INTEGER:{ + case REDIS_REPLY_INTEGER: + { return true; } - case REDIS_REPLY_NIL:{ + case REDIS_REPLY_NIL: + { return false; } - case REDIS_REPLY_STATUS:{ + case REDIS_REPLY_STATUS: + { return true; } - case REDIS_REPLY_ERROR:{ + case REDIS_REPLY_ERROR: + { return false; } - default:{ + default: + { return false; } } @@ -77,24 +87,30 @@ static const uint16_t crc16tab[256]= { return false; } -void xRedisClusterClient::FreeReply(const redisReply *reply){ - if (NULL != reply) { - freeReplyObject((void*)reply); +void xRedisClusterClient::FreeReply(const redisReply *reply) +{ + if (NULL != reply) + { + freeReplyObject((void *)reply); } } -int32_t xRedisClusterClient::Str2Vect(const char* pSrc, std::vector &vDest, const char *pSep) { - if (NULL == pSrc) { +int32_t xRedisClusterClient::Str2Vect(const char *pSrc, std::vector &vDest, const char *pSep) +{ + if (NULL == pSrc) + { return -1; } int32_t iLen = strlen(pSrc); - if (iLen == 0) { + if (iLen == 0) + { return -1; } char *pTmp = new char[iLen + 1]; - if (pTmp == NULL) { + if (pTmp == NULL) + { return -1; } @@ -102,7 +118,8 @@ int32_t xRedisClusterClient::Str2Vect(const char* pSrc, std::vector pTmp[iLen] = '\0'; char *pCurr = strtok(pTmp, pSep); - while (pCurr) { + while (pCurr) + { vDest.push_back(pCurr); pCurr = strtok(NULL, pSep); } @@ -118,7 +135,7 @@ xRedisClusterClient::xRedisClusterClient() mClusterEnabled = false; mPoolSize = 4; } - + xRedisClusterClient::~xRedisClusterClient() { Release(); @@ -127,9 +144,11 @@ xRedisClusterClient::~xRedisClusterClient() bool xRedisClusterClient::GetClusterNodes(redisContext *redis_ctx) { std::vector vlines; - redisReply *redis_reply = (redisReply*)redisCommand(redis_ctx, "CLUSTER NODES"); - if ((NULL == redis_reply) || (NULL == redis_reply->str)) { - if (redis_reply) { + redisReply *redis_reply = (redisReply *)redisCommand(redis_ctx, "CLUSTER NODES"); + if ((NULL == redis_reply) || (NULL == redis_reply->str)) + { + if (redis_reply) + { freeReplyObject(redis_reply); } redisFree(redis_ctx); @@ -139,16 +158,19 @@ bool xRedisClusterClient::GetClusterNodes(redisContext *redis_ctx) Str2Vect(redis_reply->str, vlines, "\n"); printf("vlines:%lu\r\n", vlines.size()); - for (size_t i = 0; i < vlines.size(); ++i) { + for (size_t i = 0; i < vlines.size(); ++i) + { NodeInfo node; node.strinfo = vlines[i]; std::vector nodeinfo; Str2Vect(node.strinfo.c_str(), nodeinfo, " "); - for (size_t k = 0; k < nodeinfo.size(); ++k) { + for (size_t k = 0; k < nodeinfo.size(); ++k) + { printf("%lu : %s \r\n", k, nodeinfo[k].c_str()); } - if (NULL == strstr(nodeinfo[2].c_str(), "master")) { + if (NULL == strstr(nodeinfo[2].c_str(), "master")) + { printf("%s \r\n", nodeinfo[2].c_str()); continue; } @@ -172,38 +194,42 @@ void xRedisClusterClient::Keepalive() //} size_t node_count = vNodes.size(); - for (size_t i = 0; i < node_count; ++i) { + for (size_t i = 0; i < node_count; ++i) + { XLOCK(mLock[i]); RedisConnectionList *pList = &mRedisConnList[i]; RedisConnectionIter iter = pList->begin(); - for (; iter != pList->end(); iter++) { + for (; iter != pList->end(); iter++) + { RedisConnection *pConn = *iter; redisReply *reply = static_cast(redisCommand(pConn->mCtx, "PING")); bool bRet = (NULL != reply); - if (bRet) { + if (bRet) + { freeReplyObject(reply); } } } - } void xRedisClusterClient::Release() { //XLOCK(mLock); size_t node_count = vNodes.size(); - for (size_t i = 0; i < node_count; ++i) { + for (size_t i = 0; i < node_count; ++i) + { RedisConnectionList *pList = &mRedisConnList[i]; RedisConnectionIter iter = pList->begin(); - for (; iter != pList->end(); iter++) { + for (; iter != pList->end(); iter++) + { redisFree((*iter)->mCtx); delete *iter; } } vNodes.clear(); - delete [] mRedisConnList; + delete[] mRedisConnList; mRedisConnList = NULL; - delete [] mLock; + delete[] mLock; mLock = NULL; } @@ -216,11 +242,12 @@ void xRedisClusterClient::Release() bool xRedisClusterClient::CheckReply(redisReply *reply) { - if(NULL==reply) { - printf("error, reply is NULL \r\n"); - return false; + if (NULL == reply) + { + printf("error, reply is NULL \r\n"); + return false; } - + printf("DEBBUG %d:%s \r\n", reply->type, reply->str); return true; @@ -228,9 +255,11 @@ bool xRedisClusterClient::CheckReply(redisReply *reply) bool xRedisClusterClient::ClusterEnabled(redisContext *ctx) { - redisReply *redis_reply = (redisReply*)redisCommand(ctx, "info"); - if ((NULL == redis_reply) || (NULL == redis_reply->str)) { - if (redis_reply) { + redisReply *redis_reply = (redisReply *)redisCommand(ctx, "info"); + if ((NULL == redis_reply) || (NULL == redis_reply->str)) + { + if (redis_reply) + { freeReplyObject(redis_reply); } return false; @@ -245,22 +274,24 @@ bool xRedisClusterClient::ClusterEnabled(redisContext *ctx) bool xRedisClusterClient::ClusterInfo(redisContext *ctx) { - redisReply *redis_reply = (redisReply*)redisCommand(ctx, "CLUSTER info"); - if( (NULL==redis_reply) ||(NULL==redis_reply->str)) { - if(redis_reply) { + redisReply *redis_reply = (redisReply *)redisCommand(ctx, "CLUSTER info"); + if ((NULL == redis_reply) || (NULL == redis_reply->str)) + { + if (redis_reply) + { freeReplyObject(redis_reply); } return false; } //printf("Clusterinfo:\r\n%s\r\n", redis_reply->str); char *p = strstr(redis_reply->str, ":"); - bool bRet = (0 == strncmp(p+1, "ok", 2)); + bool bRet = (0 == strncmp(p + 1, "ok", 2)); freeReplyObject(redis_reply); return bRet; } bool xRedisClusterClient::ReConnectRedis(RedisConnection *pConn) -{ +{ Release(); return ConnectRedis(pConn->mHost, pConn->mPort, pConn->mPoolSize); @@ -268,7 +299,8 @@ bool xRedisClusterClient::ReConnectRedis(RedisConnection *pConn) bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t poolsize) { - if (NULL == host) { + if (NULL == host) + { printf("error argv \r\n"); return false; } @@ -279,59 +311,73 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t mPoolSize = poolsize; redisContext *redis_ctx = redisConnectWithTimeout(host, port, timeoutVal); - if (redis_ctx == NULL || redis_ctx->err) { - if (redis_ctx) { + if (redis_ctx == NULL || redis_ctx->err) + { + if (redis_ctx) + { printf("Connection error: %s \r\n", redis_ctx->errstr); redisFree(redis_ctx); return false; - } else { + } + else + { printf("Connection error: can't allocate redis context, %s \n", redis_ctx->errstr); } - } else { + } + else + { printf("Connect to Redis: %s:%d success \n", host, port); } mClusterEnabled = ClusterEnabled(redis_ctx); printf("ClusterEnabled %d \r\n", mClusterEnabled); - if (!mClusterEnabled) { + if (!mClusterEnabled) + { mRedisConnList = new RedisConnectionList[1]; ConnectRedisNode(0, host, port, mPoolSize); return true; } - if(!ClusterInfo(redis_ctx)) { + if (!ClusterInfo(redis_ctx)) + { printf("ClusterInfo error \r\n"); return false; } - + std::vector vlines; - redisReply *redis_reply = (redisReply*)redisCommand(redis_ctx, "CLUSTER NODES"); - if( (NULL==redis_reply) ||(NULL==redis_reply->str)) { - if(redis_reply) { + redisReply *redis_reply = (redisReply *)redisCommand(redis_ctx, "CLUSTER NODES"); + if ((NULL == redis_reply) || (NULL == redis_reply->str)) + { + if (redis_reply) + { freeReplyObject(redis_reply); } redisFree(redis_ctx); return false; } - + Str2Vect(redis_reply->str, vlines, "\n"); printf("vlines:%lu\r\n", vlines.size()); - - for (size_t i= 0; i < vlines.size(); ++i) { + + for (size_t i = 0; i < vlines.size(); ++i) + { NodeInfo node; node.strinfo = vlines[i]; std::vector nodeinfo; Str2Vect(node.strinfo.c_str(), nodeinfo, " "); - for (size_t k = 0; k < nodeinfo.size(); ++k) { + for (size_t k = 0; k < nodeinfo.size(); ++k) + { printf("%lu : %s \r\n", k, nodeinfo[k].c_str()); } - if (NULL != strstr(nodeinfo[7].c_str(), "disconnected")){ + if (NULL != strstr(nodeinfo[7].c_str(), "disconnected")) + { //printf("%s \r\n", nodeinfo[7].c_str()); continue; } - if (NULL == strstr(nodeinfo[2].c_str(), "master")) { + if (NULL == strstr(nodeinfo[2].c_str(), "master")) + { printf("%s \r\n", nodeinfo[2].c_str()); continue; } @@ -345,11 +391,12 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t freeReplyObject(redis_reply); redisFree(redis_ctx); -// XLOCK(mLock); + // XLOCK(mLock); int32_t cnt = vNodes.size(); mRedisConnList = new RedisConnectionList[cnt]; mLock = new xLock[cnt]; - for (int32_t i = 0; i < cnt; ++i) { + for (int32_t i = 0; i < cnt; ++i) + { ConnectRedisNode(i, vNodes[i].ip.c_str(), vNodes[i].port, mPoolSize); } @@ -358,44 +405,52 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t bool xRedisClusterClient::ConnectRedisNode(int32_t idx, const char *host, uint32_t port, uint32_t poolsize) { - if(NULL==host) { + if (NULL == host) + { printf("error argv \r\n"); return false; } - + //同时打开 CONNECTION_NUM 个连接 - poolsize = poolsize>MAX_REDIS_POOLSIZE?MAX_REDIS_POOLSIZE:poolsize; + poolsize = poolsize > MAX_REDIS_POOLSIZE ? MAX_REDIS_POOLSIZE : poolsize; + + for (uint32_t i = 0; i < poolsize; ++i) + { + struct timeval timeoutVal; + timeoutVal.tv_sec = MAX_TIME_OUT; + timeoutVal.tv_usec = 0; - for (uint32_t i = 0; i < poolsize; ++i) + RedisConnection *pRedisconn = new RedisConnection; + if (NULL == pRedisconn) + { + printf("error pRedisconn is null, %s %d \r\n", host, port); + continue; + } + pRedisconn->mHost = host; + pRedisconn->mPort = port; + pRedisconn->mPoolSize = poolsize; + pRedisconn->mIndex = idx; + pRedisconn->mCtx = redisConnectWithTimeout(host, port, timeoutVal); + if (pRedisconn->mCtx == NULL || pRedisconn->mCtx->err) { - struct timeval timeoutVal; - timeoutVal.tv_sec = MAX_TIME_OUT; - timeoutVal.tv_usec = 0; - - RedisConnection *pRedisconn = new RedisConnection; - if(NULL==pRedisconn) { - printf("error pRedisconn is null, %s %d \r\n", host, port); - continue; + if (pRedisconn->mCtx) + { + printf("Connection error: %s \r\n", pRedisconn->mCtx->errstr); + redisFree(pRedisconn->mCtx); } - pRedisconn->mHost = host; - pRedisconn->mPort = port; - pRedisconn->mPoolSize = poolsize; - pRedisconn->mIndex = idx; - pRedisconn->mCtx = redisConnectWithTimeout(host, port, timeoutVal); - if (pRedisconn->mCtx == NULL || pRedisconn->mCtx->err) { - if (pRedisconn->mCtx) { - printf("Connection error: %s \r\n", pRedisconn->mCtx->errstr); - redisFree(pRedisconn->mCtx); - } else { - printf("Connection error: can't allocate redis context, %s \n", pRedisconn->mCtx->errstr); - } - delete pRedisconn; - } else { - printf("Connect to Redis[%u]: %s:%d poolsize:%d success \n", - idx, host, port, poolsize); - mRedisConnList[idx].push_back(pRedisconn); + else + { + printf("Connection error: can't allocate redis context, %s \n", pRedisconn->mCtx->errstr); } + delete pRedisconn; + } + else + { + printf("Connect to Redis[%u]: %s:%d poolsize:%d success \n", + idx, host, port, poolsize); + mRedisConnList[idx].push_back(pRedisconn); } + } return true; } @@ -404,13 +459,18 @@ RedisConnection *xRedisClusterClient::GetConnection(uint32_t idx) { RedisConnection *pRedisConn = NULL; - while (1) { { + while (1) + { + { XLOCK(mLock[idx]); - if (mRedisConnList[idx].size() > 0) { + if (mRedisConnList[idx].size() > 0) + { pRedisConn = mRedisConnList[idx].front(); mRedisConnList[idx].pop_front(); break; - } else { + } + else + { printf("RedisPool::GetConnection() error pthread_id=%lu \n", (unsigned long)pthread_self()); } @@ -434,21 +494,26 @@ void xRedisClusterClient::FreeConnection(RedisConnection *pRedisConn) * However if the key contains the {...} pattern, only the part between * { and } is hashed. This may be useful in the future to force certain * keys to be in the same node (assuming no resharding is in progress). */ -uint32_t xRedisClusterClient::KeyHashSlot(const char *key, size_t keylen) { +uint32_t xRedisClusterClient::KeyHashSlot(const char *key, size_t keylen) +{ size_t s, e; /* start-end indexes of { and } */ for (s = 0; s < keylen; s++) - if (key[s] == '{') break; + if (key[s] == '{') + break; /* No '{' ? Hash the whole key. This is the base case. */ - if (s == keylen) return crc16(key, keylen) & 0x3FFF; + if (s == keylen) + return crc16(key, keylen) & 0x3FFF; /* '{' found? Check if we have the corresponding '}'. */ for (e = s + 1; e < keylen; e++) - if (key[e] == '}') break; + if (key[e] == '}') + break; /* No '}' or nothing betweeen {} ? Hash the whole key. */ - if (e == keylen || e == s + 1) return crc16(key, keylen) & 0x3FFF; + if (e == keylen || e == s + 1) + return crc16(key, keylen) & 0x3FFF; /* If we are here there is both a { and a } on its right. Hash * what is in the middle between { and }. */ @@ -457,9 +522,11 @@ uint32_t xRedisClusterClient::KeyHashSlot(const char *key, size_t keylen) { uint32_t xRedisClusterClient::FindNodeIndex(uint32_t slot) { - for (size_t i = 0; i < vNodes.size(); ++i) { + for (size_t i = 0; i < vNodes.size(); ++i) + { NodeInfo *pNode = &vNodes[i]; - if (pNode->CheckSlot(slot)) { + if (pNode->CheckSlot(slot)) + { printf("FindNode %u:%lu\n", slot, i); return i; } @@ -467,9 +534,10 @@ uint32_t xRedisClusterClient::FindNodeIndex(uint32_t slot) return 0; } -uint32_t xRedisClusterClient::GetKeySlotIndex(const char* key) +uint32_t xRedisClusterClient::GetKeySlotIndex(const char *key) { - if (NULL != key) { + if (NULL != key) + { return KeyHashSlot(key, strlen(key)); } return 0; @@ -477,7 +545,8 @@ uint32_t xRedisClusterClient::GetKeySlotIndex(const char* key) RedisConnection *xRedisClusterClient::FindNodeConnection(const char *key) { - if (!mClusterEnabled) { + if (!mClusterEnabled) + { return GetConnection(0); } printf("key:%s \r\n", key); @@ -494,9 +563,10 @@ bool xRedisClusterClient::RedisCommand(RedisResult &result, const char *format, va_list args; va_start(args, format); - key = va_arg(args, char*); + key = va_arg(args, char *); printf("key:%p \n", key); - if(0==strlen(key)) { + if (0 == strlen(key)) + { printf("key is NULL key:%p \n", key); return false; } @@ -505,15 +575,18 @@ bool xRedisClusterClient::RedisCommand(RedisResult &result, const char *format, va_start(args, format); redisReply *reply = static_cast(redisvCommand(pRedisConn->mCtx, format, args)); va_end(args); - - if (CheckReply(reply)) { + + if (CheckReply(reply)) + { result.Init(reply); - printf("%d %lld %d %s %lu \r\n", - reply->type, reply->integer, reply->len, reply->str, reply->elements); + printf("%d %lld %d %s %lu \r\n", + reply->type, reply->integer, reply->len, reply->str, reply->elements); bRet = true; - } else { + } + else + { bRet = false; } @@ -521,34 +594,37 @@ bool xRedisClusterClient::RedisCommand(RedisResult &result, const char *format, return bRet; } -bool xRedisClusterClient::RedisCommandArgv(const VSTRING& vDataIn, RedisResult &result){ +bool xRedisClusterClient::RedisCommandArgv(const VSTRING &vDataIn, RedisResult &result) +{ bool bRet = false; const std::string &key = vDataIn[1]; RedisConnection *pRedisConn = FindNodeConnection(key.c_str()); - if (NULL == pRedisConn) { + if (NULL == pRedisConn) + { return false; } - std::vector argv(vDataIn.size()); + std::vector argv(vDataIn.size()); std::vector argvlen(vDataIn.size()); uint32_t j = 0; - for (VSTRING::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j) { + for (VSTRING::const_iterator i = vDataIn.begin(); i != vDataIn.end(); ++i, ++j) + { argv[j] = i->c_str(), argvlen[j] = i->size(); } redisReply *reply = static_cast(redisCommandArgv(pRedisConn->mCtx, argv.size(), &(argv[0]), &(argvlen[0]))); - if (xRedisClusterClient::CheckReply(reply)) { + if (xRedisClusterClient::CheckReply(reply)) + { result.Init(reply); printf("%d %lld %d %s %lu \r\n", - reply->type, reply->integer, reply->len, reply->str, reply->elements); + reply->type, reply->integer, reply->len, reply->str, reply->elements); bRet = true; - } else { + } + else + { //SetErrInfo(dbi, reply); } FreeConnection(pRedisConn); return bRet; } - - - diff --git a/src/xRedisPool.cpp b/src/xRedisPool.cpp index d110969..c5ef2b3 100644 --- a/src/xRedisPool.cpp +++ b/src/xRedisPool.cpp @@ -7,124 +7,145 @@ */ #include "xRedisPool.h" -#include "hiredis.h" +#include #include using namespace xrc; -RedisPool::RedisPool() { +RedisPool::RedisPool() +{ mRedisCacheList = NULL; - mTypeSize=0; + mTypeSize = 0; srand((unsigned)time(NULL)); } -RedisPool::~RedisPool() { - +RedisPool::~RedisPool() +{ } -bool RedisPool::Init(uint32_t typesize) { +bool RedisPool::Init(uint32_t typesize) +{ mTypeSize = typesize; - if (mTypeSize>MAX_REDIS_CACHE_TYPE){ + if (mTypeSize > MAX_REDIS_CACHE_TYPE) + { return false; } mRedisCacheList = new RedisCache[mTypeSize]; - return mRedisCacheList!=NULL; + return mRedisCacheList != NULL; } -bool RedisPool::setHashBase(uint32_t cachetype, uint32_t hashbase) { - if ( (hashbase>MAX_REDIS_DB_HASHBASE)||(cachetype>mTypeSize-1)) { +bool RedisPool::setHashBase(uint32_t cachetype, uint32_t hashbase) +{ + if ((hashbase > MAX_REDIS_DB_HASHBASE) || (cachetype > mTypeSize - 1)) + { return false; } bool bRet = mRedisCacheList[cachetype].InitDB(cachetype, hashbase); return bRet; } -uint32_t RedisPool::getHashBase(uint32_t cachetype) { - if ((cachetype > mTypeSize) || (cachetype > MAX_REDIS_CACHE_TYPE)) { +uint32_t RedisPool::getHashBase(uint32_t cachetype) +{ + if ((cachetype > mTypeSize) || (cachetype > MAX_REDIS_CACHE_TYPE)) + { return 0; } return mRedisCacheList[cachetype].GetHashBase(); } -void RedisPool::Keepalive() { - for(uint32_t i=0; i0){ +void RedisPool::Keepalive() +{ + for (uint32_t i = 0; i < mTypeSize; i++) + { + if (mRedisCacheList[i].GetHashBase() > 0) + { mRedisCacheList[i].KeepAlive(); } } } -bool RedisPool::CheckReply(const redisReply *reply){ - if(NULL==reply) { +bool RedisPool::CheckReply(const redisReply *reply) +{ + if (NULL == reply) + { return false; } - switch(reply->type){ - case REDIS_REPLY_STRING:{ - return true; - } - case REDIS_REPLY_ARRAY:{ + switch (reply->type) + { + case REDIS_REPLY_STRING: + { + return true; + } + case REDIS_REPLY_ARRAY: + { return true; - } - case REDIS_REPLY_INTEGER:{ - return true; - } - case REDIS_REPLY_NIL:{ - return false; - } - case REDIS_REPLY_STATUS:{ - return true; - } - case REDIS_REPLY_ERROR:{ - return false; - } - default:{ - return false; - } } - + case REDIS_REPLY_INTEGER: + { + return true; + } + case REDIS_REPLY_NIL: + { + return false; + } + case REDIS_REPLY_STATUS: + { + return true; + } + case REDIS_REPLY_ERROR: + { + return false; + } + default: + { + return false; + } + } + return false; } -void RedisPool::FreeReply(const redisReply *reply){ - if (NULL!=reply) { - freeReplyObject((void*)reply); +void RedisPool::FreeReply(const redisReply *reply) +{ + if (NULL != reply) + { + freeReplyObject((void *)reply); } } -bool RedisPool::ConnectRedisDB( uint32_t cahcetype, uint32_t dbindex, - const std::string& host, uint32_t port, const std::string& passwd, - uint32_t poolsize, uint32_t timeout, uint32_t role){ - if( (0==host.length()) - || (cahcetype>MAX_REDIS_CACHE_TYPE) - || (dbindex>MAX_REDIS_DB_HASHBASE) - || (cahcetype>mTypeSize - 1) - || (role>SLAVE) - || (poolsize>MAX_REDIS_CONN_POOLSIZE)) { - return false; +bool RedisPool::ConnectRedisDB(uint32_t cahcetype, uint32_t dbindex, + const std::string &host, uint32_t port, const std::string &passwd, + uint32_t poolsize, uint32_t timeout, uint32_t role) +{ + if ((0 == host.length()) || (cahcetype > MAX_REDIS_CACHE_TYPE) || (dbindex > MAX_REDIS_DB_HASHBASE) || (cahcetype > mTypeSize - 1) || (role > SLAVE) || (poolsize > MAX_REDIS_CONN_POOLSIZE)) + { + return false; } return mRedisCacheList[cahcetype].ConnectRedisDB(cahcetype, dbindex, host, port, - passwd, poolsize, timeout, role); + passwd, poolsize, timeout, role); } -void RedisPool::Release(){ - for(uint32_t i=0; i0) { +void RedisPool::Release() +{ + for (uint32_t i = 0; i < mTypeSize; i++) + { + if (mRedisCacheList[i].GetHashBase() > 0) + { mRedisCacheList[i].ClosePool(); } } - delete [] mRedisCacheList; + delete[] mRedisCacheList; } -RedisConn *RedisPool::GetConnection(uint32_t cahcetype, uint32_t dbindex, uint32_t ioType){ +RedisConn *RedisPool::GetConnection(uint32_t cahcetype, uint32_t dbindex, uint32_t ioType) +{ RedisConn *pRedisConn = NULL; - if ( (cahcetype>mTypeSize) - ||(dbindex>mRedisCacheList[cahcetype].GetHashBase()) - || (ioType>SLAVE) - ){ + if ((cahcetype > mTypeSize) || (dbindex > mRedisCacheList[cahcetype].GetHashBase()) || (ioType > SLAVE)) + { return NULL; } @@ -134,8 +155,10 @@ RedisConn *RedisPool::GetConnection(uint32_t cahcetype, uint32_t dbindex, uint32 return pRedisConn; } -void RedisPool::FreeConnection(RedisConn *redisconn){ - if (NULL!=redisconn) { +void RedisPool::FreeConnection(RedisConn *redisconn) +{ + if (NULL != redisconn) + { mRedisCacheList[redisconn->GetType()].FreeConn(redisconn); } } @@ -153,10 +176,9 @@ RedisConn::RedisConn() RedisConn::~RedisConn() { - } -redisContext * RedisConn::ConnectWithTimeout() +redisContext *RedisConn::ConnectWithTimeout() { struct timeval timeoutVal; timeoutVal.tv_sec = mTimeout; @@ -164,14 +186,17 @@ redisContext * RedisConn::ConnectWithTimeout() redisContext *ctx = NULL; ctx = redisConnectWithTimeout(mHost.c_str(), mPort, timeoutVal); - if (NULL == ctx || ctx->err) { - if (NULL != ctx) { + if (NULL == ctx || ctx->err) + { + if (NULL != ctx) + { redisFree(ctx); ctx = NULL; - } else { - } - } + else + { + } + } return ctx; } @@ -179,14 +204,20 @@ redisContext * RedisConn::ConnectWithTimeout() bool RedisConn::auth() { bool bRet = false; - if (0 == mPass.length()) { + if (0 == mPass.length()) + { bRet = true; - } else { + } + else + { redisReply *reply = static_cast(redisCommand(mCtx, "AUTH %s", mPass.c_str())); - if ((NULL == reply) || (strcasecmp(reply->str, "OK") != 0)) { + if ((NULL == reply) || (strcasecmp(reply->str, "OK") != 0)) + { bRet = false; - } else { - bRet = true; + } + else + { + bRet = true; } freeReplyObject(reply); } @@ -197,15 +228,19 @@ bool RedisConn::auth() bool RedisConn::RedisConnect() { bool bRet = false; - if (NULL != mCtx) { + if (NULL != mCtx) + { redisFree(mCtx); mCtx = NULL; } mCtx = ConnectWithTimeout(); - if (NULL==mCtx) { + if (NULL == mCtx) + { bRet = false; - } else { + } + else + { bRet = auth(); mConnStatus = bRet; } @@ -215,15 +250,19 @@ bool RedisConn::RedisConnect() bool RedisConn::RedisReConnect() { - if (NULL == mCtx) { + if (NULL == mCtx) + { return false; } bool bRet = false; redisContext *tmp_ctx = ConnectWithTimeout(); - if (NULL == tmp_ctx) { + if (NULL == tmp_ctx) + { bRet = false; - } else { + } + else + { redisFree(mCtx); mCtx = tmp_ctx; bRet = auth(); @@ -238,15 +277,15 @@ bool RedisConn::Ping() redisReply *reply = static_cast(redisCommand(mCtx, "PING")); bool bRet = (NULL != reply) && (reply->str) && (strcasecmp(reply->str, "PONG") == 0); mConnStatus = bRet; - if(bRet) + if (bRet) { freeReplyObject(reply); } return bRet; } -void RedisConn::Init(uint32_t cahcetype, uint32_t dbindex, const std::string& host, uint32_t port, - const std::string& pass, uint32_t poolsize, uint32_t timeout, uint32_t role, uint32_t slaveidx) +void RedisConn::Init(uint32_t cahcetype, uint32_t dbindex, const std::string &host, uint32_t port, + const std::string &pass, uint32_t poolsize, uint32_t timeout, uint32_t role, uint32_t slaveidx) { mType = cahcetype; mDbindex = dbindex; @@ -259,7 +298,6 @@ void RedisConn::Init(uint32_t cahcetype, uint32_t dbindex, const std::string& ho mSlaveIdx = slaveidx; } - RedisDBSlice::RedisDBSlice() { mType = 0; @@ -270,94 +308,111 @@ RedisDBSlice::RedisDBSlice() RedisDBSlice::~RedisDBSlice() { - } -void RedisDBSlice::Init( uint32_t cahcetype, uint32_t dbindex) +void RedisDBSlice::Init(uint32_t cahcetype, uint32_t dbindex) { mType = cahcetype; mDbindex = dbindex; } -bool RedisDBSlice::ConnectRedisNodes(uint32_t cahcetype, uint32_t dbindex, const std::string& host, uint32_t port, - const std::string& passwd, uint32_t poolsize, uint32_t timeout, int32_t role) +bool RedisDBSlice::ConnectRedisNodes(uint32_t cahcetype, uint32_t dbindex, const std::string &host, uint32_t port, + const std::string &passwd, uint32_t poolsize, uint32_t timeout, int32_t role) { bool bRet = false; - if ((host.empty()) - || (cahcetype > MAX_REDIS_CACHE_TYPE) - || (dbindex > MAX_REDIS_DB_HASHBASE) - || (poolsize > MAX_REDIS_CONN_POOLSIZE)) { + if ((host.empty()) || (cahcetype > MAX_REDIS_CACHE_TYPE) || (dbindex > MAX_REDIS_DB_HASHBASE) || (poolsize > MAX_REDIS_CONN_POOLSIZE)) + { return false; } - try { - if (MASTER == role) { + try + { + if (MASTER == role) + { XLOCK(mSliceConn.MasterLock); - for (uint32_t i = 0; i < poolsize; ++i) { + for (uint32_t i = 0; i < poolsize; ++i) + { RedisConn *pRedisconn = new RedisConn; - if (NULL == pRedisconn) { + if (NULL == pRedisconn) + { continue; } pRedisconn->Init(cahcetype, dbindex, host, port, passwd, poolsize, timeout, role, 0); - if (pRedisconn->RedisConnect()) { + if (pRedisconn->RedisConnect()) + { mSliceConn.RedisMasterConn.push_back(pRedisconn); mStatus = REDISDB_WORKING; bRet = true; - } else { + } + else + { delete pRedisconn; } } - - } else if (SLAVE == role) { + } + else if (SLAVE == role) + { XLOCK(mSliceConn.SlaveLock); RedisConnPool *pSlaveNode = new RedisConnPool; int32_t slave_idx = mSliceConn.RedisSlaveConn.size(); - for (uint32_t i = 0; i < poolsize; ++i) { + for (uint32_t i = 0; i < poolsize; ++i) + { RedisConn *pRedisconn = new RedisConn; - if (NULL == pRedisconn) { + if (NULL == pRedisconn) + { continue; } pRedisconn->Init(cahcetype, dbindex, host, port, passwd, poolsize, timeout, role, slave_idx); - if (pRedisconn->RedisConnect()) { + if (pRedisconn->RedisConnect()) + { pSlaveNode->push_back(pRedisconn); bRet = true; - } else { + } + else + { delete pRedisconn; } } mSliceConn.RedisSlaveConn.push_back(pSlaveNode); mHaveSlave = true; - } else { + } + else + { bRet = false; } - - } catch (...) { + } + catch (...) + { return false; } return bRet; } -RedisConn * RedisDBSlice::GetMasterConn() +RedisConn *RedisDBSlice::GetMasterConn() { RedisConn *pRedisConn = NULL; XLOCK(mSliceConn.MasterLock); - if (!mSliceConn.RedisMasterConn.empty()) { + if (!mSliceConn.RedisMasterConn.empty()) + { pRedisConn = mSliceConn.RedisMasterConn.front(); mSliceConn.RedisMasterConn.pop_front(); - } else { + } + else + { mStatus = REDISDB_DEAD; } return pRedisConn; } -RedisConn * RedisDBSlice::GetSlaveConn() +RedisConn *RedisDBSlice::GetSlaveConn() { RedisConn *pRedisConn = NULL; XLOCK(mSliceConn.SlaveLock); - if (!mSliceConn.RedisSlaveConn.empty()) { + if (!mSliceConn.RedisSlaveConn.empty()) + { size_t slave_cnt = mSliceConn.RedisSlaveConn.size(); uint32_t idx = rand() % slave_cnt; RedisConnPool *pSlave = mSliceConn.RedisSlaveConn[idx]; @@ -369,17 +424,23 @@ RedisConn * RedisDBSlice::GetSlaveConn() return pRedisConn; } -RedisConn * RedisDBSlice::GetConn(int32_t ioRole) +RedisConn *RedisDBSlice::GetConn(int32_t ioRole) { RedisConn *pRedisConn = NULL; - if (!mHaveSlave) { + if (!mHaveSlave) + { ioRole = MASTER; } - if (MASTER == ioRole) { + if (MASTER == ioRole) + { pRedisConn = GetMasterConn(); - } else if (SLAVE == ioRole) { + } + else if (SLAVE == ioRole) + { pRedisConn = GetSlaveConn(); - } else { + } + else + { pRedisConn = NULL; } @@ -388,17 +449,22 @@ RedisConn * RedisDBSlice::GetConn(int32_t ioRole) void RedisDBSlice::FreeConn(RedisConn *redisconn) { - if (NULL != redisconn) { + if (NULL != redisconn) + { uint32_t role = redisconn->GetRole(); - if (MASTER == role) { + if (MASTER == role) + { XLOCK(mSliceConn.MasterLock); mSliceConn.RedisMasterConn.push_back(redisconn); - } else if (SLAVE == role) { + } + else if (SLAVE == role) + { XLOCK(mSliceConn.SlaveLock); RedisConnPool *pSlave = mSliceConn.RedisSlaveConn[redisconn->GetSlaveIdx()]; pSlave->push_back(redisconn); - } else { - + } + else + { } } } @@ -408,7 +474,8 @@ void RedisDBSlice::CloseConnPool() { XLOCK(mSliceConn.MasterLock); RedisConnIter master_iter = mSliceConn.RedisMasterConn.begin(); - for (; master_iter != mSliceConn.RedisMasterConn.end(); ++master_iter) { + for (; master_iter != mSliceConn.RedisMasterConn.end(); ++master_iter) + { redisFree((*master_iter)->getCtx()); delete *master_iter; } @@ -417,10 +484,12 @@ void RedisDBSlice::CloseConnPool() { XLOCK(mSliceConn.SlaveLock); RedisSlaveGroupIter slave_iter = mSliceConn.RedisSlaveConn.begin(); - for (; slave_iter != mSliceConn.RedisSlaveConn.end(); ++slave_iter) { - RedisConnPool* pConnPool = (*slave_iter); + for (; slave_iter != mSliceConn.RedisSlaveConn.end(); ++slave_iter) + { + RedisConnPool *pConnPool = (*slave_iter); RedisConnIter iter = pConnPool->begin(); - for (; iter != pConnPool->end(); ++iter) { + for (; iter != pConnPool->end(); ++iter) + { redisFree((*iter)->getCtx()); delete *iter; } @@ -436,12 +505,15 @@ void RedisDBSlice::ConnPoolPing() { XLOCK(mSliceConn.MasterLock); RedisConnIter master_iter = mSliceConn.RedisMasterConn.begin(); - for (; master_iter != mSliceConn.RedisMasterConn.end(); ++master_iter) { + for (; master_iter != mSliceConn.RedisMasterConn.end(); ++master_iter) + { bool bRet = (*master_iter)->Ping(); - if (!bRet) { + if (!bRet) + { (*master_iter)->RedisReConnect(); - } else { - + } + else + { } } } @@ -449,15 +521,19 @@ void RedisDBSlice::ConnPoolPing() { XLOCK(mSliceConn.SlaveLock); RedisSlaveGroupIter slave_iter = mSliceConn.RedisSlaveConn.begin(); - for (; slave_iter != mSliceConn.RedisSlaveConn.end(); ++slave_iter) { - RedisConnPool* pConnPool = (*slave_iter); + for (; slave_iter != mSliceConn.RedisSlaveConn.end(); ++slave_iter) + { + RedisConnPool *pConnPool = (*slave_iter); RedisConnIter iter = pConnPool->begin(); - for (; iter != pConnPool->end(); ++iter) { + for (; iter != pConnPool->end(); ++iter) + { bool bRet = (*iter)->Ping(); - if (!bRet) { + if (!bRet) + { (*iter)->RedisReConnect(); - } else { - + } + else + { } } } @@ -469,8 +545,6 @@ uint32_t RedisDBSlice::GetStatus() const return mStatus; } - - RedisCache::RedisCache() { mCachetype = 0; @@ -480,31 +554,32 @@ RedisCache::RedisCache() RedisCache::~RedisCache() { - } bool RedisCache::InitDB(uint32_t cachetype, uint32_t hashbase) { mCachetype = cachetype; mHashbase = hashbase; - if (NULL == mDBList) { + if (NULL == mDBList) + { mDBList = new RedisDBSlice[hashbase]; } return true; } -bool RedisCache::ConnectRedisDB(uint32_t cahcetype, uint32_t dbindex, const std::string& host, - uint32_t port, const std::string& passwd, uint32_t poolsize, uint32_t timeout, uint32_t role) +bool RedisCache::ConnectRedisDB(uint32_t cahcetype, uint32_t dbindex, const std::string &host, + uint32_t port, const std::string &passwd, uint32_t poolsize, uint32_t timeout, uint32_t role) { mDBList[dbindex].Init(cahcetype, dbindex); return mDBList[dbindex].ConnectRedisNodes(cahcetype, dbindex, host, port, - passwd, poolsize, timeout, role); + passwd, poolsize, timeout, role); } void RedisCache::ClosePool() { - for (uint32_t i = 0; i < mHashbase; i++) { + for (uint32_t i = 0; i < mHashbase; i++) + { mDBList[i].CloseConnPool(); } delete[] mDBList; @@ -513,7 +588,8 @@ void RedisCache::ClosePool() void RedisCache::KeepAlive() { - for (uint32_t i = 0; i < mHashbase; i++) { + for (uint32_t i = 0; i < mHashbase; i++) + { mDBList[i].ConnPoolPing(); } } @@ -521,7 +597,8 @@ void RedisCache::KeepAlive() uint32_t RedisCache::GetDBStatus(uint32_t dbindex) { RedisDBSlice *pdbSclice = &mDBList[dbindex]; - if (NULL == pdbSclice) { + if (NULL == pdbSclice) + { return REDISDB_UNCONN; } return pdbSclice->GetStatus(); @@ -532,7 +609,7 @@ void RedisCache::FreeConn(RedisConn *redisconn) return mDBList[redisconn->getdbindex()].FreeConn(redisconn); } -RedisConn * RedisCache::GetConn(uint32_t dbindex, uint32_t ioRole) +RedisConn *RedisCache::GetConn(uint32_t dbindex, uint32_t ioRole) { return mDBList[dbindex].GetConn(ioRole); } @@ -541,5 +618,3 @@ uint32_t RedisCache::GetHashBase() const { return mHashbase; } - - diff --git a/src/xRedisPool.h b/src/xRedisPool.h deleted file mode 100644 index 7840174..0000000 --- a/src/xRedisPool.h +++ /dev/null @@ -1,182 +0,0 @@ -/* - * ---------------------------------------------------------------------------- - * Copyright (c) 2013-2014, xSky - * All rights reserved. - * Distributed under GPL license. - * ---------------------------------------------------------------------------- - */ - -#ifndef _XREDIS_POOL_H_ -#define _XREDIS_POOL_H_ - -#include "hiredis.h" -#include "xLock.h" -#include -#include -#include -#include "xRedisClient.h" - -namespace xrc -{ - -#define MAX_REDIS_CONN_POOLSIZE 128 // 每个DB最大连接数 -#define MAX_REDIS_CACHE_TYPE 128 // 最大支持的CACHE种类数 -#define MAX_REDIS_DB_HASHBASE 128 // 最大HASH分库基数 - -#define GET_CONNECT_ERROR "get connection error" -#define CONNECT_CLOSED_ERROR "redis connection be closed" - -#ifdef WIN32 - #define strcasecmp stricmp - #define strncasecmp strnicmp -#endif - -enum { - REDISDB_UNCONN, - REDISDB_WORKING, - REDISDB_DEAD -}; - -class RedisConn -{ -public: - RedisConn(); - ~RedisConn(); - - void Init(uint32_t cahcetype, - uint32_t dbindex, - const std::string& host, - uint32_t port, - const std::string& pass, - uint32_t poolsize, - uint32_t timeout, - uint32_t role, - uint32_t slaveidx - ); - - bool RedisConnect(); - bool RedisReConnect(); - bool Ping(); - - redisContext *getCtx() const { return mCtx; } - uint32_t getdbindex() const { return mDbindex; } - uint32_t GetType() const { return mType; } - uint32_t GetRole() const { return mRole; } - uint32_t GetSlaveIdx() const { return mSlaveIdx; } - bool GetConnstatus() const { return mConnStatus; } - -private: - bool auth(); - redisContext * ConnectWithTimeout(); - -private: - // redis connector context - redisContext *mCtx; - std::string mHost; // redis host - uint32_t mPort; // redis sever port - std::string mPass; // redis server password - uint32_t mTimeout; // connect timeout second - uint32_t mPoolsize; // connect pool size for each redis DB - uint32_t mType; // redis cache pool type - uint32_t mDbindex; // redis DB index - uint32_t mRole; // redis role - uint32_t mSlaveIdx; // the index in the slave group - bool mConnStatus; // redis connection status -}; - -typedef std::list RedisConnPool; -typedef std::list::iterator RedisConnIter; - -typedef std::vector RedisSlaveGroup; -typedef std::vector::iterator RedisSlaveGroupIter; - -typedef struct _RedisDBSlice_Conn_ { - RedisConnPool RedisMasterConn; - RedisSlaveGroup RedisSlaveConn; - xLock MasterLock; - xLock SlaveLock; -} RedisSliceConn; - - -class RedisDBSlice -{ -public: - RedisDBSlice(); - ~RedisDBSlice(); - - void Init( uint32_t cahcetype, uint32_t dbindex); - // 连到到一个REDIS服务节点 - bool ConnectRedisNodes(uint32_t cahcetype, uint32_t dbindex, - const std::string& host, uint32_t port, const std::string& passwd, - uint32_t poolsize, uint32_t timeout, int32_t role); - - RedisConn *GetMasterConn(); - RedisConn *GetSlaveConn(); - RedisConn *GetConn(int32_t ioRole); - void FreeConn(RedisConn *redisconn); - void CloseConnPool(); - void ConnPoolPing(); - uint32_t GetStatus() const; - -private: - RedisSliceConn mSliceConn; - bool mHaveSlave; - uint32_t mType; // redis cache pool type - uint32_t mDbindex; // redis slice index - uint32_t mStatus; // redis DB status -}; - -class RedisCache -{ -public: - RedisCache(); - virtual ~RedisCache(); - - bool InitDB( uint32_t cachetype, uint32_t hashbase); - bool ConnectRedisDB( uint32_t cahcetype, uint32_t dbindex, - const std::string& host, uint32_t port, const std::string& passwd, - uint32_t poolsize, uint32_t timeout, uint32_t role); - - RedisConn *GetConn( uint32_t dbindex, uint32_t ioRole); - void FreeConn(RedisConn *redisconn); - void ClosePool(); - void KeepAlive(); - uint32_t GetDBStatus(uint32_t dbindex); - uint32_t GetHashBase() const; - -private: - RedisDBSlice *mDBList; - uint32_t mCachetype; - uint32_t mHashbase; -}; - - -class RedisPool -{ -public: - RedisPool(); - ~RedisPool(); - - bool Init(uint32_t typesize); - bool setHashBase(uint32_t cachetype, uint32_t hashbase); - uint32_t getHashBase(uint32_t cachetype); - bool ConnectRedisDB(uint32_t cachetype, uint32_t dbindex, - const std::string& host, uint32_t port, const std::string& passwd, - uint32_t poolsize, uint32_t timeout, uint32_t role); - static bool CheckReply(const redisReply* reply); - static void FreeReply(const redisReply* reply); - - RedisConn *GetConnection(uint32_t cachetype, uint32_t index, uint32_t ioType = MASTER); - void FreeConnection(RedisConn* redisconn); - - void Keepalive(); - void Release(); -private: - RedisCache *mRedisCacheList; - uint32_t mTypeSize; -}; - - -} - -#endif From 843624cb7c4ce266cd0a16aa2f36a98ebc19b5fb Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:32:28 +0800 Subject: [PATCH 03/24] change to use c++ thread --- include/xredis/xRedisClusterClient.h | 1 + src/xRedisClusterClient.cpp | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/include/xredis/xRedisClusterClient.h b/include/xredis/xRedisClusterClient.h index 86b85ae..4e3298c 100644 --- a/include/xredis/xRedisClusterClient.h +++ b/include/xredis/xRedisClusterClient.h @@ -7,6 +7,7 @@ #include #include #include +#incldue < thread> #include #include "xLock.h" diff --git a/src/xRedisClusterClient.cpp b/src/xRedisClusterClient.cpp index e741d32..784c6a8 100644 --- a/src/xRedisClusterClient.cpp +++ b/src/xRedisClusterClient.cpp @@ -472,10 +472,10 @@ RedisConnection *xRedisClusterClient::GetConnection(uint32_t idx) else { printf("RedisPool::GetConnection() error pthread_id=%lu \n", - (unsigned long)pthread_self()); + (unsigned long)std::hash()(std::this_thread::get_id())); } } - usleep(1000); + std::this_thread::sleep_for(std::chrono::seconds(1)); } printf("idx:%u %s:%u \n", idx, pRedisConn->mHost, pRedisConn->mPort); return pRedisConn; From fd39dfdff5f1af0becc30ee86e3c901075898105 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:33:01 +0800 Subject: [PATCH 04/24] add initial cmake support --- CMakeLists.txt | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..11514e5 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,49 @@ +cmake_minimum_required (VERSION 3.15) +project(xredis CXX) + +find_path(hiredis_INCLUDE_DIR hiredis/hiredis.h) +if (hiredis_INCLUDE_DIR) + find_library(hiredis_LIBRARY hiredis) + add_library(hiredis STATIC IMPORTED) + set_target_properties(hiredis PROPERTIES + IMPORTED_LOCATION ${hiredis_LIBRARY} + ) + target_include_directories( + hiredis + INTERFACE ${hiredis_INCLUDE_DIR} + ) +endif() +option(xredis_BUILD_TEST "Build tests?" OFF) + +file(GLOB xredis_SOURCES + ${xredis_SOURCE_DIR}/src/*.cpp +) + +add_library (xredis ${xredis_SOURCES}) + +target_include_directories( + xredis + PUBLIC ${xredis_SOURCE_DIR}/include + PRIVATE ${xredis_SOURCE_DIR}/include/xredis +) + +target_link_libraries( + xredis + PRIVATE hiredis +) + +if (xredis_BUILD_TEST) + enable_testing() + + add_executable(xredis_test EXCLUDE_FROM_ALL test/xredis-test.cpp) + + target_link_libraries( + xredis_test + PRIVATE xredis + ) + + add_test( + NAME xredis_test + COMMAND $ + ) +endif() From 1f34e3afc9cfd9fb1ed2fa042ffb9bd799c0d754 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:33:07 +0800 Subject: [PATCH 05/24] update gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 0def275..98552bf 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ *.exe *.out *.app + +.vscode/ +build/ \ No newline at end of file From 1a1db52d89ba170e5056e5c21b5d1ca126a74edc Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:52:02 +0800 Subject: [PATCH 06/24] add missing time header --- test/xredis-test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/test/xredis-test.cpp b/test/xredis-test.cpp index 3ab6478..65228cd 100644 --- a/test/xredis-test.cpp +++ b/test/xredis-test.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "xRedisClient.h" From 3a23b7a3f968909e41f7bb5f1d8def82bcc7c224 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:52:42 +0800 Subject: [PATCH 07/24] add __PRETTY_FUNCTION__ shim --- test/xredis-test.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/xredis-test.cpp b/test/xredis-test.cpp index 65228cd..63e6997 100644 --- a/test/xredis-test.cpp +++ b/test/xredis-test.cpp @@ -13,6 +13,11 @@ using namespace xrc; #define CACHE_TYPE_1 1 xRedisClient xClient; +#ifdef _MSC_VER + +#define __PRETTY_FUNCTION__ __FUNCSIG__ +#endif + // AP Hash Function unsigned int APHash(const char *str) { From b869aa27a54779d0811153e7ee4191b6d8f5d05f Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:52:58 +0800 Subject: [PATCH 08/24] use public header instead --- test/xredis-test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xredis-test.cpp b/test/xredis-test.cpp index 63e6997..13df8d1 100644 --- a/test/xredis-test.cpp +++ b/test/xredis-test.cpp @@ -6,7 +6,7 @@ #include #include -#include "xRedisClient.h" +#include "xredis/xRedisClient.h" using namespace xrc; From ed97f3973baec198beaf2de18c9c2622d162aa24 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:53:15 +0800 Subject: [PATCH 09/24] general style fix --- test/xredis-test.cpp | 339 ++++++++++++++++++++++++++++--------------- 1 file changed, 220 insertions(+), 119 deletions(-) diff --git a/test/xredis-test.cpp b/test/xredis-test.cpp index 13df8d1..7cef12c 100644 --- a/test/xredis-test.cpp +++ b/test/xredis-test.cpp @@ -14,7 +14,6 @@ using namespace xrc; xRedisClient xClient; #ifdef _MSC_VER - #define __PRETTY_FUNCTION__ __FUNCSIG__ #endif @@ -24,10 +23,14 @@ unsigned int APHash(const char *str) unsigned int hash = 0; int i; - for (i = 0; *str; i++) { - if ((i & 1) == 0) { + for (i = 0; *str; i++) + { + if ((i & 1) == 0) + { hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); - } else { + } + else + { hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); } } @@ -35,21 +38,24 @@ unsigned int APHash(const char *str) return (hash & 0x7FFFFFFF); } - -void test_zadd(const char *charkey, const std::string& strValue) +void test_zadd(const char *charkey, const std::string &strValue) { - std::string strkey=charkey; + std::string strkey = charkey; VALUES vVal; - int64_t retVal=0; + int64_t retVal = 0; int64_t scores = 168; vVal.push_back(toString(scores)); vVal.push_back(strValue); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(charkey, APHash, CACHE_TYPE_1); - if (bRet) { - if (xClient.zadd(dbi, strkey, vVal, retVal)) { + if (bRet) + { + if (xClient.zadd(dbi, strkey, vVal, retVal)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -59,10 +65,14 @@ void test_set(const char *strkey, const char *strValue) { RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(strkey, APHash, CACHE_TYPE_1); - if (bRet) { - if (xClient.set(dbi, strkey, strValue)) { + if (bRet) + { + if (xClient.set(dbi, strkey, strValue)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -75,10 +85,14 @@ void test_append() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { - if (xClient.append(dbi, szKey, " xsky")) { + if (bRet) + { + if (xClient.append(dbi, szKey, " xsky")) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -91,15 +105,22 @@ void test_decr() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t res = 0; - if (xClient.decr(dbi, szKey, res)) { - if (res == 99) { + if (xClient.decr(dbi, szKey, res)) + { + if (res == 99) + { printf("%s success %ld \r\n", __PRETTY_FUNCTION__, res); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -112,15 +133,22 @@ void test_decrby() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t res = 0; - if (xClient.decrby(dbi, szKey, 11, res)) { - if (res == 89) { + if (xClient.decrby(dbi, szKey, 11, res)) + { + if (res == 89) + { printf("%s success %ld \r\n", __PRETTY_FUNCTION__, res); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -133,15 +161,22 @@ void test_incr() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t res = 0; - if (xClient.incr(dbi, szKey, res)) { - if (res == 101) { + if (xClient.incr(dbi, szKey, res)) + { + if (res == 101) + { printf("%s success %ld \r\n", __PRETTY_FUNCTION__, res); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -154,15 +189,22 @@ void test_incrby() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t res = 0; - if (xClient.incrby(dbi, szKey, 11, res)) { - if (res == 111) { + if (xClient.incrby(dbi, szKey, 11, res)) + { + if (res == 111) + { printf("%s success %ld \r\n", __PRETTY_FUNCTION__, res); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -176,26 +218,33 @@ void test_get() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { std::string strData; - if (xClient.get(dbi, szKey, strData)) { + if (xClient.get(dbi, szKey, strData)) + { printf("%s success data:%s \r\n", __PRETTY_FUNCTION__, strData.c_str()); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } } - { sprintf(szKey, "test_%u", (unsigned int)time(NULL)); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { std::string strData; - if (xClient.get(dbi, szKey, strData)) { + if (xClient.get(dbi, szKey, strData)) + { printf("%s error data:%s \r\n", __PRETTY_FUNCTION__, strData.c_str()); - } else { + } + else + { printf("%s success [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -213,12 +262,14 @@ void test_type() const std::string str = "wwwwwwwwwwwwwwwwwwwwwwwww"; xClient.set(dbi, szKey, str); std::string strData; - if (xClient.type(dbi, szKey, strData)) { + if (xClient.type(dbi, szKey, strData)) + { printf("%s success data:%s \r\n", __PRETTY_FUNCTION__, strData.c_str()); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } - } void test_getrange() @@ -229,11 +280,15 @@ void test_getrange() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { std::string strData; - if (xClient.getrange(dbi, szKey, 2, 6, strData)) { + if (xClient.getrange(dbi, szKey, 2, 6, strData)) + { printf("%s success data:%s \r\n", __PRETTY_FUNCTION__, strData.c_str()); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -245,10 +300,14 @@ void test_exists() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { - if (xClient.exists(dbi, szKey)) { + if (bRet) + { + if (xClient.exists(dbi, szKey)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -260,10 +319,14 @@ void test_del() strcpy(szKey, "test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - if (bRet) { - if (xClient.del(dbi, szKey)) { + if (bRet) + { + if (xClient.del(dbi, szKey)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -273,9 +336,10 @@ void test_mset() { char szKey[256] = {0}; DBIArray vdbi; - VDATA kvData; + VDATA kvData; - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { RedisDBIdx dbi(&xClient); sprintf(szKey, "mset_key_%d", i); dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); @@ -285,9 +349,12 @@ void test_mset() kvData.push_back(szKey); } - if (xClient.mset(vdbi, kvData)) { + if (xClient.mset(vdbi, kvData)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, "mset error"); } } @@ -296,9 +363,10 @@ void test_mget() { char szKey[256] = {0}; DBIArray vdbi; - KEYS kData; + KEYS kData; ReplyData Reply; - for (int i = 0; i < 15; i++) { + for (int i = 0; i < 15; i++) + { RedisDBIdx dbi(&xClient); sprintf(szKey, "mset_key_%d", i); dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); @@ -306,13 +374,17 @@ void test_mget() kData.push_back(szKey); } - if (xClient.mget(vdbi, kData, Reply)) { + if (xClient.mget(vdbi, kData, Reply)) + { printf("%s success %zu \r\n", __PRETTY_FUNCTION__, Reply.size()); ReplyData::iterator iter = Reply.begin(); - for (; iter != Reply.end(); iter++) { + for (; iter != Reply.end(); iter++) + { printf("%d\t%s\r\n", (*iter).type, (*iter).str.c_str()); } - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, "mset error"); } } @@ -323,32 +395,38 @@ void test_hset() strcpy(szHKey, "hashtest"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t count = 0; - if (xClient.hset(dbi, szHKey, "filed1", "filed1_values", count)) { + if (xClient.hset(dbi, szHKey, "filed1", "filed1_values", count)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } } - void test_lpush() { - char szHKey[256] = { 0 }; + char szHKey[256] = {0}; strcpy(szHKey, "list_test"); RedisDBIdx dbi(&xClient); VALUES vVal; vVal.push_back(toString(time(NULL))); bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t count = 0; - if (xClient.lpush(dbi, szHKey, vVal, count)) { + if (xClient.lpush(dbi, szHKey, vVal, count)) + { printf("%s success %ld \r\n", __PRETTY_FUNCTION__, count); } - else { + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -356,17 +434,20 @@ void test_lpush() void test_llen() { - char szHKey[256] = { 0 }; + char szHKey[256] = {0}; strcpy(szHKey, "list_test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t count = 0; - if (xClient.llen(dbi, szHKey, count)) { + if (xClient.llen(dbi, szHKey, count)) + { printf("%s success len: %ld \r\n", __PRETTY_FUNCTION__, count); } - else { + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -374,23 +455,27 @@ void test_llen() void test_lrange() { - char szHKey[256] = { 0 }; + char szHKey[256] = {0}; strcpy(szHKey, "list_test"); RedisDBIdx dbi(&xClient); VALUES vVal; - + bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { ArrayReply Reply; - if (xClient.lrange(dbi, szHKey, 0, -1, Reply)) { + if (xClient.lrange(dbi, szHKey, 0, -1, Reply)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); ReplyData::iterator iter = Reply.begin(); - for (; iter != Reply.end(); iter++) { + for (; iter != Reply.end(); iter++) + { printf("%d\t%s\r\n", (*iter).type, (*iter).str.c_str()); } } - else { + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -398,17 +483,20 @@ void test_lrange() void test_lpop() { - char szHKey[256] = { 0 }; + char szHKey[256] = {0}; strcpy(szHKey, "list_test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { std::string strVal; - if (xClient.lpop(dbi, szHKey, strVal)) { + if (xClient.lpop(dbi, szHKey, strVal)) + { printf("%s success val: %s \r\n", __PRETTY_FUNCTION__, strVal.c_str()); } - else { + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -416,35 +504,41 @@ void test_lpop() void test_rpop() { - char szHKey[256] = { 0 }; + char szHKey[256] = {0}; strcpy(szHKey, "list_test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { std::string strVal; - if (xClient.rpop(dbi, szHKey, strVal)) { + if (xClient.rpop(dbi, szHKey, strVal)) + { printf("%s success val: %s \r\n", __PRETTY_FUNCTION__, strVal.c_str()); } - else { + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } } - void test_publish() { - char szHKey[256] = { 0 }; + char szHKey[256] = {0}; strcpy(szHKey, "pubsub_test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (bRet) { + if (bRet) + { int64_t count; - if (xClient.publish(dbi, szHKey, "test message", count)) { + if (xClient.publish(dbi, szHKey, "test message", count)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } } @@ -452,28 +546,33 @@ void test_publish() void test_subscribe() { - char szHKey[256] = { 0 }; + char szHKey[256] = {0}; strcpy(szHKey, "pubsub_test"); RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(szHKey, APHash, CACHE_TYPE_1); - if (!bRet) { + if (!bRet) + { return; } - + VDATA channels; channels.push_back(szHKey); xRedisContext ctx; - if (xClient.subscribe(dbi, channels, ctx)) { + if (xClient.subscribe(dbi, channels, ctx)) + { printf("%s success \r\n", __PRETTY_FUNCTION__); ReplyData vReply; - while (0 == xRedisClient::GetReply(&ctx, vReply)) { + while (0 == xRedisClient::GetReply(&ctx, vReply)) + { ReplyData::iterator iter = vReply.begin(); - for (; iter != vReply.end(); iter++) { + for (; iter != vReply.end(); iter++) + { printf("%d\t%s\r\n", (*iter).type, (*iter).str.c_str()); } } - - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); } xClient.unsubscribe(dbi, channels, ctx); @@ -482,10 +581,11 @@ void test_subscribe() void test_scan() { - const char* pattern = "a*"; + const char *pattern = "a*"; RedisDBIdx dbi(&xClient); bool bRet = dbi.CreateDBIndex(0, CACHE_TYPE_1); - if (!bRet) { + if (!bRet) + { return; } @@ -494,16 +594,20 @@ void test_scan() xRedisContext ctx; xClient.GetxRedisContext(dbi, &ctx); - do + do { arrayReply.clear(); - if (xClient.scan(dbi, cursor, pattern, 0, arrayReply, ctx)) { - printf("%"PRId64"\t\r\n", cursor); + if (xClient.scan(dbi, cursor, pattern, 0, arrayReply, ctx)) + { + printf("%" PRId64 "\t\r\n", cursor); ReplyData::iterator iter = arrayReply.begin(); - for (; iter != arrayReply.end(); iter++) { - printf("\t\t%s\r\n", (*iter).str.c_str()); + for (; iter != arrayReply.end(); iter++) + { + printf("\t\t%s\r\n", (*iter).str.c_str()); } - } else { + } + else + { printf("%s error [%s] \r\n", __PRETTY_FUNCTION__, dbi.GetErrInfo()); break; } @@ -519,12 +623,11 @@ int main(int argc, char **argv) xClient.Init(3); RedisNode RedisList1[3] = { - {0, "127.0.0.1", 6379, "", 2, 5, 0}, - {1, "127.0.0.1", 6379, "", 2, 5, 0}, - {2, "127.0.0.1", 6379, "", 2, 5, 0} - }; + {0, "192.168.1.13", 30005, "", 2, 5, 0}, + {1, "192.168.1.13", 30005, "", 2, 5, 0}, + {2, "192.168.1.13", 30005, "", 2, 5, 0}}; - xClient.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode),3, CACHE_TYPE_1); + xClient.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 3, CACHE_TYPE_1); test_zadd("test:sorted:key", "sorted value hello xredis"); test_set("test", "wwww"); @@ -560,5 +663,3 @@ int main(int argc, char **argv) return 0; } - - From a2bbb79d69c75778f9f59757325130155627cc89 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:53:42 +0800 Subject: [PATCH 10/24] add c++ thread instead of relying on pthread --- include/xredis/xRedisClusterClient.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/xredis/xRedisClusterClient.h b/include/xredis/xRedisClusterClient.h index 4e3298c..f29cad5 100644 --- a/include/xredis/xRedisClusterClient.h +++ b/include/xredis/xRedisClusterClient.h @@ -7,7 +7,7 @@ #include #include #include -#incldue < thread> +#include #include #include "xLock.h" From 1f2fba07cbd89c44d0dae44458117c1725211e52 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 22:53:47 +0800 Subject: [PATCH 11/24] fix testing on cmake --- CMakeLists.txt | 45 +++++++++++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 11514e5..e22ed7e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,19 +1,31 @@ cmake_minimum_required (VERSION 3.15) project(xredis CXX) -find_path(hiredis_INCLUDE_DIR hiredis/hiredis.h) -if (hiredis_INCLUDE_DIR) - find_library(hiredis_LIBRARY hiredis) - add_library(hiredis STATIC IMPORTED) - set_target_properties(hiredis PROPERTIES - IMPORTED_LOCATION ${hiredis_LIBRARY} - ) - target_include_directories( - hiredis - INTERFACE ${hiredis_INCLUDE_DIR} - ) +if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) + include(CTest) +endif() + +find_package(hiredis) + +if (NOT ${hiredis_FOUND}) + message("Dependency 'hiredis' is not within CMake package sources, attempting to add it manually") + find_path(hiredis_INCLUDE_DIR hiredis/hiredis.h) + if (hiredis_INCLUDE_DIR) + find_library(hiredis_LIBRARY hiredis) + add_library(hiredis STATIC IMPORTED) + set_target_properties(hiredis PROPERTIES + IMPORTED_LOCATION ${hiredis_LIBRARY} + ) + target_include_directories( + hiredis + INTERFACE ${hiredis_INCLUDE_DIR} + ) + message("Successfully found dependency 'hiredis' on ${hiredis_LIBRARY}") + else() + message(FATAL_ERROR "Dependency 'hiredis' not found, aborting") + endif() endif() -option(xredis_BUILD_TEST "Build tests?" OFF) + file(GLOB xredis_SOURCES ${xredis_SOURCE_DIR}/src/*.cpp @@ -32,9 +44,14 @@ target_link_libraries( PRIVATE hiredis ) -if (xredis_BUILD_TEST) - enable_testing() +if (MSVC) + target_link_libraries( + xredis + PUBLIC ws2_32 + ) +endif() +if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING) add_executable(xredis_test EXCLUDE_FROM_ALL test/xredis-test.cpp) target_link_libraries( From bf5b8f2fe48e70d2f1b42c3130154344cb53368a Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:02:24 +0800 Subject: [PATCH 12/24] fix more test --- test/xredis-test.cpp | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/test/xredis-test.cpp b/test/xredis-test.cpp index 7cef12c..9792bb0 100644 --- a/test/xredis-test.cpp +++ b/test/xredis-test.cpp @@ -618,14 +618,30 @@ void test_scan() int main(int argc, char **argv) { - printf("%d %s\r\n", argc, argv[0]); - xClient.Init(3); + auto server_var = argc > 1 ? argv[1] : std::getenv("XREDIS_TEST_SERVER_ADDR"); + auto port_var = argc > 2 ? argv[2] : std::getenv("XREDIS_TEST_SERVER_PORT"); + + std::string server; + int port; + + if (server_var && port_var) + { + server = std::string(server_var); + port = std::stoi(port_var); + } + else + { + fprintf(stderr, "Error: You must specify a redis address and ther port to continue!\n"); + return 1; + } + + // ???? RedisNode RedisList1[3] = { - {0, "192.168.1.13", 30005, "", 2, 5, 0}, - {1, "192.168.1.13", 30005, "", 2, 5, 0}, - {2, "192.168.1.13", 30005, "", 2, 5, 0}}; + {0, server, port, "", 2, 5, 0}, + {1, server, port, "", 2, 5, 0}, + {2, server, port, "", 2, 5, 0}}; xClient.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 3, CACHE_TYPE_1); From 72876f98dc6cc98ce549e1182567625e97dbcd15 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:21:13 +0800 Subject: [PATCH 13/24] use c++ headers --- examples/redis-cluster-client.cpp | 2 +- examples/xRedisClusterClient_test.cpp | 2 +- .../redis-test.cpp | 4 +- .../xredis-example-Consistent-hash.cpp | 2 +- examples/xredis-example.cpp | 178 +++++++++--------- include/xredis/xRedisClient.h | 4 +- include/xredis/xRedisClusterClient.h | 6 +- include/xredis/xRedisPool.h | 4 +- src/xRedisClient.cpp | 1 + src/xRedisClient_connection.cpp | 1 + src/xRedisClient_hashs.cpp | 2 + src/xRedisClient_keys.cpp | 1 + src/xRedisClient_lists.cpp | 2 + src/xRedisClient_pubsub.cpp | 1 + src/xRedisClient_sortedsets.cpp | 1 + src/xRedisClient_strings.cpp | 1 + src/xRedisPool.cpp | 5 +- test/xredis-test.cpp | 11 +- 18 files changed, 116 insertions(+), 112 deletions(-) diff --git a/examples/redis-cluster-client.cpp b/examples/redis-cluster-client.cpp index b6de2aa..5926e37 100644 --- a/examples/redis-cluster-client.cpp +++ b/examples/redis-cluster-client.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include "xRedisClusterClient.h" diff --git a/examples/xRedisClusterClient_test.cpp b/examples/xRedisClusterClient_test.cpp index 1a31e06..dc67716 100644 --- a/examples/xRedisClusterClient_test.cpp +++ b/examples/xRedisClusterClient_test.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include "xRedisClusterClient.h" diff --git a/examples/xredis-example-Consistent-hash/redis-test.cpp b/examples/xredis-example-Consistent-hash/redis-test.cpp index 93e7ae4..7bd842f 100644 --- a/examples/xredis-example-Consistent-hash/redis-test.cpp +++ b/examples/xredis-example-Consistent-hash/redis-test.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include "CMd5.h" @@ -108,7 +108,7 @@ bool ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) { if (ret.second) { vMap.insert(make_pair(hval, pVnode)); } else { - printf("ڵͻ: %s-%u \r\n", vNodekey, hval); + printf("�ڵ��ͻ: %s-%u \r\n", vNodekey, hval); delete pVnode; return false; } diff --git a/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp b/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp index 479de8a..32e7b74 100644 --- a/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp +++ b/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include "xRedisClient.h" diff --git a/examples/xredis-example.cpp b/examples/xredis-example.cpp index 77f8dbc..abd5872 100644 --- a/examples/xredis-example.cpp +++ b/examples/xredis-example.cpp @@ -1,89 +1,89 @@ -#include -#include -#include -#include - -#include "xRedisClient.h" - -using namespace xrc; - -// AP Hash Function -unsigned int APHash(const char *str) { - unsigned int hash = 0; - int i; - for (i=0; *str; i++) { - if ((i& 1) == 0) { - hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); - } else { - hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); - } - } - return (hash& 0x7FFFFFFF); -} - -enum { - CACHE_TYPE_1, - CACHE_TYPE_2, - CACHE_TYPE_MAX, -}; - - -RedisNode RedisList1[3]= -{ - {0,"127.0.0.1", 7000, "", 2, 5, 0}, - {1,"127.0.0.1", 7000, "", 2, 5, 0}, - {2,"127.0.0.1", 7000, "", 2, 5, 0} -}; - -RedisNode RedisList2[5]= -{ - {0,"127.0.0.1", 7000, "", 2, 5, 0}, - {1,"127.0.0.1", 7000, "", 2, 5, 0}, - {2,"127.0.0.1", 7000, "", 2, 5, 0}, - {3,"127.0.0.1", 7000, "", 2, 5, 0}, - {4,"127.0.0.1", 7000, "", 2, 5, 0}, -}; - -int main(int argc, char **argv) { - - (void)argc;(void)argv; - - xRedisClient xRedis; - xRedis.Init(CACHE_TYPE_MAX); - xRedis.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 3, CACHE_TYPE_1); - xRedis.ConnectRedisCache(RedisList2, sizeof(RedisList2) / sizeof(RedisNode), 5, CACHE_TYPE_2); - - for (int n = 0; n<1000; n++) { - char szKey[256] = {0}; - sprintf(szKey, "test_%d", n); - RedisDBIdx dbi(&xRedis); - dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - bool bRet = xRedis.set(dbi, szKey, "hello redis!"); - if (!bRet){ - printf(" %s %s \n", szKey, dbi.GetErrInfo()); - } - } - - for (int n = 0; n<1000; n++) { - char szKey[256] = {0}; - sprintf(szKey, "test_%d", n); - RedisDBIdx dbi(&xRedis); - dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); - std::string strValue; - xRedis.get(dbi, szKey, strValue); - printf("%s \r\n", strValue.c_str()); - } - - - int n = 10; - while (n--) { - xRedis.Keepalive(); - usleep(1000*1000*10); - } - - xRedis.Release(); - - return 0; -} - - +#include +#include +#include +#include + +#include "xRedisClient.h" + +using namespace xrc; + +// AP Hash Function +unsigned int APHash(const char *str) { + unsigned int hash = 0; + int i; + for (i=0; *str; i++) { + if ((i& 1) == 0) { + hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); + } else { + hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); + } + } + return (hash& 0x7FFFFFFF); +} + +enum { + CACHE_TYPE_1, + CACHE_TYPE_2, + CACHE_TYPE_MAX, +}; + + +RedisNode RedisList1[3]= +{ + {0,"127.0.0.1", 7000, "", 2, 5, 0}, + {1,"127.0.0.1", 7000, "", 2, 5, 0}, + {2,"127.0.0.1", 7000, "", 2, 5, 0} +}; + +RedisNode RedisList2[5]= +{ + {0,"127.0.0.1", 7000, "", 2, 5, 0}, + {1,"127.0.0.1", 7000, "", 2, 5, 0}, + {2,"127.0.0.1", 7000, "", 2, 5, 0}, + {3,"127.0.0.1", 7000, "", 2, 5, 0}, + {4,"127.0.0.1", 7000, "", 2, 5, 0}, +}; + +int main(int argc, char **argv) { + + (void)argc;(void)argv; + + xRedisClient xRedis; + xRedis.Init(CACHE_TYPE_MAX); + xRedis.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 3, CACHE_TYPE_1); + xRedis.ConnectRedisCache(RedisList2, sizeof(RedisList2) / sizeof(RedisNode), 5, CACHE_TYPE_2); + + for (int n = 0; n<1000; n++) { + char szKey[256] = {0}; + sprintf(szKey, "test_%d", n); + RedisDBIdx dbi(&xRedis); + dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); + bool bRet = xRedis.set(dbi, szKey, "hello redis!"); + if (!bRet){ + printf(" %s %s \n", szKey, dbi.GetErrInfo()); + } + } + + for (int n = 0; n<1000; n++) { + char szKey[256] = {0}; + sprintf(szKey, "test_%d", n); + RedisDBIdx dbi(&xRedis); + dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); + std::string strValue; + xRedis.get(dbi, szKey, strValue); + printf("%s \r\n", strValue.c_str()); + } + + + int n = 10; + while (n--) { + xRedis.Keepalive(); + usleep(1000*1000*10); + } + + xRedis.Release(); + + return 0; +} + + diff --git a/include/xredis/xRedisClient.h b/include/xredis/xRedisClient.h index 2388acb..4f6a8c7 100644 --- a/include/xredis/xRedisClient.h +++ b/include/xredis/xRedisClient.h @@ -9,8 +9,8 @@ #ifndef _XREDIS_CLIENT_H_ #define _XREDIS_CLIENT_H_ -#include -#include +#include +#include #include #include #include diff --git a/include/xredis/xRedisClusterClient.h b/include/xredis/xRedisClusterClient.h index f29cad5..b968a92 100644 --- a/include/xredis/xRedisClusterClient.h +++ b/include/xredis/xRedisClusterClient.h @@ -1,9 +1,9 @@ #ifndef _XREDIS_HIREDISCPP_H_ #define _XREDIS_HIREDISCPP_H_ -#include -#include -#include +#include +#include +#include #include #include #include diff --git a/include/xredis/xRedisPool.h b/include/xredis/xRedisPool.h index 022779b..fec4bdf 100644 --- a/include/xredis/xRedisPool.h +++ b/include/xredis/xRedisPool.h @@ -9,9 +9,7 @@ #ifndef _XREDIS_POOL_H_ #define _XREDIS_POOL_H_ -#include -#include "xLock.h" -#include +#include #include #include #include "xRedisClient.h" diff --git a/src/xRedisClient.cpp b/src/xRedisClient.cpp index 040d9e9..d9909cc 100644 --- a/src/xRedisClient.cpp +++ b/src/xRedisClient.cpp @@ -5,6 +5,7 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include #include "xRedisClient.h" #include "xRedisPool.h" diff --git a/src/xRedisClient_connection.cpp b/src/xRedisClient_connection.cpp index 461bd7e..bc63f1c 100644 --- a/src/xRedisClient_connection.cpp +++ b/src/xRedisClient_connection.cpp @@ -5,6 +5,7 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include #include "xRedisClient.h" #include diff --git a/src/xRedisClient_hashs.cpp b/src/xRedisClient_hashs.cpp index 3bdeb0e..92a2428 100644 --- a/src/xRedisClient_hashs.cpp +++ b/src/xRedisClient_hashs.cpp @@ -5,6 +5,8 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include +#include #include "xRedisClient.h" #include "xRedisPool.h" diff --git a/src/xRedisClient_keys.cpp b/src/xRedisClient_keys.cpp index be79d80..1846142 100644 --- a/src/xRedisClient_keys.cpp +++ b/src/xRedisClient_keys.cpp @@ -5,6 +5,7 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include #include "xRedisClient.h" #include "xRedisPool.h" diff --git a/src/xRedisClient_lists.cpp b/src/xRedisClient_lists.cpp index c77bfee..57d8941 100644 --- a/src/xRedisClient_lists.cpp +++ b/src/xRedisClient_lists.cpp @@ -5,6 +5,8 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include +#include #include #include "xRedisClient.h" diff --git a/src/xRedisClient_pubsub.cpp b/src/xRedisClient_pubsub.cpp index 9ebb397..4222b9c 100644 --- a/src/xRedisClient_pubsub.cpp +++ b/src/xRedisClient_pubsub.cpp @@ -5,6 +5,7 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include #include "xRedisClient.h" #include "xRedisPool.h" diff --git a/src/xRedisClient_sortedsets.cpp b/src/xRedisClient_sortedsets.cpp index a245579..7e888da 100644 --- a/src/xRedisClient_sortedsets.cpp +++ b/src/xRedisClient_sortedsets.cpp @@ -5,6 +5,7 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include #include "xRedisClient.h" #include diff --git a/src/xRedisClient_strings.cpp b/src/xRedisClient_strings.cpp index 3c9b024..fd03795 100644 --- a/src/xRedisClient_strings.cpp +++ b/src/xRedisClient_strings.cpp @@ -5,6 +5,7 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ +#include #include #include "xRedisClient.h" diff --git a/src/xRedisPool.cpp b/src/xRedisPool.cpp index c5ef2b3..12d22a9 100644 --- a/src/xRedisPool.cpp +++ b/src/xRedisPool.cpp @@ -5,10 +5,7 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ - -#include "xRedisPool.h" -#include -#include +#include using namespace xrc; diff --git a/test/xredis-test.cpp b/test/xredis-test.cpp index 9792bb0..efb04e0 100644 --- a/test/xredis-test.cpp +++ b/test/xredis-test.cpp @@ -1,10 +1,9 @@ -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include "xredis/xRedisClient.h" From e6722c0270daf3e650edc2277ab97ed10e70e1c8 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:21:22 +0800 Subject: [PATCH 14/24] re add missing dep --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e22ed7e..e431ba8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,7 +56,7 @@ if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING) target_link_libraries( xredis_test - PRIVATE xredis + PRIVATE xredis hiredis ) add_test( From ad568bc63a5c65b94163952627b0d3bd756f46d1 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:24:01 +0800 Subject: [PATCH 15/24] use a common header --- include/xredis/xredis.h | 11 +++++++++++ src/xRedisClient.cpp | 4 +--- src/xRedisClient_connection.cpp | 3 +-- src/xRedisClient_hashs.cpp | 6 ++---- src/xRedisClient_keys.cpp | 4 +--- src/xRedisClient_lists.cpp | 4 +--- src/xRedisClient_pubsub.cpp | 4 +--- src/xRedisClient_sets.cpp | 2 +- src/xRedisClient_sortedsets.cpp | 3 +-- src/xRedisClient_strings.cpp | 5 +---- src/xRedisClusterClient.cpp | 3 +-- src/xRedisPool.cpp | 1 + test/xredis-test.cpp | 2 +- 13 files changed, 24 insertions(+), 28 deletions(-) create mode 100644 include/xredis/xredis.h diff --git a/include/xredis/xredis.h b/include/xredis/xredis.h new file mode 100644 index 0000000..4f5f429 --- /dev/null +++ b/include/xredis/xredis.h @@ -0,0 +1,11 @@ +#pragma once + +#ifdef _MSC_VER +#include +#endif + +#include + +#include "xRedisClient.h" +#include "xRedisClusterClient.h" +#include "xRedisPool.h" diff --git a/src/xRedisClient.cpp b/src/xRedisClient.cpp index d9909cc..edbd627 100644 --- a/src/xRedisClient.cpp +++ b/src/xRedisClient.cpp @@ -6,10 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include "xredis.h" -#include "xRedisClient.h" -#include "xRedisPool.h" -#include using namespace xrc; RedisDBIdx::RedisDBIdx() diff --git a/src/xRedisClient_connection.cpp b/src/xRedisClient_connection.cpp index bc63f1c..3074b16 100644 --- a/src/xRedisClient_connection.cpp +++ b/src/xRedisClient_connection.cpp @@ -6,9 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include "xredis.h" -#include "xRedisClient.h" -#include using namespace xrc; void xRedisClient::quit() diff --git a/src/xRedisClient_hashs.cpp b/src/xRedisClient_hashs.cpp index 92a2428..4a57a03 100644 --- a/src/xRedisClient_hashs.cpp +++ b/src/xRedisClient_hashs.cpp @@ -8,10 +8,8 @@ #include #include -#include "xRedisClient.h" -#include "xRedisPool.h" -#include -#include +#include "xredis.h" + using namespace xrc; bool xRedisClient::hdel(const RedisDBIdx &dbi, const std::string &key, const std::string &field, int64_t &count) diff --git a/src/xRedisClient_keys.cpp b/src/xRedisClient_keys.cpp index 1846142..e576408 100644 --- a/src/xRedisClient_keys.cpp +++ b/src/xRedisClient_keys.cpp @@ -6,10 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include "xredis.h" -#include "xRedisClient.h" -#include "xRedisPool.h" -#include using namespace xrc; bool xRedisClient::del(const RedisDBIdx &dbi, const std::string &key) diff --git a/src/xRedisClient_lists.cpp b/src/xRedisClient_lists.cpp index 57d8941..504e61f 100644 --- a/src/xRedisClient_lists.cpp +++ b/src/xRedisClient_lists.cpp @@ -8,9 +8,7 @@ #include #include -#include -#include "xRedisClient.h" -#include +#include "xredis.h" using namespace xrc; bool xRedisClient::lindex(const RedisDBIdx &dbi, const std::string &key, int64_t index, VALUE &value) diff --git a/src/xRedisClient_pubsub.cpp b/src/xRedisClient_pubsub.cpp index 4222b9c..cfc14c9 100644 --- a/src/xRedisClient_pubsub.cpp +++ b/src/xRedisClient_pubsub.cpp @@ -6,10 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include "xredis.h" -#include "xRedisClient.h" -#include "xRedisPool.h" -#include using namespace xrc; bool xRedisClient::psubscribe(const RedisDBIdx &dbi, const KEYS &patterns, xRedisContext &ctx) diff --git a/src/xRedisClient_sets.cpp b/src/xRedisClient_sets.cpp index 3ab5d1f..d4ec089 100644 --- a/src/xRedisClient_sets.cpp +++ b/src/xRedisClient_sets.cpp @@ -6,7 +6,7 @@ * ---------------------------------------------------------------------------- */ -#include "xRedisClient.h" +#include "xredis.h" using namespace xrc; bool xRedisClient::sadd(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &count) diff --git a/src/xRedisClient_sortedsets.cpp b/src/xRedisClient_sortedsets.cpp index 7e888da..c3e60fa 100644 --- a/src/xRedisClient_sortedsets.cpp +++ b/src/xRedisClient_sortedsets.cpp @@ -6,9 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include "xredis.h" -#include "xRedisClient.h" -#include using namespace xrc; bool xRedisClient::zadd(const RedisDBIdx &dbi, const KEY &key, const VALUES &vValues, int64_t &count) diff --git a/src/xRedisClient_strings.cpp b/src/xRedisClient_strings.cpp index fd03795..93ddffe 100644 --- a/src/xRedisClient_strings.cpp +++ b/src/xRedisClient_strings.cpp @@ -6,11 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include "xredis.h" -#include -#include "xRedisClient.h" -#include "xRedisPool.h" -#include using namespace xrc; bool xRedisClient::psetex(const RedisDBIdx &dbi, const std::string &key, int32_t milliseconds, const std::string &value) diff --git a/src/xRedisClusterClient.cpp b/src/xRedisClusterClient.cpp index 784c6a8..4be4064 100644 --- a/src/xRedisClusterClient.cpp +++ b/src/xRedisClusterClient.cpp @@ -1,5 +1,4 @@ -#include "xRedisClusterClient.h" - +#include "xredis.h" using namespace xrc; static const uint16_t crc16tab[256] = { diff --git a/src/xRedisPool.cpp b/src/xRedisPool.cpp index 12d22a9..f8446bc 100644 --- a/src/xRedisPool.cpp +++ b/src/xRedisPool.cpp @@ -6,6 +6,7 @@ * ---------------------------------------------------------------------------- */ #include +#include "xredis.h" using namespace xrc; diff --git a/test/xredis-test.cpp b/test/xredis-test.cpp index efb04e0..7d3e800 100644 --- a/test/xredis-test.cpp +++ b/test/xredis-test.cpp @@ -5,7 +5,7 @@ #include #include -#include "xredis/xRedisClient.h" +#include "xredis/xredis.h" using namespace xrc; From 3cfcef8de791ae66fd34268596463c10c0b7366b Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:25:02 +0800 Subject: [PATCH 16/24] general style fixup --- examples/demo.cpp | 58 ++-- examples/demo_cluster.cpp | 66 ++-- examples/demo_multi_cluster.cpp | 89 ++--- examples/redis-cluster-client.cpp | 70 ++-- examples/xRedisClusterClient_test.cpp | 37 +-- .../xredis-example-Consistent-hash/CMd5.cpp | 304 +++++++++--------- .../xredis-example-Consistent-hash/CMd5.h | 11 +- .../redis-test.cpp | 136 ++++---- .../xredis-example-Consistent-hash.cpp | 103 +++--- examples/xredis-example.cpp | 75 +++-- 10 files changed, 516 insertions(+), 433 deletions(-) diff --git a/examples/demo.cpp b/examples/demo.cpp index 37e1533..96468c4 100644 --- a/examples/demo.cpp +++ b/examples/demo.cpp @@ -12,60 +12,70 @@ using namespace xrc; // AP Hash Function -unsigned int APHash(const char *str) { +unsigned int APHash(const char *str) +{ unsigned int hash = 0; int i; - for (i=0; *str; i++) { - if ((i& 1) == 0) { + for (i = 0; *str; i++) + { + if ((i & 1) == 0) + { hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); - } else { + } + else + { hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); } } - return (hash& 0x7FFFFFFF); + return (hash & 0x7FFFFFFF); } -enum { - CACHE_TYPE_1, - CACHE_TYPE_2, - CACHE_TYPE_MAX, +enum +{ + CACHE_TYPE_1, + CACHE_TYPE_2, + CACHE_TYPE_MAX, }; /* 配置单个redis存储节点 */ -RedisNode RedisList1[1]= -{ - {0,"127.0.0.1", 7000, "", 8, 5, 0} -}; +RedisNode RedisList1[1] = + { + {0, "127.0.0.1", 7000, "", 8, 5, 0}}; +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; -int main(int argc, char **argv) { - (void)argc;(void)argv; - xRedisClient xRedis; xRedis.Init(CACHE_TYPE_MAX); xRedis.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 1, CACHE_TYPE_1); - + const char *key = "test"; const char *value = "test value"; RedisDBIdx dbi(&xRedis); dbi.CreateDBIndex(key, APHash, CACHE_TYPE_1); - bool bRet = xRedis.set(dbi, key, value); - if(bRet){ + bool bRet = xRedis.set(dbi, key, value); + if (bRet) + { printf("success \r\n"); - } else { + } + else + { printf("error [%s] \r\n", dbi.GetErrInfo()); } std::string strValue; bRet = xRedis.get(dbi, key, strValue); - if (bRet) { + if (bRet) + { printf("%s \r\n", strValue.c_str()); - } else { + } + else + { printf("error [%s] \r\n", dbi.GetErrInfo()); } return 0; } - - diff --git a/examples/demo_cluster.cpp b/examples/demo_cluster.cpp index c28d95b..32fd8bb 100644 --- a/examples/demo_cluster.cpp +++ b/examples/demo_cluster.cpp @@ -1,5 +1,5 @@ - /** \example demo_cluster.cpp +/** \example demo_cluster.cpp * This is an example of how to use the xRedis. *
Connect to a redis cluster which contains three redis node *
More details about this example. @@ -11,36 +11,43 @@ using namespace xrc; // AP Hash Function -unsigned int APHash(const char *str) { +unsigned int APHash(const char *str) +{ unsigned int hash = 0; int i; - for (i=0; *str; i++) { - if ((i& 1) == 0) { + for (i = 0; *str; i++) + { + if ((i & 1) == 0) + { hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); - } else { + } + else + { hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); } } - return (hash& 0x7FFFFFFF); + return (hash & 0x7FFFFFFF); } -enum { - CACHE_TYPE_1, - CACHE_TYPE_2, - CACHE_TYPE_MAX, +enum +{ + CACHE_TYPE_1, + CACHE_TYPE_2, + CACHE_TYPE_MAX, }; /* 配置一个redis分片存储集群:共三个存储主节点 */ -RedisNode RedisList1[3]= +RedisNode RedisList1[3] = + { + {0, "127.0.0.1", 7000, "", 2, 5, 0}, + {1, "127.0.0.1", 7000, "", 2, 5, 0}, + {2, "127.0.0.1", 7000, "", 2, 5, 0}}; + +int main(int argc, char **argv) { - {0,"127.0.0.1", 7000, "", 2, 5, 0}, - {1,"127.0.0.1", 7000, "", 2, 5, 0}, - {2,"127.0.0.1", 7000, "", 2, 5, 0} -}; + (void)argc; + (void)argv; -int main(int argc, char **argv) { - (void)argc;(void)argv; - xRedisClient xRedis; xRedis.Init(CACHE_TYPE_MAX); xRedis.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 3, CACHE_TYPE_1); @@ -50,26 +57,31 @@ int main(int argc, char **argv) { RedisDBIdx dbi(&xRedis); bool bRet = dbi.CreateDBIndex(key, APHash, CACHE_TYPE_1); - if (!bRet) { + if (!bRet) + { return 0; } bRet = xRedis.set(dbi, key, value); - if (bRet){ - printf("success \r\n"); - } else { + if (bRet) + { + printf("success \r\n"); + } + else + { printf("error [%s] \r\n", dbi.GetErrInfo()); - } + } std::string strValue; bRet = xRedis.get(dbi, key, strValue); - if (bRet) { + if (bRet) + { printf("%s \r\n", strValue.c_str()); - } else { + } + else + { printf("error [%s] \r\n", dbi.GetErrInfo()); } return 0; } - - diff --git a/examples/demo_multi_cluster.cpp b/examples/demo_multi_cluster.cpp index 308b48a..9195282 100644 --- a/examples/demo_multi_cluster.cpp +++ b/examples/demo_multi_cluster.cpp @@ -1,7 +1,6 @@ - - /** \example demo_multi_cluster.cpp +/** \example demo_multi_cluster.cpp * This is an example of how to use the xRedis. *
connect to multi redis clusters *
every redis cluster have multi redis server nodes @@ -9,81 +8,93 @@ *
More details about this example. */ -#include +#include #include "xRedisClient.h" using namespace xrc; // AP Hash Function -unsigned int APHash(const char *str) { +unsigned int APHash(const char *str) +{ unsigned int hash = 0; int i; - for (i=0; *str; i++) { - if ((i& 1) == 0) { + for (i = 0; *str; i++) + { + if ((i & 1) == 0) + { hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); - } else { + } + else + { hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); } } - return (hash& 0x7FFFFFFF); + return (hash & 0x7FFFFFFF); } -enum { - CACHE_TYPE_1, - CACHE_TYPE_2, - CACHE_TYPE_MAX, +enum +{ + CACHE_TYPE_1, + CACHE_TYPE_2, + CACHE_TYPE_MAX, }; /* 有3个redis分片存储节点的集群*/ -RedisNode RedisList1[3]= -{ - {0,"10.10.0.1", 7000, "", 2, 5, 0}, - {1,"10.10.0.2", 7000, "", 2, 5, 0}, - {2,"10.10.0.3", 7000, "", 2, 5, 0} -}; +RedisNode RedisList1[3] = + { + {0, "10.10.0.1", 7000, "", 2, 5, 0}, + {1, "10.10.0.2", 7000, "", 2, 5, 0}, + {2, "10.10.0.3", 7000, "", 2, 5, 0}}; /* 有5个redis分片存储节点的集群 */ -RedisNode RedisList2[5]= -{ - {0,"10.10.1.1", 7000, "", 2, 5, 0}, - {1,"10.10.1.2", 7000, "", 2, 5, 0}, - {2,"10.10.1.3", 7000, "", 2, 5, 0}, - {3,"10.10.1.4", 7000, "", 2, 5, 0}, - {4,"10.10.1.5", 7000, "", 2, 5, 0}, +RedisNode RedisList2[5] = + { + {0, "10.10.1.1", 7000, "", 2, 5, 0}, + {1, "10.10.1.2", 7000, "", 2, 5, 0}, + {2, "10.10.1.3", 7000, "", 2, 5, 0}, + {3, "10.10.1.4", 7000, "", 2, 5, 0}, + {4, "10.10.1.5", 7000, "", 2, 5, 0}, }; -int main(int argc, char **argv) { - (void)argc;(void)argv; - +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; + xRedisClient xRedis; xRedis.Init(CACHE_TYPE_MAX); - xRedis.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode),3, CACHE_TYPE_1); + xRedis.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 3, CACHE_TYPE_1); xRedis.ConnectRedisCache(RedisList2, sizeof(RedisList2) / sizeof(RedisNode), 5, CACHE_TYPE_2); - + const char *key = "test"; const char *value = "test value"; RedisDBIdx dbi(&xRedis); bool bRet = dbi.CreateDBIndex(key, APHash, CACHE_TYPE_1); - if (!bRet) { + if (!bRet) + { return 0; } bRet = xRedis.set(dbi, key, value); - if (bRet){ - printf("success \r\n"); - } else { + if (bRet) + { + printf("success \r\n"); + } + else + { printf("error [%s] \r\n", dbi.GetErrInfo()); - } + } std::string strValue; bRet = xRedis.get(dbi, key, strValue); - if (bRet) { + if (bRet) + { printf("%s \r\n", strValue.c_str()); - } else { + } + else + { printf("error [%s] \r\n", dbi.GetErrInfo()); } return 0; } - - diff --git a/examples/redis-cluster-client.cpp b/examples/redis-cluster-client.cpp index 5926e37..e4382b1 100644 --- a/examples/redis-cluster-client.cpp +++ b/examples/redis-cluster-client.cpp @@ -1,50 +1,80 @@ -#include +#include #include #include #include #include "xRedisClusterClient.h" +using std::cin; using std::cout; using std::endl; -using std::cin; -int main(int argc, char **argv) { - (void)argc;(void)argv; - +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; + xRedisClusterClient redisclient; - + bool bRet = redisclient.ConnectRedis(argv[1], atoi(argv[2]), 2); - if(!bRet) { + if (!bRet) + { return -1; } - std::string strInput; - while (true) { + std::string strInput; + while (true) + { cout << "\033[32mxRedis> \033[0m"; getline(cin, strInput); if (!cin) return 0; - if (strInput.length() < 1) { + if (strInput.length() < 1) + { cout << "input again" << endl; - } else { + } + else + { RedisResult result; VSTRING vDataIn; xRedisClusterClient::str2Vect(strInput.c_str(), vDataIn, " "); redisclient.RedisCommandArgv(vDataIn, result); - switch (result.type()){ - case REDIS_REPLY_INTEGER:{ printf("%lld \r\n", result.integer()); break;} - case REDIS_REPLY_NIL: { printf("%lld %s \r\n", result.integer(), result.str()); break; } - case REDIS_REPLY_STATUS: { printf("%s \r\n", result.str()); break; } - case REDIS_REPLY_ERROR: { printf("%s \r\n", result.str()); break; } - case REDIS_REPLY_STRING: { printf("%s \r\n", result.str()); break; } - case REDIS_REPLY_ARRAY: { - for (size_t i = 0; i < result.elements(); ++i) { + switch (result.type()) + { + case REDIS_REPLY_INTEGER: + { + printf("%lld \r\n", result.integer()); + break; + } + case REDIS_REPLY_NIL: + { + printf("%lld %s \r\n", result.integer(), result.str()); + break; + } + case REDIS_REPLY_STATUS: + { + printf("%s \r\n", result.str()); + break; + } + case REDIS_REPLY_ERROR: + { + printf("%s \r\n", result.str()); + break; + } + case REDIS_REPLY_STRING: + { + printf("%s \r\n", result.str()); + break; + } + case REDIS_REPLY_ARRAY: + { + for (size_t i = 0; i < result.elements(); ++i) + { RedisResult::RedisReply reply = result.element(i); printf("type:%d integer:%lld str:%s \r\n", - reply.type(), reply.integer(), reply.str()); + reply.type(), reply.integer(), reply.str()); } break; } diff --git a/examples/xRedisClusterClient_test.cpp b/examples/xRedisClusterClient_test.cpp index dc67716..7ca2c7f 100644 --- a/examples/xRedisClusterClient_test.cpp +++ b/examples/xRedisClusterClient_test.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include @@ -6,40 +6,31 @@ using namespace xrc; -int main(int argc, char **argv) { - (void)argc;(void)argv; - +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; + xRedisClusterClient redisclient; //bool bRet = redisclient.ConnectRedis("127.0.0.1", 7000, 4); bool bRet = redisclient.ConnectRedis(argv[1], atoi(argv[2]), 4); - if(!bRet) { + if (!bRet) + { return -1; } RedisResult result; redisclient.RedisCommand(result, "hgetall %s", "htest"); - + printf("type:%d integer:%lld str:%s \r\n", - result.type(), result.integer(), result.str()); - - for(size_t i=0; i< result.elements();++i) { + result.type(), result.integer(), result.str()); + + for (size_t i = 0; i < result.elements(); ++i) + { RedisResult::RedisReply reply = result.element(i); printf("type:%d integer:%lld str:%s \r\n", - reply.type(), reply.integer(), reply.str()); + reply.type(), reply.integer(), reply.str()); } - return 0; } - - - - - - - - - - - - diff --git a/examples/xredis-example-Consistent-hash/CMd5.cpp b/examples/xredis-example-Consistent-hash/CMd5.cpp index 9ffdc2e..91c2db9 100644 --- a/examples/xredis-example-Consistent-hash/CMd5.cpp +++ b/examples/xredis-example-Consistent-hash/CMd5.cpp @@ -1,87 +1,87 @@ #include "CMd5.h" #include -#include +#include -#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ +#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ #ifdef ARCH_IS_BIG_ENDIAN -# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) +#define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) #else -# define BYTE_ORDER 0 +#define BYTE_ORDER 0 #endif #define T_MASK ((md5_word_t)~0) #define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) #define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) -#define T3 0x242070db +#define T3 0x242070db #define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) #define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) -#define T6 0x4787c62a +#define T6 0x4787c62a #define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) #define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) -#define T9 0x698098d8 +#define T9 0x698098d8 #define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) #define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) #define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) -#define T13 0x6b901122 +#define T13 0x6b901122 #define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) #define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) -#define T16 0x49b40821 +#define T16 0x49b40821 #define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) #define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) -#define T19 0x265e5a51 +#define T19 0x265e5a51 #define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) #define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) -#define T22 0x02441453 +#define T22 0x02441453 #define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) #define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) -#define T25 0x21e1cde6 +#define T25 0x21e1cde6 #define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) #define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) -#define T28 0x455a14ed +#define T28 0x455a14ed #define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) #define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) -#define T31 0x676f02d9 +#define T31 0x676f02d9 #define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) #define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) #define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) -#define T35 0x6d9d6122 +#define T35 0x6d9d6122 #define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) #define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) -#define T38 0x4bdecfa9 +#define T38 0x4bdecfa9 #define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) #define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) -#define T41 0x289b7ec6 +#define T41 0x289b7ec6 #define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) #define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) -#define T44 0x04881d05 +#define T44 0x04881d05 #define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) #define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) -#define T47 0x1fa27cf8 +#define T47 0x1fa27cf8 #define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) #define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) -#define T50 0x432aff97 +#define T50 0x432aff97 #define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) #define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) -#define T53 0x655b59c3 +#define T53 0x655b59c3 #define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) #define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) #define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) -#define T57 0x6fa87e4f +#define T57 0x6fa87e4f #define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) #define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) -#define T60 0x4e0811a1 +#define T60 0x4e0811a1 #define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) #define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) -#define T63 0x2ad7d2bb +#define T63 0x2ad7d2bb #define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) - static void md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) { md5_word_t - a = pms->abcd[0], b = pms->abcd[1], - c = pms->abcd[2], d = pms->abcd[3]; + a = pms->abcd[0], + b = pms->abcd[1], + c = pms->abcd[2], d = pms->abcd[3]; md5_word_t t; #if BYTE_ORDER > 0 /* Define storage only for big-endian CPUs. */ @@ -94,51 +94,54 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) { #if BYTE_ORDER == 0 - /* + /* * Determine dynamically whether this is a big-endian or * little-endian machine, since we can use a more efficient * algorithm on the latter. */ - static const int w = 1; + static const int w = 1; - if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ + if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ #endif -#if BYTE_ORDER <= 0 /* little-endian */ - { - /* +#if BYTE_ORDER <= 0 /* little-endian */ + { + /* * On little-endian machines, we can process properly aligned * data without copying it. */ - if (!((data - (const md5_byte_t *)0) & 3)) { - /* data are properly aligned */ - X = (const md5_word_t *)data; - } else { - /* not aligned */ - memcpy(xbuf, data, 64); - X = xbuf; - } - } + if (!((data - (const md5_byte_t *)0) & 3)) + { + /* data are properly aligned */ + X = (const md5_word_t *)data; + } + else + { + /* not aligned */ + memcpy(xbuf, data, 64); + X = xbuf; + } + } #endif #if BYTE_ORDER == 0 - else /* dynamic big-endian */ + else /* dynamic big-endian */ #endif -#if BYTE_ORDER >= 0 /* big-endian */ - { - /* +#if BYTE_ORDER >= 0 /* big-endian */ + { + /* * On big-endian machines, we must arrange the bytes in the * right order. */ - const md5_byte_t *xp = data; - int i; + const md5_byte_t *xp = data; + int i; -# if BYTE_ORDER == 0 - X = xbuf; /* (dynamic only) */ -# else -# define xbuf X /* (static only) */ -# endif - for (i = 0; i < 16; ++i, xp += 4) - xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); - } +#if BYTE_ORDER == 0 + X = xbuf; /* (dynamic only) */ +#else +#define xbuf X /* (static only) */ +#endif + for (i = 0; i < 16; ++i, xp += 4) + xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); + } #endif } @@ -148,107 +151,107 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) /* Let [abcd k s i] denote the operation a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ #define F(x, y, z) (((x) & (y)) | (~(x) & (z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + F(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b +#define SET(a, b, c, d, k, s, Ti) \ + t = a + F(b, c, d) + X[k] + Ti; \ + a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 7, T1); - SET(d, a, b, c, 1, 12, T2); - SET(c, d, a, b, 2, 17, T3); - SET(b, c, d, a, 3, 22, T4); - SET(a, b, c, d, 4, 7, T5); - SET(d, a, b, c, 5, 12, T6); - SET(c, d, a, b, 6, 17, T7); - SET(b, c, d, a, 7, 22, T8); - SET(a, b, c, d, 8, 7, T9); - SET(d, a, b, c, 9, 12, T10); + SET(a, b, c, d, 0, 7, T1); + SET(d, a, b, c, 1, 12, T2); + SET(c, d, a, b, 2, 17, T3); + SET(b, c, d, a, 3, 22, T4); + SET(a, b, c, d, 4, 7, T5); + SET(d, a, b, c, 5, 12, T6); + SET(c, d, a, b, 6, 17, T7); + SET(b, c, d, a, 7, 22, T8); + SET(a, b, c, d, 8, 7, T9); + SET(d, a, b, c, 9, 12, T10); SET(c, d, a, b, 10, 17, T11); SET(b, c, d, a, 11, 22, T12); - SET(a, b, c, d, 12, 7, T13); + SET(a, b, c, d, 12, 7, T13); SET(d, a, b, c, 13, 12, T14); SET(c, d, a, b, 14, 17, T15); SET(b, c, d, a, 15, 22, T16); #undef SET - /* Round 2. */ - /* Let [abcd k s i] denote the operation + /* Round 2. */ + /* Let [abcd k s i] denote the operation a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ #define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + G(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 1, 5, T17); - SET(d, a, b, c, 6, 9, T18); +#define SET(a, b, c, d, k, s, Ti) \ + t = a + G(b, c, d) + X[k] + Ti; \ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 1, 5, T17); + SET(d, a, b, c, 6, 9, T18); SET(c, d, a, b, 11, 14, T19); - SET(b, c, d, a, 0, 20, T20); - SET(a, b, c, d, 5, 5, T21); - SET(d, a, b, c, 10, 9, T22); + SET(b, c, d, a, 0, 20, T20); + SET(a, b, c, d, 5, 5, T21); + SET(d, a, b, c, 10, 9, T22); SET(c, d, a, b, 15, 14, T23); - SET(b, c, d, a, 4, 20, T24); - SET(a, b, c, d, 9, 5, T25); - SET(d, a, b, c, 14, 9, T26); - SET(c, d, a, b, 3, 14, T27); - SET(b, c, d, a, 8, 20, T28); - SET(a, b, c, d, 13, 5, T29); - SET(d, a, b, c, 2, 9, T30); - SET(c, d, a, b, 7, 14, T31); + SET(b, c, d, a, 4, 20, T24); + SET(a, b, c, d, 9, 5, T25); + SET(d, a, b, c, 14, 9, T26); + SET(c, d, a, b, 3, 14, T27); + SET(b, c, d, a, 8, 20, T28); + SET(a, b, c, d, 13, 5, T29); + SET(d, a, b, c, 2, 9, T30); + SET(c, d, a, b, 7, 14, T31); SET(b, c, d, a, 12, 20, T32); #undef SET - /* Round 3. */ - /* Let [abcd k s t] denote the operation + /* Round 3. */ + /* Let [abcd k s t] denote the operation a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ #define H(x, y, z) ((x) ^ (y) ^ (z)) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + H(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 5, 4, T33); - SET(d, a, b, c, 8, 11, T34); +#define SET(a, b, c, d, k, s, Ti) \ + t = a + H(b, c, d) + X[k] + Ti; \ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 5, 4, T33); + SET(d, a, b, c, 8, 11, T34); SET(c, d, a, b, 11, 16, T35); SET(b, c, d, a, 14, 23, T36); - SET(a, b, c, d, 1, 4, T37); - SET(d, a, b, c, 4, 11, T38); - SET(c, d, a, b, 7, 16, T39); + SET(a, b, c, d, 1, 4, T37); + SET(d, a, b, c, 4, 11, T38); + SET(c, d, a, b, 7, 16, T39); SET(b, c, d, a, 10, 23, T40); - SET(a, b, c, d, 13, 4, T41); - SET(d, a, b, c, 0, 11, T42); - SET(c, d, a, b, 3, 16, T43); - SET(b, c, d, a, 6, 23, T44); - SET(a, b, c, d, 9, 4, T45); + SET(a, b, c, d, 13, 4, T41); + SET(d, a, b, c, 0, 11, T42); + SET(c, d, a, b, 3, 16, T43); + SET(b, c, d, a, 6, 23, T44); + SET(a, b, c, d, 9, 4, T45); SET(d, a, b, c, 12, 11, T46); SET(c, d, a, b, 15, 16, T47); - SET(b, c, d, a, 2, 23, T48); + SET(b, c, d, a, 2, 23, T48); #undef SET - /* Round 4. */ - /* Let [abcd k s t] denote the operation + /* Round 4. */ + /* Let [abcd k s t] denote the operation a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ #define I(x, y, z) ((y) ^ ((x) | ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + I(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 6, T49); - SET(d, a, b, c, 7, 10, T50); +#define SET(a, b, c, d, k, s, Ti) \ + t = a + I(b, c, d) + X[k] + Ti; \ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 0, 6, T49); + SET(d, a, b, c, 7, 10, T50); SET(c, d, a, b, 14, 15, T51); - SET(b, c, d, a, 5, 21, T52); - SET(a, b, c, d, 12, 6, T53); - SET(d, a, b, c, 3, 10, T54); + SET(b, c, d, a, 5, 21, T52); + SET(a, b, c, d, 12, 6, T53); + SET(d, a, b, c, 3, 10, T54); SET(c, d, a, b, 10, 15, T55); - SET(b, c, d, a, 1, 21, T56); - SET(a, b, c, d, 8, 6, T57); + SET(b, c, d, a, 1, 21, T56); + SET(a, b, c, d, 8, 6, T57); SET(d, a, b, c, 15, 10, T58); - SET(c, d, a, b, 6, 15, T59); + SET(c, d, a, b, 6, 15, T59); SET(b, c, d, a, 13, 21, T60); - SET(a, b, c, d, 4, 6, T61); + SET(a, b, c, d, 4, 6, T61); SET(d, a, b, c, 11, 10, T62); - SET(c, d, a, b, 2, 15, T63); - SET(b, c, d, a, 9, 21, T64); + SET(c, d, a, b, 2, 15, T63); + SET(b, c, d, a, 9, 21, T64); #undef SET - /* Then perform the following additions. (That is increment each + /* Then perform the following additions. (That is increment each of the four registers by the value it had before this block was started.) */ pms->abcd[0] += a; @@ -257,8 +260,7 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) pms->abcd[3] += d; } -void -md5_init(md5_state_t *pms) +void md5_init(md5_state_t *pms) { pms->count[0] = pms->count[1] = 0; pms->abcd[0] = 0x67452301; @@ -267,8 +269,7 @@ md5_init(md5_state_t *pms) pms->abcd[3] = 0x10325476; } -void -md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) +void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) { const md5_byte_t *p = data; int left = nbytes; @@ -276,62 +277,62 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) md5_word_t nbits = (md5_word_t)(nbytes << 3); if (nbytes <= 0) - return; + return; /* Update the message length. */ pms->count[1] += nbytes >> 29; pms->count[0] += nbits; if (pms->count[0] < nbits) - pms->count[1]++; + pms->count[1]++; /* Process an initial partial block. */ - if (offset) { - int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); + if (offset) + { + int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - memcpy(pms->buf + offset, p, copy); - if (offset + copy < 64) - return; - p += copy; - left -= copy; - md5_process(pms, pms->buf); + memcpy(pms->buf + offset, p, copy); + if (offset + copy < 64) + return; + p += copy; + left -= copy; + md5_process(pms, pms->buf); } /* Process full blocks. */ for (; left >= 64; p += 64, left -= 64) - md5_process(pms, p); + md5_process(pms, p); /* Process a final partial block. */ if (left) - memcpy(pms->buf, p, left); + memcpy(pms->buf, p, left); } -void -md5_finish(md5_state_t *pms, md5_byte_t digest[16]) +void md5_finish(md5_state_t *pms, md5_byte_t digest[16]) { static const md5_byte_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; md5_byte_t data[8]; int i; /* Save the length before padding. */ for (i = 0; i < 8; ++i) - data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); + data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); /* Pad to 56 bytes mod 64. */ md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); /* Append the length. */ md5_append(pms, data, 8); for (i = 0; i < 16; ++i) - digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); + digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); } void getMd5String(char *inbuf, md5_byte_t digest[16]) { - for (int j = 0; j < 16; j++) { - sprintf(inbuf + j * 2, "%02x", ((unsigned char*)digest)[j]); + for (int j = 0; j < 16; j++) + { + sprintf(inbuf + j * 2, "%02x", ((unsigned char *)digest)[j]); } } @@ -345,4 +346,3 @@ void getMd5Str(const char *str, char *strhash) getMd5String(strhash, digest); } - diff --git a/examples/xredis-example-Consistent-hash/CMd5.h b/examples/xredis-example-Consistent-hash/CMd5.h index 63926dc..bd2ad25 100644 --- a/examples/xredis-example-Consistent-hash/CMd5.h +++ b/examples/xredis-example-Consistent-hash/CMd5.h @@ -2,13 +2,14 @@ #define md5_INCLUDED typedef unsigned char md5_byte_t; /* 8-bit byte */ -typedef unsigned int md5_word_t; /* 32-bit word */ +typedef unsigned int md5_word_t; /* 32-bit word */ /* Define the state of the MD5 Algorithm. */ -typedef struct md5_state_s { - md5_word_t count[2]; /* message length in bits, lsw first */ - md5_word_t abcd[4]; /* digest buffer */ - md5_byte_t buf[64]; /* accumulate block */ +typedef struct md5_state_s +{ + md5_word_t count[2]; /* message length in bits, lsw first */ + md5_word_t abcd[4]; /* digest buffer */ + md5_byte_t buf[64]; /* accumulate block */ } md5_state_t; void md5_init(md5_state_t *pms); diff --git a/examples/xredis-example-Consistent-hash/redis-test.cpp b/examples/xredis-example-Consistent-hash/redis-test.cpp index 7bd842f..e89cfc9 100644 --- a/examples/xredis-example-Consistent-hash/redis-test.cpp +++ b/examples/xredis-example-Consistent-hash/redis-test.cpp @@ -1,19 +1,24 @@ -#include +#include #include -#include +#include #include "CMd5.h" #include "xRedisClient.h" // AP Hash Function -unsigned int APHash(const char *str) { +unsigned int APHash(const char *str) +{ unsigned int hash = 0; int i; - for (i = 0; *str; i++) { - if ((i & 1) == 0) { + for (i = 0; *str; i++) + { + if ((i & 1) == 0) + { hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); - } else { + } + else + { hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); } } @@ -21,10 +26,8 @@ unsigned int APHash(const char *str) { return (hash & 0x7FFFFFFF); } - - -#include -#include +#include +#include #include #include #include @@ -37,28 +40,29 @@ typedef std::map USSMAP; typedef std::list SLIST; typedef std::map SUMAP; -typedef unsigned int(*HASHFUNC)(const char *str); - +typedef unsigned int (*HASHFUNC)(const char *str); - -struct vnode_t { +struct vnode_t +{ unsigned int id; string rIden; const RedisNode *data; }; -typedef std::map VNODEMAP; +typedef std::map VNODEMAP; typedef std::map RNODELIST; -class ConHashIdx :public RedisDBIdx { +class ConHashIdx : public RedisDBIdx +{ private: - USMAP _node_info; // nodeid to server - USSMAP _node_slot; // nodeid to keys - HASHFUNC _hash; // hash function - int _vnode_num; // vnode number per server + USMAP _node_info; // nodeid to server + USSMAP _node_slot; // nodeid to keys + HASHFUNC _hash; // hash function + int _vnode_num; // vnode number per server VNODEMAP vNodeMap; RNODELIST rNodeMap; + public: ConHashIdx(const RedisNode *rNode, int size, HASHFUNC hash, int vnode_num); ~ConHashIdx(); @@ -66,33 +70,35 @@ class ConHashIdx :public RedisDBIdx { void del_server(const RedisNode *rNode); unsigned int get_index(const char *key); + private: bool _add_node(const RedisNode *rNode, int vnode_num); - }; - -ConHashIdx::ConHashIdx(const RedisNode *rNode, int size, HASHFUNC hash, int vnode_num) { +ConHashIdx::ConHashIdx(const RedisNode *rNode, int size, HASHFUNC hash, int vnode_num) +{ _hash = hash; _vnode_num = vnode_num; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { _add_node(&rNode[i], vnode_num); } } ConHashIdx::~ConHashIdx() { - } -bool ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) { +bool ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) +{ - char szIden[128] = { 0 }; + char szIden[128] = {0}; VNODEMAP vMap; getMd5Str(rNode->host, szIden); - for (int i = 0; i < vnode_num; i++) { + for (int i = 0; i < vnode_num; i++) + { char sztmp[256] = {0}; char vNodekey[256] = {0}; sprintf(sztmp, "%s-%06d", szIden, i); @@ -103,11 +109,14 @@ bool ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) { pVnode->data = rNode; pVnode->rIden = szIden; printf("%s %u %s \r\n", vNodekey, pVnode->id, pVnode->data->host); - std::pair< VNODEMAP::iterator, bool > ret; + std::pair ret; ret = vNodeMap.insert(make_pair(hval, pVnode)); - if (ret.second) { + if (ret.second) + { vMap.insert(make_pair(hval, pVnode)); - } else { + } + else + { printf("�ڵ��ͻ: %s-%u \r\n", vNodekey, hval); delete pVnode; return false; @@ -115,14 +124,14 @@ bool ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) { } rNodeMap.insert(make_pair(szIden, vMap)); - } unsigned int ConHashIdx::get_index(const char *key) { unsigned int hval = _hash(key); VNODEMAP::iterator iter = vNodeMap.upper_bound(hval); - if (iter == vNodeMap.end() && 0 != vNodeMap.size()) { + if (iter == vNodeMap.end() && 0 != vNodeMap.size()) + { iter = vNodeMap.begin(); } @@ -131,38 +140,42 @@ unsigned int ConHashIdx::get_index(const char *key) void ConHashIdx::del_server(const RedisNode *rNode) { - char szIden[128] = { 0 }; + char szIden[128] = {0}; getMd5Str(rNode->host, szIden); VNODEMAP::iterator iter = vNodeMap.begin(); - for (;iter!=vNodeMap.end();){ - if (0 == strcasecmp(szIden, iter->second->rIden.c_str())) { + for (; iter != vNodeMap.end();) + { + if (0 == strcasecmp(szIden, iter->second->rIden.c_str())) + { vNodeMap.erase(iter++); - } else { + } + else + { iter++; } } } RedisNode RedisList1[3] = -{ - { 0, "127.0.0.1", 6379, "", 2, 5 }, - { 1, "127.0.0.2", 6379, "", 2, 5 }, - { 2, "127.0.0.3", 6379, "", 2, 5 } -}; + { + {0, "127.0.0.1", 6379, "", 2, 5}, + {1, "127.0.0.2", 6379, "", 2, 5}, + {2, "127.0.0.3", 6379, "", 2, 5}}; RedisNode RedisList2[5] = -{ - { 0, "127.0.0.1", 6379, "", 2, 5 }, - { 1, "127.0.0.2", 6379, "", 2, 5 }, - { 2, "127.0.0.3", 6379, "", 2, 5 }, - { 3, "127.0.0.4", 6379, "", 2, 5 }, - { 4, "127.0.0.5", 6379, "", 2, 5 }, + { + {0, "127.0.0.1", 6379, "", 2, 5}, + {1, "127.0.0.2", 6379, "", 2, 5}, + {2, "127.0.0.3", 6379, "", 2, 5}, + {3, "127.0.0.4", 6379, "", 2, 5}, + {4, "127.0.0.5", 6379, "", 2, 5}, }; #define CACHE_TYPE_1 1 #define CACHE_TYPE_2 2 -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ xRedisClient xRedis; xRedis.Init(3); @@ -171,27 +184,31 @@ int main(int argc, char **argv) { ConHashIdx cIdx(RedisList2, 5, APHash, 10); - for (int i = 0; i < 100; ++i) { - char szKey[256] = { 0 }; - char szHash[256] = { 0 }; + for (int i = 0; i < 100; ++i) + { + char szKey[256] = {0}; + char szHash[256] = {0}; sprintf(szKey, "test_%d_%u", i * 8888, i + 888); getMd5Str(szKey, szHash); printf("%s index: %u \r\n", szKey, cIdx.get_index(szHash)); } - for (int n = 0; n < 1000; n++) { - char szKey[256] = { 0 }; + for (int n = 0; n < 1000; n++) + { + char szKey[256] = {0}; sprintf(szKey, "test_%d", n); RedisDBIdx dbi(&xRedis); dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); bool bRet = xRedis.set(dbi, szKey, "hello redis!"); - if (!bRet){ + if (!bRet) + { printf(" %s %s \n", szKey, dbi.GetErrInfo()); } } - for (int n = 0; n < 1000; n++) { - char szKey[256] = { 0 }; + for (int n = 0; n < 1000; n++) + { + char szKey[256] = {0}; sprintf(szKey, "test_%d", n); RedisDBIdx dbi(&xRedis); dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); @@ -201,7 +218,8 @@ int main(int argc, char **argv) { } int n = 10; - while (n--) { + while (n--) + { xRedis.KeepAlive(); usleep(1000 * 1000 * 10); } @@ -210,5 +228,3 @@ int main(int argc, char **argv) { return 0; } - - diff --git a/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp b/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp index 32e7b74..cfad8f6 100644 --- a/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp +++ b/examples/xredis-example-Consistent-hash/xredis-example-Consistent-hash.cpp @@ -1,11 +1,12 @@ -#include +#include #include #include #include "xRedisClient.h" // AP Hash Function -unsigned int APHash(const char *str) { +unsigned int APHash(const char *str) +{ unsigned int hash = 0; int i; @@ -24,10 +25,8 @@ unsigned int APHash(const char *str) { return (hash & 0x7FFFFFFF); } - - -#include -#include +#include +#include #include #include #include @@ -40,23 +39,23 @@ typedef std::map USSMAP; typedef std::list SLIST; typedef std::map SUMAP; -typedef unsigned int(*HASHFUNC)(const char *str); +typedef unsigned int (*HASHFUNC)(const char *str); - -struct vnode_t { +struct vnode_t +{ unsigned int id; const RedisNode *data; }; -typedef std::map VNODEMAP; +typedef std::map VNODEMAP; - -class ConHashIdx :public RedisDBIdx { +class ConHashIdx : public RedisDBIdx +{ private: - USMAP _node_info; // nodeid to server - USSMAP _node_slot; // nodeid to keys - HASHFUNC _hash; // hash function - int _vnode_num; // vnode number per server + USMAP _node_info; // nodeid to server + USSMAP _node_slot; // nodeid to keys + HASHFUNC _hash; // hash function + int _vnode_num; // vnode number per server VNODEMAP vNodeMap; @@ -68,13 +67,15 @@ class ConHashIdx :public RedisDBIdx { std::string get_server(const std::string &key); unsigned int get_index(const char *key); + private: void _add_node(const RedisNode *rNode, int vnode_num); - }; -void ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) { - for (int i = 0; i < vnode_num; i++) { +void ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) +{ + for (int i = 0; i < vnode_num; i++) + { char buf[256]; sprintf(buf, "%s-%010d-%u", rNode->host, i, time(NULL)); unsigned int hval = _hash(buf); @@ -86,25 +87,27 @@ void ConHashIdx::_add_node(const RedisNode *rNode, int vnode_num) { } } -ConHashIdx::ConHashIdx(const RedisNode *rNode, int size, HASHFUNC hash, int vnode_num) { +ConHashIdx::ConHashIdx(const RedisNode *rNode, int size, HASHFUNC hash, int vnode_num) +{ _hash = hash; _vnode_num = vnode_num; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { _add_node(&rNode[i], vnode_num); } } ConHashIdx::~ConHashIdx() { - } unsigned int ConHashIdx::get_index(const char *key) { unsigned int hval = _hash(key); VNODEMAP::iterator iter = vNodeMap.upper_bound(hval); - if (iter == vNodeMap.end() && 0 != vNodeMap.size()) { + if (iter == vNodeMap.end() && 0 != vNodeMap.size()) + { iter = vNodeMap.begin(); } @@ -115,7 +118,8 @@ std::string ConHashIdx::get_server(const std::string &key) { unsigned int hval = _hash(key.c_str()); USMAP::iterator iter = _node_info.upper_bound(hval); - if (iter == _node_info.end() && 0 != _node_info.size()) { + if (iter == _node_info.end() && 0 != _node_info.size()) + { iter = _node_info.begin(); } @@ -123,25 +127,25 @@ std::string ConHashIdx::get_server(const std::string &key) } RedisNode RedisList1[3] = -{ - { 0, "127.0.0.1", 6379, "", 2, 5 }, - { 1, "127.0.0.2", 6379, "", 2, 5 }, - { 2, "127.0.0.3", 6379, "", 2, 5 } -}; + { + {0, "127.0.0.1", 6379, "", 2, 5}, + {1, "127.0.0.2", 6379, "", 2, 5}, + {2, "127.0.0.3", 6379, "", 2, 5}}; RedisNode RedisList2[5] = -{ - { 0, "127.0.0.1", 6379, "", 2, 5 }, - { 1, "127.0.0.2", 6379, "", 2, 5 }, - { 2, "127.0.0.3", 6379, "", 2, 5 }, - { 3, "127.0.0.4", 6379, "", 2, 5 }, - { 4, "127.0.0.5", 6379, "", 2, 5 }, + { + {0, "127.0.0.1", 6379, "", 2, 5}, + {1, "127.0.0.2", 6379, "", 2, 5}, + {2, "127.0.0.3", 6379, "", 2, 5}, + {3, "127.0.0.4", 6379, "", 2, 5}, + {4, "127.0.0.5", 6379, "", 2, 5}, }; #define CACHE_TYPE_1 1 #define CACHE_TYPE_2 2 -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ xRedisClient xRedis; xRedis.Init(3); @@ -150,27 +154,29 @@ int main(int argc, char **argv) { ConHashIdx cIdx(RedisList2, 5, APHash, 10); - for (int i = 0; i < 100; ++i) { - char szKey[256] = { 0 }; - sprintf(szKey, "test_%d_%u", i*8888, time(NULL)); + for (int i = 0; i < 100; ++i) + { + char szKey[256] = {0}; + sprintf(szKey, "test_%d_%u", i * 8888, time(NULL)); printf("%s index: %u \r\n", szKey, cIdx.get_index(szKey)); } - - - for (int n = 0; n < 1000; n++) { - char szKey[256] = { 0 }; + for (int n = 0; n < 1000; n++) + { + char szKey[256] = {0}; sprintf(szKey, "test_%d", n); RedisDBIdx dbi(&xRedis); dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); bool bRet = xRedis.set(dbi, szKey, "hello redis!"); - if (!bRet){ + if (!bRet) + { printf(" %s %s \n", szKey, dbi.GetErrInfo()); } } - for (int n = 0; n < 1000; n++) { - char szKey[256] = { 0 }; + for (int n = 0; n < 1000; n++) + { + char szKey[256] = {0}; sprintf(szKey, "test_%d", n); RedisDBIdx dbi(&xRedis); dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); @@ -180,7 +186,8 @@ int main(int argc, char **argv) { } int n = 10; - while (n--) { + while (n--) + { xRedis.KeepAlive(); usleep(1000 * 1000 * 10); } @@ -189,5 +196,3 @@ int main(int argc, char **argv) { return 0; } - - diff --git a/examples/xredis-example.cpp b/examples/xredis-example.cpp index abd5872..da47718 100644 --- a/examples/xredis-example.cpp +++ b/examples/xredis-example.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include #include @@ -8,63 +8,72 @@ using namespace xrc; // AP Hash Function -unsigned int APHash(const char *str) { +unsigned int APHash(const char *str) +{ unsigned int hash = 0; int i; - for (i=0; *str; i++) { - if ((i& 1) == 0) { + for (i = 0; *str; i++) + { + if ((i & 1) == 0) + { hash ^= ((hash << 7) ^ (*str++) ^ (hash >> 3)); - } else { + } + else + { hash ^= (~((hash << 11) ^ (*str++) ^ (hash >> 5))); } } - return (hash& 0x7FFFFFFF); + return (hash & 0x7FFFFFFF); } -enum { - CACHE_TYPE_1, - CACHE_TYPE_2, - CACHE_TYPE_MAX, +enum +{ + CACHE_TYPE_1, + CACHE_TYPE_2, + CACHE_TYPE_MAX, }; +RedisNode RedisList1[3] = + { + {0, "127.0.0.1", 7000, "", 2, 5, 0}, + {1, "127.0.0.1", 7000, "", 2, 5, 0}, + {2, "127.0.0.1", 7000, "", 2, 5, 0}}; -RedisNode RedisList1[3]= -{ - {0,"127.0.0.1", 7000, "", 2, 5, 0}, - {1,"127.0.0.1", 7000, "", 2, 5, 0}, - {2,"127.0.0.1", 7000, "", 2, 5, 0} +RedisNode RedisList2[5] = + { + {0, "127.0.0.1", 7000, "", 2, 5, 0}, + {1, "127.0.0.1", 7000, "", 2, 5, 0}, + {2, "127.0.0.1", 7000, "", 2, 5, 0}, + {3, "127.0.0.1", 7000, "", 2, 5, 0}, + {4, "127.0.0.1", 7000, "", 2, 5, 0}, }; -RedisNode RedisList2[5]= +int main(int argc, char **argv) { - {0,"127.0.0.1", 7000, "", 2, 5, 0}, - {1,"127.0.0.1", 7000, "", 2, 5, 0}, - {2,"127.0.0.1", 7000, "", 2, 5, 0}, - {3,"127.0.0.1", 7000, "", 2, 5, 0}, - {4,"127.0.0.1", 7000, "", 2, 5, 0}, -}; -int main(int argc, char **argv) { + (void)argc; + (void)argv; - (void)argc;(void)argv; - xRedisClient xRedis; xRedis.Init(CACHE_TYPE_MAX); xRedis.ConnectRedisCache(RedisList1, sizeof(RedisList1) / sizeof(RedisNode), 3, CACHE_TYPE_1); xRedis.ConnectRedisCache(RedisList2, sizeof(RedisList2) / sizeof(RedisNode), 5, CACHE_TYPE_2); - - for (int n = 0; n<1000; n++) { + + for (int n = 0; n < 1000; n++) + { char szKey[256] = {0}; sprintf(szKey, "test_%d", n); RedisDBIdx dbi(&xRedis); dbi.CreateDBIndex(szKey, APHash, CACHE_TYPE_1); bool bRet = xRedis.set(dbi, szKey, "hello redis!"); - if (!bRet){ + if (!bRet) + { printf(" %s %s \n", szKey, dbi.GetErrInfo()); } } - for (int n = 0; n<1000; n++) { + for (int n = 0; n < 1000; n++) + { char szKey[256] = {0}; sprintf(szKey, "test_%d", n); RedisDBIdx dbi(&xRedis); @@ -73,17 +82,15 @@ int main(int argc, char **argv) { xRedis.get(dbi, szKey, strValue); printf("%s \r\n", strValue.c_str()); } - int n = 10; - while (n--) { + while (n--) + { xRedis.Keepalive(); - usleep(1000*1000*10); + usleep(1000 * 1000 * 10); } xRedis.Release(); return 0; } - - From 364fd42d2cd3484ef4ffa5d4a55cc2ea9949076c Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:25:30 +0800 Subject: [PATCH 17/24] use modern c++ recursive mutex primitives --- include/xredis/xLock.h | 54 ++++-------------------------------------- 1 file changed, 5 insertions(+), 49 deletions(-) diff --git a/include/xredis/xLock.h b/include/xredis/xLock.h index 33ae3f9..90eff26 100644 --- a/include/xredis/xLock.h +++ b/include/xredis/xLock.h @@ -6,65 +6,23 @@ * ---------------------------------------------------------------------------- */ -#ifndef _XLOCK_H_ -#define _XLOCK_H_ +#pragma once -#ifdef WIN32 -#include -#else -#include -#include -#include -#endif +#include class xLock { private: -#ifdef WIN32 - CRITICAL_SECTION mSection; -#else - pthread_mutex_t mMutex; -#endif + std::recursive_mutex mMutex; public: - inline xLock() - { -#ifdef WIN32 - InitializeCriticalSection(&mSection); -#else - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - int ret = pthread_mutex_init(&mMutex, &attr); - if (ret != 0) - { - fprintf(stderr, "pthread_mutex_init error %d \n\r", ret); - } -#endif - }; - inline ~xLock() - { -#ifdef WIN32 - DeleteCriticalSection(&mSection); -#else - pthread_mutex_destroy(&mMutex); -#endif - } inline void Enter() { -#ifdef WIN32 - EnterCriticalSection(&mSection); -#else - pthread_mutex_lock(&mMutex); -#endif + mMutex.lock(); } inline void Leave() { -#ifdef WIN32 - LeaveCriticalSection(&mSection); -#else - pthread_mutex_unlock(&mMutex); -#endif + mMutex.unlock(); }; }; @@ -85,5 +43,3 @@ class CLockUser }; #define XLOCK(T) CLockUser lock(T) - -#endif From 31a1ee463a5355b21e5809b5cb34299890d1dd9e Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:25:45 +0800 Subject: [PATCH 18/24] remove classical include guard and use pragma once instead --- include/xredis/xRedisClient.h | 5 +---- include/xredis/xRedisClusterClient.h | 7 ++----- include/xredis/xRedisPool.h | 7 +++---- 3 files changed, 6 insertions(+), 13 deletions(-) diff --git a/include/xredis/xRedisClient.h b/include/xredis/xRedisClient.h index 4f6a8c7..12df1cd 100644 --- a/include/xredis/xRedisClient.h +++ b/include/xredis/xRedisClient.h @@ -6,8 +6,7 @@ * ---------------------------------------------------------------------------- */ -#ifndef _XREDIS_CLIENT_H_ -#define _XREDIS_CLIENT_H_ +#pragma once #include #include @@ -381,5 +380,3 @@ class xRedisClient }; } // namespace xrc - -#endif diff --git a/include/xredis/xRedisClusterClient.h b/include/xredis/xRedisClusterClient.h index b968a92..f28fa8d 100644 --- a/include/xredis/xRedisClusterClient.h +++ b/include/xredis/xRedisClusterClient.h @@ -1,5 +1,4 @@ -#ifndef _XREDIS_HIREDISCPP_H_ -#define _XREDIS_HIREDISCPP_H_ +#pragma once #include #include @@ -8,7 +7,7 @@ #include #include #include -#include + #include "xLock.h" namespace xrc @@ -229,5 +228,3 @@ class xRedisClusterClient }; } // namespace xrc - -#endif diff --git a/include/xredis/xRedisPool.h b/include/xredis/xRedisPool.h index fec4bdf..19056db 100644 --- a/include/xredis/xRedisPool.h +++ b/include/xredis/xRedisPool.h @@ -6,12 +6,13 @@ * ---------------------------------------------------------------------------- */ -#ifndef _XREDIS_POOL_H_ -#define _XREDIS_POOL_H_ +#pragma once #include #include #include + +#include "xLock.h" #include "xRedisClient.h" namespace xrc @@ -175,5 +176,3 @@ class RedisPool }; } // namespace xrc - -#endif From ccfc769055bb08387663ab2f666ee03e30ce0101 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:26:18 +0800 Subject: [PATCH 19/24] makefiles no more --- makefile | 126 ------------------------------------------------------- 1 file changed, 126 deletions(-) delete mode 100644 makefile diff --git a/makefile b/makefile deleted file mode 100644 index 6ff51d1..0000000 --- a/makefile +++ /dev/null @@ -1,126 +0,0 @@ -# xredis Makefile -# Copyright (C) 2010-2011 Salvatore Sanfilippo -# Copyright (C) 2010-2011 Pieter Noordhuis -# Copyright (C) 2013-2016 xsky -# This file is released under the BSD license, see the COPYING file - -OBJ=src/xRedisClient.o src/xRedisClient_keys.o src/xRedisClient_sets.o src/xRedisClient_strings.o src/xRedisClient_pubsub.o src/xRedisClusterClient.o \ -src/xRedisClient_connection.o src/xRedisClient_hashs.o src/xRedisClient_lists.o src/xRedisClient_sortedsets.o src/xRedisPool.o -EXAMPLES=xredis-example -TESTS=xredis-test -LIBNAME=libxredis - -XREDIS_MAJOR=0 -XREDIS_MINOR=11 - -# Fallback to gcc when $CC is not in $PATH. -CC:=g++ -OPTIMIZATION?=-O3 -WARNINGS=-Wall -W -Wwrite-strings -DEBUG?= -g -ggdb -REAL_CFLAGS=$(OPTIMIZATION) -fPIC $(CFLAGS) $(WARNINGS) $(DEBUG) $(ARCH) -REAL_LDFLAGS=$(LDFLAGS) $(ARCH) - -DYLIBSUFFIX=so -STLIBSUFFIX=a -DYLIB_MINOR_NAME=$(LIBNAME).$(DYLIBSUFFIX).$(XREDIS_MAJOR).$(XREDIS_MINOR) -DYLIB_MAJOR_NAME=$(LIBNAME).$(DYLIBSUFFIX).$(XREDIS_MAJOR) -DYLIBNAME=$(LIBNAME).$(DYLIBSUFFIX) -DYLIB_MAKE_CMD=$(CC) -shared -fPIC -Wl,-soname,$(DYLIB_MINOR_NAME) -o $(DYLIBNAME) $(LDFLAGS) -lhiredis -STLIBNAME=$(LIBNAME).$(STLIBSUFFIX) -STLIB_MAKE_CMD=ar rcs $(STLIBNAME) - -# Platform-specific overrides -uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') -ifeq ($(uname_S),SunOS) - REAL_LDFLAGS+= -ldl -lnsl -lsocket - DYLIB_MAKE_CMD=$(CC) -G -o $(DYLIBNAME) -h $(DYLIB_MINOR_NAME) $(LDFLAGS) -lhiredis - INSTALL= cp -r -endif -ifeq ($(uname_S),Darwin) - DYLIBSUFFIX=dylib - DYLIB_MINOR_NAME=$(LIBNAME).$(XREDIS_MAJOR).$(XREDIS_MINOR).$(DYLIBSUFFIX) - DYLIB_MAJOR_NAME=$(LIBNAME).$(XREDIS_MAJOR).$(DYLIBSUFFIX) - DYLIB_MAKE_CMD=$(CC) -shared -Wl,-install_name,$(DYLIB_MINOR_NAME) -o $(DYLIBNAME) $(LDFLAGS) -lhiredis -endif - -all: $(DYLIBNAME) $(STLIBNAME) - -# Deps (use make dep to generate this) -xRedisClient_connection.o: xRedisClient_connection.cpp -xRedisClient.o: xRedisClient.cpp -xRedisClient_hashs.o: xRedisClient_hashs.cpp -xRedisClient_keys.o: xRedisClient_keys.cpp -xRedisClient_lists.o: xRedisClient_lists.cpp -xRedisClient_sets.o: xRedisClient_sets.cpp -xRedisClient_sortedsets.o: xRedisClient_sortedsets.cpp -xRedisClient_strings.o: xRedisClient_strings.cpp -xRedisClient_pubsub.o: xRedisClient_pubsub.cpp -xRedisPool.o: xRedisPool.cpp -xRedisClusterClient.o: xRedisClusterClient.cpp - -$(DYLIBNAME): $(OBJ) - $(DYLIB_MAKE_CMD) $(OBJ) - -$(STLIBNAME): $(OBJ) - $(STLIB_MAKE_CMD) $(OBJ) - -dynamic: $(DYLIBNAME) -static: $(STLIBNAME) - -# Binaries: -xredis-example: - $(CC) examples/xredis-example.cpp -o examples/xredis-example $(REAL_CFLAGS) $(REAL_LDFLAGS) -I./src -L./ $< $(STLIBNAME) -Wl,-Bstatic -lhiredis -Wl,-Bdynamic -lpthread - $(CC) examples/demo.cpp -o examples/demo $(REAL_CFLAGS) $(REAL_LDFLAGS) -I./src -L./ $< $(STLIBNAME) -Wl,-Bstatic -lhiredis -Wl,-Bdynamic -lpthread - $(CC) examples/demo_cluster.cpp -o examples/demo_cluster $(REAL_CFLAGS) $(REAL_LDFLAGS) -I./src -L./ $< $(STLIBNAME) -Wl,-Bstatic -lhiredis -Wl,-Bdynamic -lpthread - $(CC) examples/demo_multi_cluster.cpp -o examples/demo_multi_cluster $(REAL_LDFLAGS) -I./src -L./ $< $(STLIBNAME) -Wl,-Bstatic -lhiredis -Wl,-Bdynamic -lpthread - $(CC) examples/xRedisClusterClient_test.cpp -o examples/xRedisClusterClient_test $(REAL_LDFLAGS) -I./src -L./ $< $(STLIBNAME) -Wl,-Bstatic -lhiredis -Wl,-Bdynamic -lpthread - - -examples: $(EXAMPLES) - -xredis-test: test/xredis-test.cpp $(STLIBNAME) - $(CC) -o test/$@ $(REAL_CFLAGS) $(REAL_LDFLAGS) -D__STDC_FORMAT_MACROS -I./src -L. $< $(STLIBNAME) -lhiredis -lpthread - -test: xredis-test - @echo ./test/xredis-test - -%.o: %.cpp - $(CC) $(REAL_CFLAGS) -c $< -o $@ - -clean: - rm -rf $(DYLIBNAME) $(STLIBNAME) $(TESTS) src/*.o examples/example* *.o test/*.o - -dep: - $(CC) -MM *.cpp - -# Installation related variables and target -PREFIX?=/usr/local -INSTALL_INCLUDE_PATH= $(PREFIX)/include/xredis -INSTALL_LIBRARY_PATH= $(PREFIX)/lib - -ifeq ($(uname_S),SunOS) - INSTALL?= cp -r -endif - -INSTALL?= cp -a - -install: $(DYLIBNAME) $(STLIBNAME) - mkdir -p $(INSTALL_INCLUDE_PATH) $(INSTALL_LIBRARY_PATH) - $(INSTALL) src/xRedisClient.h $(INSTALL_INCLUDE_PATH) - $(INSTALL) $(DYLIBNAME) $(INSTALL_LIBRARY_PATH)/$(DYLIB_MINOR_NAME) - cd $(INSTALL_LIBRARY_PATH) && ln -sf $(DYLIB_MINOR_NAME) $(DYLIB_MAJOR_NAME) - cd $(INSTALL_LIBRARY_PATH) && ln -sf $(DYLIB_MAJOR_NAME) $(DYLIBNAME) - $(INSTALL) $(STLIBNAME) $(INSTALL_LIBRARY_PATH) - -32bit: - @echo "" - @echo "WARNING: if this fails under Linux you probably need to install libc6-dev-i386" - @echo "" - $(MAKE) CFLAGS="-m32" LDFLAGS="-m32" - -gprof: - $(MAKE) CFLAGS="-pg" LDFLAGS="-pg" - - -.PHONY: all test check clean dep install 32bit gprof gcov noopt From 9e1203fb99d3e5a5ccef6b3338995cc94d5a75f5 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:45:27 +0800 Subject: [PATCH 20/24] whoops, just include windows.h instead --- include/xredis/xredis.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/xredis/xredis.h b/include/xredis/xredis.h index 4f5f429..3e5c238 100644 --- a/include/xredis/xredis.h +++ b/include/xredis/xredis.h @@ -1,7 +1,7 @@ #pragma once #ifdef _MSC_VER -#include +#include #endif #include From 83012db8e69e99abf417e6f3e00fba4788c2120a Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Sun, 19 Apr 2020 23:45:59 +0800 Subject: [PATCH 21/24] use std::string and fmt instead --- include/xredis/xRedisClient.h | 4 ++-- src/xRedisClient.cpp | 25 +++++-------------------- 2 files changed, 7 insertions(+), 22 deletions(-) diff --git a/include/xredis/xRedisClient.h b/include/xredis/xRedisClient.h index 12df1cd..2f8661e 100644 --- a/include/xredis/xRedisClient.h +++ b/include/xredis/xRedisClient.h @@ -74,7 +74,7 @@ class RedisDBIdx bool CreateDBIndex(const char *key, HASHFUN fun, uint32_t type); bool CreateDBIndex(int64_t id, uint32_t type); - char *GetErrInfo() { return mStrerr; } + const char *GetErrInfo() { return mStrerr.c_str(); } void SetIOMaster(); private: @@ -85,7 +85,7 @@ class RedisDBIdx private: uint32_t mType; uint32_t mIndex; - char *mStrerr; + std::string mStrerr; xRedisClient *mClient; uint32_t mIOtype; bool mIOFlag; diff --git a/src/xRedisClient.cpp b/src/xRedisClient.cpp index edbd627..04f2025 100644 --- a/src/xRedisClient.cpp +++ b/src/xRedisClient.cpp @@ -6,6 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include + #include "xredis.h" using namespace xrc; @@ -14,7 +16,6 @@ RedisDBIdx::RedisDBIdx() { mType = 0; mIndex = 0; - mStrerr = NULL; mClient = NULL; mIOtype = MASTER; mIOFlag = false; @@ -24,18 +25,12 @@ RedisDBIdx::RedisDBIdx(xRedisClient *xredisclient) { mType = 0; mIndex = 0; - mStrerr = NULL; mClient = xredisclient; mIOtype = MASTER; mIOFlag = false; } RedisDBIdx::~RedisDBIdx() { - if (NULL != mStrerr) - { - delete[] mStrerr; - mStrerr = NULL; - } } bool RedisDBIdx::CreateDBIndex(const char *key, HASHFUN fun, const uint32_t type) @@ -79,16 +74,7 @@ bool RedisDBIdx::SetErrInfo(const char *info, int32_t len) { return false; } - if (NULL == mStrerr) - { - mStrerr = new char[len + 1]; - } - if (NULL != mStrerr) - { - strncpy(mStrerr, info, len); - mStrerr[len] = '\0'; - return true; - } + mStrerr = std::string(info, info + len); return false; } @@ -204,12 +190,11 @@ void xRedisClient::SetIOtype(const RedisDBIdx &dbi, uint32_t iotype, bool ioflag void xRedisClient::SetErrMessage(const RedisDBIdx &dbi, const char *fmt, ...) { - char szBuf[128] = {0}; va_list va; va_start(va, fmt); - vsnprintf(szBuf, sizeof(szBuf), fmt, va); + std::string formatted = fmt::sprintf(fmt, va); va_end(va); - SetErrString(dbi, szBuf, ::strlen(szBuf)); + SetErrString(dbi, formatted.c_str(), formatted.length()); } rReply *xRedisClient::command(const RedisDBIdx &dbi, const char *cmd) From be76c30c5398f9f21d8c9bfecc870a3032c0d736 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Mon, 20 Apr 2020 00:42:38 +0800 Subject: [PATCH 22/24] use fmt::format --- CMakeLists.txt | 3 +- src/xRedisClient.cpp | 1 + src/xRedisClient_connection.cpp | 4 +- src/xRedisClient_hashs.cpp | 24 +++++----- src/xRedisClient_keys.cpp | 25 ++++++----- src/xRedisClient_lists.cpp | 31 +++++++------ src/xRedisClient_pubsub.cpp | 6 ++- src/xRedisClient_sets.cpp | 17 +++---- src/xRedisClient_sortedsets.cpp | 25 ++++++----- src/xRedisClient_strings.cpp | 45 ++++++++++--------- src/xRedisClusterClient.cpp | 79 +++++++++++++++++---------------- src/xRedisPool.cpp | 5 ++- 12 files changed, 147 insertions(+), 118 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e431ba8..11eab14 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,6 +5,7 @@ if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) include(CTest) endif() +find_package(fmt CONFIG REQUIRED) find_package(hiredis) if (NOT ${hiredis_FOUND}) @@ -41,7 +42,7 @@ target_include_directories( target_link_libraries( xredis - PRIVATE hiredis + PRIVATE hiredis fmt::fmt fmt::fmt-header-only ) if (MSVC) diff --git a/src/xRedisClient.cpp b/src/xRedisClient.cpp index 04f2025..04fa497 100644 --- a/src/xRedisClient.cpp +++ b/src/xRedisClient.cpp @@ -7,6 +7,7 @@ */ #include #include +#include #include "xredis.h" diff --git a/src/xRedisClient_connection.cpp b/src/xRedisClient_connection.cpp index 3074b16..e357c83 100644 --- a/src/xRedisClient_connection.cpp +++ b/src/xRedisClient_connection.cpp @@ -6,6 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include +#include #include "xredis.h" using namespace xrc; @@ -22,5 +24,5 @@ bool xRedisClient::echo(const RedisDBIdx &dbi, const std::string &str, std::stri return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "echo %s", str.c_str()); + return command_string(dbi, value, fmt::format("echo {}").c_str()); } diff --git a/src/xRedisClient_hashs.cpp b/src/xRedisClient_hashs.cpp index 4a57a03..f9b5f14 100644 --- a/src/xRedisClient_hashs.cpp +++ b/src/xRedisClient_hashs.cpp @@ -7,6 +7,8 @@ */ #include #include +#include +#include #include "xredis.h" @@ -15,7 +17,7 @@ using namespace xrc; bool xRedisClient::hdel(const RedisDBIdx &dbi, const std::string &key, const std::string &field, int64_t &count) { SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, count, "HDEL %s %s", key.c_str(), field.c_str()); + return command_integer(dbi, count, fmt::format("HDEL {} {}", key, field).c_str()); } bool xRedisClient::hdel(const RedisDBIdx &dbi, const std::string &key, const KEYS &vfiled, int64_t &count) @@ -31,25 +33,25 @@ bool xRedisClient::hdel(const RedisDBIdx &dbi, const std::string &key, const KEY bool xRedisClient::hexist(const RedisDBIdx &dbi, const std::string &key, const std::string &field) { SETDEFAULTIOTYPE(SLAVE); - return command_bool(dbi, "HEXISTS %s %s", key.c_str(), field.c_str()); + return command_bool(dbi, fmt::format("HEXISTS {} {}", key, field).c_str()); } bool xRedisClient::hget(const RedisDBIdx &dbi, const std::string &key, const std::string &field, std::string &value) { SETDEFAULTIOTYPE(SLAVE); - return command_string(dbi, value, "HGET %s %s", key.c_str(), field.c_str()); + return command_string(dbi, value, fmt::format("HGET {} {}", key, field).c_str()); } bool xRedisClient::hgetall(const RedisDBIdx &dbi, const std::string &key, ArrayReply &array) { SETDEFAULTIOTYPE(SLAVE); - return command_array(dbi, array, "HGETALL %s", key.c_str()); + return command_array(dbi, array, fmt::format("HGETALL {}", key).c_str()); } bool xRedisClient::hincrby(const RedisDBIdx &dbi, const std::string &key, const std::string &field, int64_t increment, int64_t &num) { SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, num, "HINCRBY %s %s %lld", key.c_str(), field.c_str(), increment); + return command_integer(dbi, num, fmt::format("HINCRBY {} {} {}", key, field, increment).c_str()); } bool xRedisClient::hincrbyfloat(const RedisDBIdx &dbi, const std::string &key, const std::string &field, float increment, float &value) @@ -62,7 +64,7 @@ bool xRedisClient::hincrbyfloat(const RedisDBIdx &dbi, const std::string &key, c return false; } - redisReply *reply = static_cast(redisCommand(pRedisConn->getCtx(), "HINCRBYFLOAT %s %s %f", key.c_str(), field.c_str(), increment)); + redisReply *reply = static_cast(redisCommand(pRedisConn->getCtx(), fmt::format("HINCRBYFLOAT {} {} {}", key, field, increment).c_str())); if (RedisPool::CheckReply(reply)) { value = atof(reply->str); @@ -77,13 +79,13 @@ bool xRedisClient::hincrbyfloat(const RedisDBIdx &dbi, const std::string &key, c bool xRedisClient::hkeys(const RedisDBIdx &dbi, const std::string &key, KEYS &keys) { SETDEFAULTIOTYPE(SLAVE); - return command_list(dbi, keys, "HKEYS %s", key.c_str()); + return command_list(dbi, keys, fmt::format("HKEYS {}", key).c_str()); } bool xRedisClient::hlen(const RedisDBIdx &dbi, const std::string &key, int64_t &count) { SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, count, "HLEN %s", key.c_str()); + return command_integer(dbi, count, fmt::format("HLEN {}", key).c_str()); } bool xRedisClient::hmget(const RedisDBIdx &dbi, const std::string &key, const KEYS &field, ArrayReply &array) @@ -120,17 +122,17 @@ bool xRedisClient::hset(const RedisDBIdx &dbi, const std::string &key, const std vCmdData.push_back(field); vCmdData.push_back(value); return commandargv_integer(dbi, vCmdData, retval); - //return command_integer(dbi, retval, "HSET %s %s %s", key.c_str(), field.c_str(), value.c_str()); + //return command_integer(dbi, retval, "HSET {} {} {}", key.c_str(), field.c_str(), value.c_str()); } bool xRedisClient::hsetnx(const RedisDBIdx &dbi, const std::string &key, const std::string &field, const std::string &value) { SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "HSETNX %s %s %s", key.c_str(), field.c_str(), value.c_str()); + return command_bool(dbi, fmt::format("HSETNX {} {} {}", key, field, value).c_str()); } bool xRedisClient::hvals(const RedisDBIdx &dbi, const std::string &key, VALUES &values) { SETDEFAULTIOTYPE(SLAVE); - return command_list(dbi, values, "HVALS %s", key.c_str()); + return command_list(dbi, values, fmt::format("HVALS {}", key).c_str()); } diff --git a/src/xRedisClient_keys.cpp b/src/xRedisClient_keys.cpp index e576408..812c941 100644 --- a/src/xRedisClient_keys.cpp +++ b/src/xRedisClient_keys.cpp @@ -6,6 +6,9 @@ * ---------------------------------------------------------------------------- */ #include +#include +#include + #include "xredis.h" using namespace xrc; @@ -18,7 +21,7 @@ bool xRedisClient::del(const RedisDBIdx &dbi, const std::string &key) } SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "DEL %s", key.c_str()); + return command_bool(dbi, fmt::format("DEL {}", key).c_str()); } bool xRedisClient::del(const DBIArray &vdbi, const KEYS &vkey, int64_t &count) @@ -49,7 +52,7 @@ bool xRedisClient::exists(const RedisDBIdx &dbi, const std::string &key) return false; } SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "EXISTS %s", key.c_str()); + return command_bool(dbi, fmt::format("EXISTS {}", key).c_str()); } bool xRedisClient::expire(const RedisDBIdx &dbi, const std::string &key, uint32_t second) @@ -60,7 +63,7 @@ bool xRedisClient::expire(const RedisDBIdx &dbi, const std::string &key, uint32_ } SETDEFAULTIOTYPE(MASTER); int64_t ret = -1; - if (!command_integer(dbi, ret, "EXPIRE %s %u", key.c_str(), second)) + if (!command_integer(dbi, ret, fmt::format("EXPIRE {} {}", key, second).c_str())) { return false; } @@ -71,7 +74,7 @@ bool xRedisClient::expire(const RedisDBIdx &dbi, const std::string &key, uint32_ } else { - SetErrMessage(dbi, "expire return %ld ", ret); + SetErrMessage(dbi, "expire return {} ", ret); return false; } } @@ -83,7 +86,7 @@ bool xRedisClient::expireat(const RedisDBIdx &dbi, const std::string &key, uint3 return false; } SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "EXPIREAT %s %u", key.c_str(), timestamp); + return command_bool(dbi, fmt::format("EXPIREAT {} {}", key, timestamp).c_str()); } bool xRedisClient::persist(const RedisDBIdx &dbi, const std::string &key) @@ -93,7 +96,7 @@ bool xRedisClient::persist(const RedisDBIdx &dbi, const std::string &key) return false; } SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "PERSIST %s %u", key.c_str()); + return command_bool(dbi, fmt::format("PERSIST {}", key).c_str()); } bool xRedisClient::pexpire(const RedisDBIdx &dbi, const std::string &key, uint32_t milliseconds) @@ -102,7 +105,7 @@ bool xRedisClient::pexpire(const RedisDBIdx &dbi, const std::string &key, uint32 { return false; } - return command_bool(dbi, "PEXPIRE %s %u", key.c_str(), milliseconds); + return command_bool(dbi, fmt::format("PEXPIRE {} {}", key, milliseconds).c_str()); } bool xRedisClient::pexpireat(const RedisDBIdx &dbi, const std::string &key, uint32_t millisecondstimestamp) @@ -112,7 +115,7 @@ bool xRedisClient::pexpireat(const RedisDBIdx &dbi, const std::string &key, uint return false; } SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "PEXPIREAT %s %u", key.c_str(), millisecondstimestamp); + return command_bool(dbi, fmt::format("PEXPIREAT {} {}", key, millisecondstimestamp).c_str()); } bool xRedisClient::pttl(const RedisDBIdx &dbi, const std::string &key, int64_t &milliseconds) @@ -122,7 +125,7 @@ bool xRedisClient::pttl(const RedisDBIdx &dbi, const std::string &key, int64_t & return false; } SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, milliseconds, "PTTL %s", key.c_str()); + return command_integer(dbi, milliseconds, fmt::format("PTTL {}", key).c_str()); } bool xRedisClient::ttl(const RedisDBIdx &dbi, const std::string &key, int64_t &seconds) @@ -132,13 +135,13 @@ bool xRedisClient::ttl(const RedisDBIdx &dbi, const std::string &key, int64_t &s return false; } SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, seconds, "TTL %s", key.c_str()); + return command_integer(dbi, seconds, fmt::format("TTL {}", key).c_str()); } bool xRedisClient::type(const RedisDBIdx &dbi, const std::string &key, std::string &value) { SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "TYPE %s", key.c_str()); + return command_string(dbi, value, fmt::format("TYPE {}", key).c_str()); } bool xRedisClient::randomkey(const RedisDBIdx &dbi, KEY &key) diff --git a/src/xRedisClient_lists.cpp b/src/xRedisClient_lists.cpp index 504e61f..c1145b4 100644 --- a/src/xRedisClient_lists.cpp +++ b/src/xRedisClient_lists.cpp @@ -8,6 +8,9 @@ #include #include +#include +#include + #include "xredis.h" using namespace xrc; @@ -18,7 +21,7 @@ bool xRedisClient::lindex(const RedisDBIdx &dbi, const std::string &key, int64_t return false; } SETDEFAULTIOTYPE(SLAVE); - return command_string(dbi, value, "LINDEX %s %lld", key.c_str(), index); + return command_string(dbi, value, fmt::format("LINDEX {} {}", key, index).c_str()); } bool xRedisClient::linsert(const RedisDBIdx &dbi, const std::string &key, const LMODEL mod, const std::string &pivot, const std::string &value, int64_t &retval) @@ -29,7 +32,7 @@ bool xRedisClient::linsert(const RedisDBIdx &dbi, const std::string &key, const return false; } SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, retval, "LINSERT %s %s %s %s", key.c_str(), lmodel[mod], pivot.c_str(), value.c_str()); + return command_integer(dbi, retval, fmt::format("LINSERT {} {} {} {}", key, lmodel[mod], pivot, value).c_str()); } bool xRedisClient::llen(const RedisDBIdx &dbi, const std::string &key, int64_t &retval) @@ -39,7 +42,7 @@ bool xRedisClient::llen(const RedisDBIdx &dbi, const std::string &key, int64_t & return false; } SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, retval, "LLEN %s", key.c_str()); + return command_integer(dbi, retval, fmt::format("LLEN {}", key).c_str()); } bool xRedisClient::blPop(const RedisDBIdx &dbi, const std::string &key, VALUES &vValues, int64_t timeout) @@ -49,7 +52,7 @@ bool xRedisClient::blPop(const RedisDBIdx &dbi, const std::string &key, VALUES & return false; } SETDEFAULTIOTYPE(MASTER); - return command_list(dbi, vValues, "BLPOP %s %d", key.c_str(), (int32_t)timeout); + return command_list(dbi, vValues, fmt::format("BLPOP {} {}", key, (int32_t)timeout).c_str()); } bool xRedisClient::brPop(const RedisDBIdx &dbi, const std::string &key, VALUES &vValues, int64_t timeout) @@ -59,7 +62,7 @@ bool xRedisClient::brPop(const RedisDBIdx &dbi, const std::string &key, VALUES & return false; } SETDEFAULTIOTYPE(MASTER); - return command_list(dbi, vValues, "BRPOP %s %d", key.c_str(), (int32_t)timeout); + return command_list(dbi, vValues, fmt::format("BRPOP {} {}", key, (int32_t)timeout).c_str()); } bool xRedisClient::brPoplpush(const RedisDBIdx &dbi, const std::string &key, std::string &targetkey, VALUE &value, int64_t timeout) @@ -69,7 +72,7 @@ bool xRedisClient::brPoplpush(const RedisDBIdx &dbi, const std::string &key, std return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "BRPOPLPUSH %s %s %d", key.c_str(), targetkey.c_str(), (int32_t)timeout); + return command_string(dbi, value, fmt::format("BRPOPLPUSH {} {}", key, targetkey, (int32_t)timeout).c_str()); } bool xRedisClient::lpop(const RedisDBIdx &dbi, const std::string &key, std::string &value) @@ -79,7 +82,7 @@ bool xRedisClient::lpop(const RedisDBIdx &dbi, const std::string &key, std::stri return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "LPOP %s", key.c_str()); + return command_string(dbi, value, fmt::format("LPOP {}", key).c_str()); } bool xRedisClient::lpush(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &length) @@ -103,7 +106,7 @@ bool xRedisClient::lrange(const RedisDBIdx &dbi, const std::string &key, int64_t return false; } SETDEFAULTIOTYPE(SLAVE); - return command_array(dbi, array, "LRANGE %s %lld %lld", key.c_str(), start, end); + return command_array(dbi, array, fmt::format("LRANGE {} {} {}", key, start, end).c_str()); } bool xRedisClient::lrem(const RedisDBIdx &dbi, const std::string &key, int32_t count, const std::string &value, int64_t num) @@ -113,7 +116,7 @@ bool xRedisClient::lrem(const RedisDBIdx &dbi, const std::string &key, int32_t c return false; } SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, num, "LREM %s %d %s", key.c_str(), count, value.c_str()); + return command_integer(dbi, num, fmt::format("LREM {} {} {}", key, count, value).c_str()); } bool xRedisClient::lset(const RedisDBIdx &dbi, const std::string &key, int32_t index, const std::string &value) @@ -123,7 +126,7 @@ bool xRedisClient::lset(const RedisDBIdx &dbi, const std::string &key, int32_t i return false; } SETDEFAULTIOTYPE(MASTER); - return command_status(dbi, "LSET %s %d %s", key.c_str(), index, value.c_str()); + return command_status(dbi, fmt::format("LSET {} {} {}", key, index, value).c_str()); } bool xRedisClient::ltrim(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end) @@ -133,7 +136,7 @@ bool xRedisClient::ltrim(const RedisDBIdx &dbi, const std::string &key, int32_t return false; } SETDEFAULTIOTYPE(MASTER); - return command_status(dbi, "LTRIM %s %d %d", key.c_str(), start, end); + return command_status(dbi, fmt::format("LTRIM {} {} {}", key, start, end).c_str()); } bool xRedisClient::rpop(const RedisDBIdx &dbi, const std::string &key, std::string &value) @@ -143,7 +146,7 @@ bool xRedisClient::rpop(const RedisDBIdx &dbi, const std::string &key, std::stri return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "RPOP %s", key.c_str()); + return command_string(dbi, value, fmt::format("RPOP {}", key).c_str()); } bool xRedisClient::rpoplpush(const RedisDBIdx &dbi, const std::string &key_src, const std::string &key_dest, std::string &value) @@ -153,7 +156,7 @@ bool xRedisClient::rpoplpush(const RedisDBIdx &dbi, const std::string &key_src, return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "RPOPLPUSH %s %s", key_src.c_str(), key_dest.c_str()); + return command_string(dbi, value, fmt::format("RPOPLPUSH {} {}", key_src, key_dest).c_str()); } bool xRedisClient::rpush(const RedisDBIdx &dbi, const std::string &key, const VALUES &vValue, int64_t &length) @@ -177,5 +180,5 @@ bool xRedisClient::rpushx(const RedisDBIdx &dbi, const std::string &key, const s return false; } SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, length, "RPUSHX %s %s", key.c_str(), value.c_str()); + return command_integer(dbi, length, fmt::format("RPUSHX {} {}", key, value).c_str()); } diff --git a/src/xRedisClient_pubsub.cpp b/src/xRedisClient_pubsub.cpp index cfc14c9..351895c 100644 --- a/src/xRedisClient_pubsub.cpp +++ b/src/xRedisClient_pubsub.cpp @@ -6,6 +6,8 @@ * ---------------------------------------------------------------------------- */ #include +#include +#include #include "xredis.h" using namespace xrc; @@ -22,7 +24,7 @@ bool xRedisClient::psubscribe(const RedisDBIdx &dbi, const KEYS &patterns, xRedi bool xRedisClient::publish(const RedisDBIdx &dbi, const KEY &channel, const std::string &message, int64_t &count) { //SETDEFAULTIOTYPE(MASTER); - //return command_integer(dbi, count, "PUBLISH %s %s", channel.c_str(), message.c_str(), count); + //return command_integer(dbi, count, "PUBLISH {} {}", channel.c_str(), message.c_str(), count); SETDEFAULTIOTYPE(MASTER); VDATA vCmdData; @@ -35,7 +37,7 @@ bool xRedisClient::publish(const RedisDBIdx &dbi, const KEY &channel, const std: bool xRedisClient::pubsub_channels(const RedisDBIdx &dbi, const std::string &pattern, ArrayReply &reply) { SETDEFAULTIOTYPE(MASTER); - return command_array(dbi, reply, "pubsub channels %s", pattern.c_str()); + return command_array(dbi, reply, fmt::format("pubsub channels {}", pattern).c_str()); } bool xRedisClient::pubsub_numsub(const RedisDBIdx &dbi, const KEYS &keys, ArrayReply &reply) diff --git a/src/xRedisClient_sets.cpp b/src/xRedisClient_sets.cpp index d4ec089..d76f8fc 100644 --- a/src/xRedisClient_sets.cpp +++ b/src/xRedisClient_sets.cpp @@ -5,7 +5,8 @@ * Distributed under GPL license. * ---------------------------------------------------------------------------- */ - +#include +#include #include "xredis.h" using namespace xrc; @@ -26,7 +27,7 @@ bool xRedisClient::scard(const RedisDBIdx &dbi, const std::string &key, int64_t return false; } SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, count, "SCARD %s", key.c_str()); + return command_integer(dbi, count, fmt::format("SCARD {}", key).c_str()); } bool xRedisClient::sdiff(const DBIArray &vdbi, const KEYS &vkey, VALUES &sValue) @@ -120,7 +121,7 @@ bool xRedisClient::sismember(const RedisDBIdx &dbi, const KEY &key, const VALUE { return false; } - return command_bool(dbi, "SISMEMBER %s %s", key.c_str(), member.c_str()); + return command_bool(dbi, fmt::format("SISMEMBER {} {}", key, member).c_str()); } bool xRedisClient::smembers(const RedisDBIdx &dbi, const KEY &key, VALUES &vValue) @@ -130,7 +131,7 @@ bool xRedisClient::smembers(const RedisDBIdx &dbi, const KEY &key, VALUES &vValu return false; } SETDEFAULTIOTYPE(SLAVE); - return command_list(dbi, vValue, "SMEMBERS %s", key.c_str()); + return command_list(dbi, vValue, fmt::format("SMEMBERS {}", key).c_str()); } bool xRedisClient::smove(const RedisDBIdx &dbi, const KEY &srckey, const KEY &deskey, const VALUE &member) @@ -140,7 +141,7 @@ bool xRedisClient::smove(const RedisDBIdx &dbi, const KEY &srckey, const KEY &de return false; } SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "SMOVE %s %s %s", srckey.c_str(), deskey.c_str(), member.c_str()); + return command_bool(dbi, fmt::format("SMOVE {} {} {}", srckey, deskey, member).c_str()); } bool xRedisClient::spop(const RedisDBIdx &dbi, const KEY &key, VALUE &member) @@ -150,7 +151,7 @@ bool xRedisClient::spop(const RedisDBIdx &dbi, const KEY &key, VALUE &member) return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, member, "SPOP %s", key.c_str()); + return command_string(dbi, member, fmt::format("SPOP {}", key).c_str()); } bool xRedisClient::srandmember(const RedisDBIdx &dbi, const KEY &key, VALUES &members, int32_t count) @@ -162,9 +163,9 @@ bool xRedisClient::srandmember(const RedisDBIdx &dbi, const KEY &key, VALUES &me SETDEFAULTIOTYPE(SLAVE); if (0 == count) { - return command_list(dbi, members, "SRANDMEMBER %s", key.c_str()); + return command_list(dbi, members, fmt::format("SRANDMEMBER {}", key).c_str()); } - return command_list(dbi, members, "SRANDMEMBER %s %d", key.c_str(), count); + return command_list(dbi, members, fmt::format("SRANDMEMBER {} {}", key, count).c_str()); } bool xRedisClient::srem(const RedisDBIdx &dbi, const KEY &key, const VALUES &vmembers, int64_t &count) diff --git a/src/xRedisClient_sortedsets.cpp b/src/xRedisClient_sortedsets.cpp index c3e60fa..372173a 100644 --- a/src/xRedisClient_sortedsets.cpp +++ b/src/xRedisClient_sortedsets.cpp @@ -6,6 +6,9 @@ * ---------------------------------------------------------------------------- */ #include +#include +#include + #include "xredis.h" using namespace xrc; @@ -27,7 +30,7 @@ bool xRedisClient::zscrad(const RedisDBIdx &dbi, const std::string &key, int64_t return false; } SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, count, "ZSCRAD %s", key.c_str()); + return command_integer(dbi, count, fmt::format("ZSCRAD {}", key).c_str()); } bool xRedisClient::zincrby(const RedisDBIdx &dbi, const std::string &key, const double &increment, const std::string &member, std::string &value) @@ -37,7 +40,7 @@ bool xRedisClient::zincrby(const RedisDBIdx &dbi, const std::string &key, const return false; } SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, value, "ZINCRBY %s %f %s", key.c_str(), increment, member.c_str()); + return command_string(dbi, value, fmt::format("ZINCRBY {} {} {}", key, increment, member).c_str()); } bool xRedisClient::zrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, VALUES &vValues, bool withscore) @@ -49,9 +52,9 @@ bool xRedisClient::zrange(const RedisDBIdx &dbi, const std::string &key, int32_t SETDEFAULTIOTYPE(SLAVE); if (withscore) { - return command_list(dbi, vValues, "ZRANGE %s %d %d %s", key.c_str(), start, end, "WITHSCORES"); + return command_list(dbi, vValues, fmt::format("ZRANGE {} {} {} WITHSCORES", key, start, end).c_str()); } - return command_list(dbi, vValues, "ZRANGE %s %d %d", key.c_str(), start, end); + return command_list(dbi, vValues, fmt::format("ZRANGE {} {} {}", key, start, end).c_str()); } bool xRedisClient::zrangebyscore(const RedisDBIdx &dbi, const std::string &key, const std::string &min, @@ -91,7 +94,7 @@ bool xRedisClient::zrank(const RedisDBIdx &dbi, const std::string &key, const st return false; } SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, rank, "ZRANK %s %s", key.c_str(), member.c_str()); + return command_integer(dbi, rank, fmt::format("ZRANK {} {}", key, member).c_str()); } bool xRedisClient::zrem(const RedisDBIdx &dbi, const KEY &key, const VALUES &vmembers, int64_t &count) @@ -111,7 +114,7 @@ bool xRedisClient::zremrangebyrank(const RedisDBIdx &dbi, const std::string &key return false; } SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, count, "ZREMRANGEBYRANK %s %d %d", key.c_str(), start, stop); + return command_integer(dbi, count, fmt::format("ZREMRANGEBYRANK {} {} {}", key, start, stop).c_str()); } bool xRedisClient::zremrangebyscore(const RedisDBIdx &dbi, const KEY &key, double min, double max, int64_t &count) @@ -121,7 +124,7 @@ bool xRedisClient::zremrangebyscore(const RedisDBIdx &dbi, const KEY &key, doubl return false; } SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, count, "ZREMRANGEBYSCORE %s %d %d", key.c_str(), min, max); + return command_integer(dbi, count, fmt::format("ZREMRANGEBYSCORE {} {} {}", key, min, max).c_str()); } bool xRedisClient::zrevrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, VALUES &vValues, bool withscore) @@ -132,9 +135,9 @@ bool xRedisClient::zrevrange(const RedisDBIdx &dbi, const std::string &key, int3 } if (withscore) { - return command_list(dbi, vValues, "ZREVRANGE %s %d %d %s", key.c_str(), start, end, "WITHSCORES"); + return command_list(dbi, vValues, fmt::format("ZREVRANGE {} {} {} {}", key, start, end, "WITHSCORES").c_str()); } - return command_list(dbi, vValues, "ZREVRANGE %s %d %d", key.c_str(), start, end); + return command_list(dbi, vValues, fmt::format("ZREVRANGE {} {} {}", key, start, end).c_str()); } bool xRedisClient::zrevrank(const RedisDBIdx &dbi, const std::string &key, const std::string &member, int64_t &rank) @@ -144,7 +147,7 @@ bool xRedisClient::zrevrank(const RedisDBIdx &dbi, const std::string &key, const return false; } SETDEFAULTIOTYPE(SLAVE); - return command_integer(dbi, rank, "ZREVRANK %s %s", key.c_str(), member.c_str()); + return command_integer(dbi, rank, fmt::format("ZREVRANK {} {}", key, member).c_str()); } bool xRedisClient::zscan(const RedisDBIdx &dbi, const std::string &key, int64_t &cursor, const char *pattern, @@ -160,5 +163,5 @@ bool xRedisClient::zscore(const RedisDBIdx &dbi, const std::string &key, const s return false; } SETDEFAULTIOTYPE(SLAVE); - return command_string(dbi, score, "ZSCORE %s %s", key.c_str(), member.c_str()); + return command_string(dbi, score, fmt::format("ZSCORE {} {}", key, member).c_str()); } diff --git a/src/xRedisClient_strings.cpp b/src/xRedisClient_strings.cpp index 93ddffe..1307a6a 100644 --- a/src/xRedisClient_strings.cpp +++ b/src/xRedisClient_strings.cpp @@ -6,6 +6,9 @@ * ---------------------------------------------------------------------------- */ #include +#include +#include + #include "xredis.h" using namespace xrc; @@ -13,7 +16,7 @@ using namespace xrc; bool xRedisClient::psetex(const RedisDBIdx &dbi, const std::string &key, int32_t milliseconds, const std::string &value) { SETDEFAULTIOTYPE(MASTER); - return command_bool(dbi, "PSETEX %s %d %s", key.c_str(), milliseconds, value.c_str()); + return command_bool(dbi, fmt::format("PSETEX {} {} {}", key, milliseconds, value).c_str()); } bool xRedisClient::append(const RedisDBIdx &dbi, const std::string &key, const std::string &value) @@ -63,33 +66,35 @@ bool xRedisClient::set(const RedisDBIdx &dbi, const std::string &key, const std: bool xRedisClient::set(const RedisDBIdx &dbi, const std::string &key, const char *value, int32_t len, int32_t second) { SETDEFAULTIOTYPE(MASTER); + + // use std::string_view here? if (0 == second) { - return command_bool(dbi, "set %s %b", key.c_str(), value, len); + return command_bool(dbi, "set %s %b", key, value, len); } else { - return command_bool(dbi, "set %s %b EX %d", key.c_str(), value, len, second); + return command_bool(dbi, "set %s %b EX %s", key, value, len, second); } } bool xRedisClient::setbit(const RedisDBIdx &dbi, const std::string &key, int32_t offset, int64_t newbitValue, int64_t oldbitValue) { SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, oldbitValue, "SETBIT %s %d %lld", key.c_str(), offset, newbitValue); + return command_integer(dbi, oldbitValue, fmt::format("SETBIT {} {} {}", key, offset, newbitValue).c_str()); } bool xRedisClient::get(const RedisDBIdx &dbi, const std::string &key, std::string &value) { SETDEFAULTIOTYPE(SLAVE); - return command_string(dbi, value, "GET %s", key.c_str()); + return command_string(dbi, value, fmt::format("GET {}", key).c_str()); } bool xRedisClient::getbit(const RedisDBIdx &dbi, const std::string &key, int32_t &offset, int32_t &bit) { SETDEFAULTIOTYPE(SLAVE); int64_t intval = 0; - bool bRet = command_integer(dbi, intval, "GETBIT %s %d", key.c_str(), offset); + bool bRet = command_integer(dbi, intval, fmt::format("GETBIT {} {}", key, offset).c_str()); bit = (int32_t)intval; return bRet; } @@ -97,13 +102,13 @@ bool xRedisClient::getbit(const RedisDBIdx &dbi, const std::string &key, int32_t bool xRedisClient::getrange(const RedisDBIdx &dbi, const std::string &key, int32_t start, int32_t end, std::string &out) { SETDEFAULTIOTYPE(SLAVE); - return command_string(dbi, out, "GETRANGE %s %d %d", key.c_str(), start, end); + return command_string(dbi, out, fmt::format("GETRANGE {} {} {}", key, start, end).c_str()); } bool xRedisClient::getset(const RedisDBIdx &dbi, const std::string &key, const std::string &newValue, std::string &oldValue) { SETDEFAULTIOTYPE(MASTER); - return command_string(dbi, oldValue, "GETSET %s %s", key.c_str(), newValue.c_str()); + return command_string(dbi, oldValue, fmt::format("GETSET {} {}", key, newValue).c_str()); } bool xRedisClient::mget(const DBIArray &vdbi, const KEYS &keys, ReplyData &vDdata) @@ -125,7 +130,7 @@ bool xRedisClient::mget(const DBIArray &vdbi, const KEYS &keys, ReplyData &vDdat const std::string &key = *iter_key; if (key.length() > 0) { - bool ret = command_string(*iter_dbi, item.str, "GET %s", key.c_str()); + bool ret = command_string(*iter_dbi, item.str, fmt::format("GET {}", key).c_str()); if (!ret) { item.type = REDIS_REPLY_NIL; @@ -152,7 +157,7 @@ bool xRedisClient::mset(const DBIArray &vdbi, const VDATA &vData) const std::string &value = (*iter_data++); const RedisDBIdx &dbi = *iter_dbi; SETDEFAULTIOTYPE(SLAVE); - command_status(dbi, "SET %s %s", key.c_str(), value.c_str()); + command_status(dbi, fmt::format("SET {} {}", key, value).c_str()); } return true; } @@ -183,7 +188,7 @@ bool xRedisClient::setrange(const RedisDBIdx &dbi, const std::string &key, int32 { int64_t intval = 0; SETDEFAULTIOTYPE(MASTER); - bool bRet = command_integer(dbi, intval, "setrange %s %d %s", key.c_str(), offset, value.c_str()); + bool bRet = command_integer(dbi, intval, fmt::format("setrange {} {} {}", key, offset, value).c_str()); length = (int32_t)intval; return bRet; } @@ -192,7 +197,7 @@ bool xRedisClient::strlen(const RedisDBIdx &dbi, const std::string &key, int32_t { int64_t intval = 0; SETDEFAULTIOTYPE(SLAVE); - bool bRet = command_integer(dbi, intval, "STRLEN %s", key.c_str()); + bool bRet = command_integer(dbi, intval, fmt::format("STRLEN {}", key).c_str()); length = (int32_t)intval; return bRet; } @@ -200,13 +205,13 @@ bool xRedisClient::strlen(const RedisDBIdx &dbi, const std::string &key, int32_t bool xRedisClient::incr(const RedisDBIdx &dbi, const std::string &key, int64_t &result) { SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, result, "INCR %s", key.c_str()); + return command_integer(dbi, result, fmt::format("INCR {}", key).c_str()); } bool xRedisClient::incrby(const RedisDBIdx &dbi, const std::string &key, int32_t by, int64_t &result) { SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, result, "INCRBY %s %d", key.c_str(), by); + return command_integer(dbi, result, fmt::format("INCRBY {} {}", key, by).c_str()); } bool xRedisClient::bitcount(const RedisDBIdx &dbi, const std::string &key, int32_t &count, int32_t start, int32_t end) @@ -216,11 +221,11 @@ bool xRedisClient::bitcount(const RedisDBIdx &dbi, const std::string &key, int32 SETDEFAULTIOTYPE(SLAVE); if ((start != 0) || (end != 0)) { - bRet = command_integer(dbi, intval, "bitcount %s %d %d", key.c_str(), start, end); + bRet = command_integer(dbi, intval, fmt::format("bitcount {} {} {}", key, start, end).c_str()); } else { - bRet = command_integer(dbi, intval, "bitcount %s", key.c_str()); + bRet = command_integer(dbi, intval, fmt::format("bitcount {}", key).c_str()); } count = (int32_t)intval; return bRet; @@ -246,19 +251,19 @@ bool xRedisClient::bitpos(const RedisDBIdx &dbi, const std::string &key, int32_t SETDEFAULTIOTYPE(SLAVE); if ((start != 0) || (end != 0)) { - return command_integer(dbi, pos, "BITPOS %s %d %d %d", key.c_str(), bit, start, end); + return command_integer(dbi, pos, fmt::format("BITPOS {} {} {} {}", key, bit, start, end).c_str()); } - return command_integer(dbi, pos, "BITPOS %s %d", key.c_str(), bit); + return command_integer(dbi, pos, fmt::format("BITPOS {} {}", key.c_str(), bit).c_str()); } bool xRedisClient::decr(const RedisDBIdx &dbi, const std::string &key, int64_t &result) { SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, result, "decr %s", key.c_str()); + return command_integer(dbi, result, fmt::format("decr {}", key).c_str()); } bool xRedisClient::decrby(const RedisDBIdx &dbi, const std::string &key, int32_t by, int64_t &result) { SETDEFAULTIOTYPE(MASTER); - return command_integer(dbi, result, "decrby %s %d", key.c_str(), by); + return command_integer(dbi, result, fmt::format("decrby {} {}", key.c_str(), by).c_str()); } diff --git a/src/xRedisClusterClient.cpp b/src/xRedisClusterClient.cpp index 4be4064..6b354c3 100644 --- a/src/xRedisClusterClient.cpp +++ b/src/xRedisClusterClient.cpp @@ -1,4 +1,7 @@ +#include +#include #include "xredis.h" + using namespace xrc; static const uint16_t crc16tab[256] = { @@ -155,7 +158,7 @@ bool xRedisClusterClient::GetClusterNodes(redisContext *redis_ctx) } Str2Vect(redis_reply->str, vlines, "\n"); - printf("vlines:%lu\r\n", vlines.size()); + fmt::printf("vlines:{}\r\n", vlines.size()); for (size_t i = 0; i < vlines.size(); ++i) { @@ -166,17 +169,17 @@ bool xRedisClusterClient::GetClusterNodes(redisContext *redis_ctx) Str2Vect(node.strinfo.c_str(), nodeinfo, " "); for (size_t k = 0; k < nodeinfo.size(); ++k) { - printf("%lu : %s \r\n", k, nodeinfo[k].c_str()); + fmt::printf("{} : {} \r\n", k, nodeinfo[k].c_str()); } if (NULL == strstr(nodeinfo[2].c_str(), "master")) { - printf("%s \r\n", nodeinfo[2].c_str()); + fmt::printf("{} \r\n", nodeinfo[2].c_str()); continue; } node.id = nodeinfo[0]; node.ParseNodeString(nodeinfo[1]); node.ParseSlotString(nodeinfo[8]); - printf("------------------------\r\n"); + fmt::printf("------------------------\r\n"); } freeReplyObject(redis_reply); @@ -188,7 +191,7 @@ void xRedisClusterClient::Keepalive() //RedisConnIter iter = mRedisConnList.begin(); //for (; iter != mRedisConnList.end(); iter++) { // redisReply *reply = (redisReply *)redisCommand((*iter)->c,"PING"); - // printf("PING: %s\n", reply->str); + // fmt::printf("PING: {}\n", reply->str); // freeReplyObject(reply); //} @@ -243,11 +246,11 @@ bool xRedisClusterClient::CheckReply(redisReply *reply) { if (NULL == reply) { - printf("error, reply is NULL \r\n"); + fmt::printf("error, reply is NULL \r\n"); return false; } - printf("DEBBUG %d:%s \r\n", reply->type, reply->str); + fmt::printf("DEBBUG {}:{} \r\n", reply->type, reply->str); return true; } @@ -263,10 +266,10 @@ bool xRedisClusterClient::ClusterEnabled(redisContext *ctx) } return false; } - //printf("redis info:\r\n%s\r\n", redis_reply->str); + //fmt::printf("redis info:\r\n{}\r\n", redis_reply->str); char *p = strstr(redis_reply->str, "cluster_enabled:"); bool bRet = p != NULL && (0 == strncmp(p + strlen("cluster_enabled:"), "1", 1)); - //printf("--:%s\r\n", p + strlen("cluster_enabled:")); + //fmt::printf("--:{}\r\n", p + strlen("cluster_enabled:")); freeReplyObject(redis_reply); return bRet; } @@ -282,7 +285,7 @@ bool xRedisClusterClient::ClusterInfo(redisContext *ctx) } return false; } - //printf("Clusterinfo:\r\n%s\r\n", redis_reply->str); + //fmt::printf("Clusterinfo:\r\n{}\r\n", redis_reply->str); char *p = strstr(redis_reply->str, ":"); bool bRet = (0 == strncmp(p + 1, "ok", 2)); freeReplyObject(redis_reply); @@ -300,7 +303,7 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t { if (NULL == host) { - printf("error argv \r\n"); + fmt::printf("error argv \r\n"); return false; } @@ -314,22 +317,22 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t { if (redis_ctx) { - printf("Connection error: %s \r\n", redis_ctx->errstr); + fmt::printf("Connection error: {} \r\n", redis_ctx->errstr); redisFree(redis_ctx); return false; } else { - printf("Connection error: can't allocate redis context, %s \n", redis_ctx->errstr); + fmt::printf("Connection error: can't allocate redis context, {} \n", redis_ctx->errstr); } } else { - printf("Connect to Redis: %s:%d success \n", host, port); + fmt::printf("Connect to Redis: {}:{} success \n", host, port); } mClusterEnabled = ClusterEnabled(redis_ctx); - printf("ClusterEnabled %d \r\n", mClusterEnabled); + fmt::printf("ClusterEnabled {} \r\n", mClusterEnabled); if (!mClusterEnabled) { @@ -340,7 +343,7 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t if (!ClusterInfo(redis_ctx)) { - printf("ClusterInfo error \r\n"); + fmt::printf("ClusterInfo error \r\n"); return false; } @@ -357,7 +360,7 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t } Str2Vect(redis_reply->str, vlines, "\n"); - printf("vlines:%lu\r\n", vlines.size()); + fmt::printf("vlines:{}\r\n", vlines.size()); for (size_t i = 0; i < vlines.size(); ++i) { @@ -368,22 +371,22 @@ bool xRedisClusterClient::ConnectRedis(const char *host, uint32_t port, uint32_t Str2Vect(node.strinfo.c_str(), nodeinfo, " "); for (size_t k = 0; k < nodeinfo.size(); ++k) { - printf("%lu : %s \r\n", k, nodeinfo[k].c_str()); + fmt::printf("{} : {} \r\n", k, nodeinfo[k].c_str()); } if (NULL != strstr(nodeinfo[7].c_str(), "disconnected")) { - //printf("%s \r\n", nodeinfo[7].c_str()); + //fmt::printf("{} \r\n", nodeinfo[7].c_str()); continue; } if (NULL == strstr(nodeinfo[2].c_str(), "master")) { - printf("%s \r\n", nodeinfo[2].c_str()); + fmt::printf("{} \r\n", nodeinfo[2].c_str()); continue; } node.id = nodeinfo[0]; node.ParseNodeString(nodeinfo[1]); node.ParseSlotString(nodeinfo[8]); - printf("------------------------\r\n"); + fmt::printf("------------------------\r\n"); vNodes.push_back(node); } @@ -406,7 +409,7 @@ bool xRedisClusterClient::ConnectRedisNode(int32_t idx, const char *host, uint32 { if (NULL == host) { - printf("error argv \r\n"); + fmt::printf("error argv \r\n"); return false; } @@ -422,7 +425,7 @@ bool xRedisClusterClient::ConnectRedisNode(int32_t idx, const char *host, uint32 RedisConnection *pRedisconn = new RedisConnection; if (NULL == pRedisconn) { - printf("error pRedisconn is null, %s %d \r\n", host, port); + fmt::printf("error pRedisconn is null, {} {} \r\n", host, port); continue; } pRedisconn->mHost = host; @@ -434,19 +437,19 @@ bool xRedisClusterClient::ConnectRedisNode(int32_t idx, const char *host, uint32 { if (pRedisconn->mCtx) { - printf("Connection error: %s \r\n", pRedisconn->mCtx->errstr); + fmt::printf("Connection error: {} \r\n", pRedisconn->mCtx->errstr); redisFree(pRedisconn->mCtx); } else { - printf("Connection error: can't allocate redis context, %s \n", pRedisconn->mCtx->errstr); + fmt::printf("Connection error: can't allocate redis context, {} \n", pRedisconn->mCtx->errstr); } delete pRedisconn; } else { - printf("Connect to Redis[%u]: %s:%d poolsize:%d success \n", - idx, host, port, poolsize); + fmt::printf("Connect to Redis[%u]: {}:{} poolsize:{} success \n", + idx, host, port, poolsize); mRedisConnList[idx].push_back(pRedisconn); } } @@ -470,13 +473,13 @@ RedisConnection *xRedisClusterClient::GetConnection(uint32_t idx) } else { - printf("RedisPool::GetConnection() error pthread_id=%lu \n", - (unsigned long)std::hash()(std::this_thread::get_id())); + fmt::printf("RedisPool::GetConnection() error pthread_id={} \n", + (unsigned long)std::hash()(std::this_thread::get_id())); } } std::this_thread::sleep_for(std::chrono::seconds(1)); } - printf("idx:%u %s:%u \n", idx, pRedisConn->mHost, pRedisConn->mPort); + fmt::printf("idx:%u {}:%u \n", idx, pRedisConn->mHost, pRedisConn->mPort); return pRedisConn; } @@ -526,7 +529,7 @@ uint32_t xRedisClusterClient::FindNodeIndex(uint32_t slot) NodeInfo *pNode = &vNodes[i]; if (pNode->CheckSlot(slot)) { - printf("FindNode %u:%lu\n", slot, i); + fmt::printf("FindNode %u:{}\n", slot, i); return i; } } @@ -548,7 +551,7 @@ RedisConnection *xRedisClusterClient::FindNodeConnection(const char *key) { return GetConnection(0); } - printf("key:%s \r\n", key); + fmt::printf("key:{} \r\n", key); uint32_t slot_id = GetKeySlotIndex(key); uint32_t index = FindNodeIndex(slot_id); return GetConnection(index); @@ -563,10 +566,10 @@ bool xRedisClusterClient::RedisCommand(RedisResult &result, const char *format, va_list args; va_start(args, format); key = va_arg(args, char *); - printf("key:%p \n", key); + fmt::printf("key:%p \n", key); if (0 == strlen(key)) { - printf("key is NULL key:%p \n", key); + fmt::printf("key is NULL key:%p \n", key); return false; } pRedisConn = FindNodeConnection(key); @@ -579,8 +582,8 @@ bool xRedisClusterClient::RedisCommand(RedisResult &result, const char *format, { result.Init(reply); - printf("%d %lld %d %s %lu \r\n", - reply->type, reply->integer, reply->len, reply->str, reply->elements); + fmt::printf("{} {} {} {} {} \r\n", + reply->type, reply->integer, reply->len, reply->str, reply->elements); bRet = true; } @@ -615,8 +618,8 @@ bool xRedisClusterClient::RedisCommandArgv(const VSTRING &vDataIn, RedisResult & if (xRedisClusterClient::CheckReply(reply)) { result.Init(reply); - printf("%d %lld %d %s %lu \r\n", - reply->type, reply->integer, reply->len, reply->str, reply->elements); + fmt::printf("{} {} {} {} {} \r\n", + reply->type, reply->integer, reply->len, reply->str, reply->elements); bRet = true; } else diff --git a/src/xRedisPool.cpp b/src/xRedisPool.cpp index f8446bc..5293a1b 100644 --- a/src/xRedisPool.cpp +++ b/src/xRedisPool.cpp @@ -6,6 +6,9 @@ * ---------------------------------------------------------------------------- */ #include +#include +#include + #include "xredis.h" using namespace xrc; @@ -208,7 +211,7 @@ bool RedisConn::auth() } else { - redisReply *reply = static_cast(redisCommand(mCtx, "AUTH %s", mPass.c_str())); + redisReply *reply = static_cast(redisCommand(mCtx, fmt::format("AUTH {}", mPass).c_str())); if ((NULL == reply) || (strcasecmp(reply->str, "OK") != 0)) { bRet = false; From 5ff523f304ddfee3a59ba48d4df27d9f3e77faec Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Mon, 20 Apr 2020 00:51:39 +0800 Subject: [PATCH 23/24] add target added check --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 11eab14..5d6d406 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ endif() find_package(fmt CONFIG REQUIRED) find_package(hiredis) -if (NOT ${hiredis_FOUND}) +if (NOT (TARGET hiredis OR ${hiredis_FOUND})) message("Dependency 'hiredis' is not within CMake package sources, attempting to add it manually") find_path(hiredis_INCLUDE_DIR hiredis/hiredis.h) if (hiredis_INCLUDE_DIR) From e5bb43d71f5e4d1afa5e4da313dd1dd8e5a838c0 Mon Sep 17 00:00:00 2001 From: Steve Fan <19037626d@connect.polyu.hk> Date: Mon, 20 Apr 2020 00:59:48 +0800 Subject: [PATCH 24/24] add static and shared build --- CMakeLists.txt | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5d6d406..b6001fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,13 +2,13 @@ cmake_minimum_required (VERSION 3.15) project(xredis CXX) if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) - include(CTest) + include(CTest) endif() find_package(fmt CONFIG REQUIRED) find_package(hiredis) -if (NOT (TARGET hiredis OR ${hiredis_FOUND})) +if (NOT TARGET hiredis) message("Dependency 'hiredis' is not within CMake package sources, attempting to add it manually") find_path(hiredis_INCLUDE_DIR hiredis/hiredis.h) if (hiredis_INCLUDE_DIR) @@ -32,32 +32,55 @@ file(GLOB xredis_SOURCES ${xredis_SOURCE_DIR}/src/*.cpp ) -add_library (xredis ${xredis_SOURCES}) +# Static +add_library (xredis-static ${xredis_SOURCES}) target_include_directories( - xredis + xredis-static PUBLIC ${xredis_SOURCE_DIR}/include PRIVATE ${xredis_SOURCE_DIR}/include/xredis ) target_link_libraries( - xredis + xredis-static PRIVATE hiredis fmt::fmt fmt::fmt-header-only ) +# Shared +add_library (xredis-shared ${xredis_SOURCES}) + +target_include_directories( + xredis-shared + PUBLIC ${xredis_SOURCE_DIR}/include + PRIVATE ${xredis_SOURCE_DIR}/include/xredis +) + +target_link_libraries( + xredis-shared + PRIVATE hiredis fmt::fmt +) + if (MSVC) target_link_libraries( - xredis + xredis-static + PUBLIC ws2_32 + ) + + target_link_libraries( + xredis-shared PUBLIC ws2_32 ) endif() +add_library(xredis::static ALIAS xredis-static) +add_library(xredis::shared ALIAS xredis-shared) + if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING) add_executable(xredis_test EXCLUDE_FROM_ALL test/xredis-test.cpp) target_link_libraries( xredis_test - PRIVATE xredis hiredis + PRIVATE xredis::static hiredis ) add_test(