redis采用的是RedisClusterStrictRedis,这两个库的区别在于一个用于redis集群,一个非集群
    所以,当在配置文件内定义is_colony=True 的时候就会采用RedisCluster(集群),否则为StrictRedis(非集群)

    RedisCluster入参及使用说明见redis.RedisCluster,以下为部分

    1. class Redis(object):
    2. """
    3. Implementation of the Redis protocol.
    4. This abstract class provides a Python interface to all Redis commands
    5. and an implementation of the Redis protocol.
    6. Connection and Pipeline derive from this, implementing how
    7. the commands are sent and received to the Redis server
    8. """
    9. RESPONSE_CALLBACKS = dict_merge(
    10. string_keys_to_dict(
    11. 'AUTH EXPIRE EXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST '
    12. 'PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNX',
    13. bool
    14. ),
    15. string_keys_to_dict(
    16. 'BITCOUNT BITPOS DECRBY DEL EXISTS GEOADD GETBIT HDEL HLEN '
    17. 'HSTRLEN INCRBY LINSERT LLEN LPUSHX PFADD PFCOUNT RPUSHX SADD '
    18. 'SCARD SDIFFSTORE SETBIT SETRANGE SINTERSTORE SREM STRLEN '
    19. 'SUNIONSTORE UNLINK XACK XDEL XLEN XTRIM ZCARD ZLEXCOUNT ZREM '
    20. 'ZREMRANGEBYLEX ZREMRANGEBYRANK ZREMRANGEBYSCORE',
    21. int
    22. ),
    23. string_keys_to_dict(
    24. 'INCRBYFLOAT HINCRBYFLOAT',
    25. float
    26. ),
    27. string_keys_to_dict(
    28. # these return OK, or int if redis-server is >=1.3.4
    29. 'LPUSH RPUSH',
    30. lambda r: isinstance(r, (long, int)) and r or nativestr(r) == 'OK'
    31. ),
    32. string_keys_to_dict('SORT', sort_return_tuples),
    33. string_keys_to_dict('ZSCORE ZINCRBY GEODIST', float_or_none),
    34. string_keys_to_dict(
    35. 'FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE READONLY READWRITE '
    36. 'RENAME SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH ',
    37. bool_ok
    38. ),
    39. string_keys_to_dict('BLPOP BRPOP', lambda r: r and tuple(r) or None),
    40. string_keys_to_dict(
    41. 'SDIFF SINTER SMEMBERS SUNION',
    42. lambda r: r and set(r) or set()
    43. ),
    44. string_keys_to_dict(
    45. 'ZPOPMAX ZPOPMIN ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE',
    46. zset_score_pairs
    47. ),
    48. string_keys_to_dict('BZPOPMIN BZPOPMAX', \
    49. lambda r: r and (r[0], r[1], float(r[2])) or None),
    50. string_keys_to_dict('ZRANK ZREVRANK', int_or_none),
    51. string_keys_to_dict('XREVRANGE XRANGE', parse_stream_list),
    52. string_keys_to_dict('XREAD XREADGROUP', parse_xread),
    53. string_keys_to_dict('BGREWRITEAOF BGSAVE', lambda r: True),
    54. {
    55. 'ACL CAT': lambda r: list(map(nativestr, r)),
    56. 'ACL DELUSER': int,
    57. 'ACL GENPASS': nativestr,
    58. 'ACL GETUSER': parse_acl_getuser,
    59. 'ACL LIST': lambda r: list(map(nativestr, r)),
    60. 'ACL LOAD': bool_ok,
    61. 'ACL SAVE': bool_ok,
    62. 'ACL SETUSER': bool_ok,
    63. 'ACL USERS': lambda r: list(map(nativestr, r)),
    64. 'ACL WHOAMI': nativestr,
    65. 'CLIENT GETNAME': lambda r: r and nativestr(r),
    66. 'CLIENT ID': int,
    67. 'CLIENT KILL': parse_client_kill,
    68. 'CLIENT LIST': parse_client_list,
    69. 'CLIENT SETNAME': bool_ok,
    70. 'CLIENT UNBLOCK': lambda r: r and int(r) == 1 or False,
    71. 'CLIENT PAUSE': bool_ok,
    72. 'CLUSTER ADDSLOTS': bool_ok,
    73. 'CLUSTER COUNT-FAILURE-REPORTS': lambda x: int(x),
    74. 'CLUSTER COUNTKEYSINSLOT': lambda x: int(x),
    75. 'CLUSTER DELSLOTS': bool_ok,
    76. 'CLUSTER FAILOVER': bool_ok,
    77. 'CLUSTER FORGET': bool_ok,
    78. 'CLUSTER INFO': parse_cluster_info,
    79. 'CLUSTER KEYSLOT': lambda x: int(x),
    80. 'CLUSTER MEET': bool_ok,
    81. 'CLUSTER NODES': parse_cluster_nodes,
    82. 'CLUSTER REPLICATE': bool_ok,
    83. 'CLUSTER RESET': bool_ok,
    84. 'CLUSTER SAVECONFIG': bool_ok,
    85. 'CLUSTER SET-CONFIG-EPOCH': bool_ok,
    86. 'CLUSTER SETSLOT': bool_ok,
    87. 'CLUSTER SLAVES': parse_cluster_nodes,
    88. 'CONFIG GET': parse_config_get,
    89. 'CONFIG RESETSTAT': bool_ok,
    90. 'CONFIG SET': bool_ok,
    91. 'DEBUG OBJECT': parse_debug_object,
    92. 'GEOHASH': lambda r: list(map(nativestr_or_none, r)),
    93. 'GEOPOS': lambda r: list(map(lambda ll: (float(ll[0]),
    94. float(ll[1]))
    95. if ll is not None else None, r)),
    96. 'GEORADIUS': parse_georadius_generic,
    97. 'GEORADIUSBYMEMBER': parse_georadius_generic,
    98. 'HGETALL': lambda r: r and pairs_to_dict(r) or {},
    99. 'HSCAN': parse_hscan,
    100. 'INFO': parse_info,
    101. 'LASTSAVE': timestamp_to_datetime,
    102. 'MEMORY PURGE': bool_ok,
    103. 'MEMORY STATS': parse_memory_stats,
    104. 'MEMORY USAGE': int_or_none,
    105. 'OBJECT': parse_object,
    106. 'PING': lambda r: nativestr(r) == 'PONG',
    107. 'PUBSUB NUMSUB': parse_pubsub_numsub,
    108. 'RANDOMKEY': lambda r: r and r or None,
    109. 'SCAN': parse_scan,
    110. 'SCRIPT EXISTS': lambda r: list(imap(bool, r)),
    111. 'SCRIPT FLUSH': bool_ok,
    112. 'SCRIPT KILL': bool_ok,
    113. 'SCRIPT LOAD': nativestr,
    114. 'SENTINEL GET-MASTER-ADDR-BY-NAME': parse_sentinel_get_master,
    115. 'SENTINEL MASTER': parse_sentinel_master,
    116. 'SENTINEL MASTERS': parse_sentinel_masters,
    117. 'SENTINEL MONITOR': bool_ok,
    118. 'SENTINEL REMOVE': bool_ok,
    119. 'SENTINEL SENTINELS': parse_sentinel_slaves_and_sentinels,
    120. 'SENTINEL SET': bool_ok,
    121. 'SENTINEL SLAVES': parse_sentinel_slaves_and_sentinels,
    122. 'SET': lambda r: r and nativestr(r) == 'OK',
    123. 'SLOWLOG GET': parse_slowlog_get,
    124. 'SLOWLOG LEN': int,
    125. 'SLOWLOG RESET': bool_ok,
    126. 'SSCAN': parse_scan,
    127. 'TIME': lambda x: (int(x[0]), int(x[1])),
    128. 'XCLAIM': parse_xclaim,
    129. 'XGROUP CREATE': bool_ok,
    130. 'XGROUP DELCONSUMER': int,
    131. 'XGROUP DESTROY': bool,
    132. 'XGROUP SETID': bool_ok,
    133. 'XINFO CONSUMERS': parse_list_of_dicts,
    134. 'XINFO GROUPS': parse_list_of_dicts,
    135. 'XINFO STREAM': parse_xinfo_stream,
    136. 'XPENDING': parse_xpending,
    137. 'ZADD': parse_zadd,
    138. 'ZSCAN': parse_zscan,
    139. }
    140. )
    141. @classmethod
    142. def from_url(cls, url, db=None, **kwargs):
    143. """
    144. Return a Redis client object configured from the given URL
    145. For example::
    146. redis://[[username]:[password]]@localhost:6379/0
    147. rediss://[[username]:[password]]@localhost:6379/0
    148. unix://[[username]:[password]]@/path/to/socket.sock?db=0
    149. Three URL schemes are supported:
    150. - ```redis://``
    151. <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ creates a
    152. normal TCP socket connection
    153. - ```rediss://``
    154. <http://www.iana.org/assignments/uri-schemes/prov/rediss>`_ creates a
    155. SSL wrapped TCP socket connection
    156. - ``unix://`` creates a Unix Domain Socket connection
    157. There are several ways to specify a database number. The parse function
    158. will return the first specified option:
    159. 1. A ``db`` querystring option, e.g. redis://localhost?db=0
    160. 2. If using the redis:// scheme, the path argument of the url, e.g.
    161. redis://localhost/0
    162. 3. The ``db`` argument to this function.
    163. If none of these options are specified, db=0 is used.
    164. Any additional querystring arguments and keyword arguments will be
    165. passed along to the ConnectionPool class's initializer. In the case
    166. of conflicting arguments, querystring arguments always win.
    167. """
    168. connection_pool = ConnectionPool.from_url(url, db=db, **kwargs)
    169. return cls(connection_pool=connection_pool)
    170. def __init__(self, host='localhost', port=6379,
    171. db=0, password=None, socket_timeout=None,
    172. socket_connect_timeout=None,
    173. socket_keepalive=None, socket_keepalive_options=None,
    174. connection_pool=None, unix_socket_path=None,
    175. encoding='utf-8', encoding_errors='strict',
    176. charset=None, errors=None,
    177. decode_responses=False, retry_on_timeout=False,
    178. ssl=False, ssl_keyfile=None, ssl_certfile=None,
    179. ssl_cert_reqs='required', ssl_ca_certs=None,
    180. ssl_check_hostname=False,
    181. max_connections=None, single_connection_client=False,
    182. health_check_interval=0, client_name=None, username=None):
    183. def pipeline(self, transaction=True, shard_hint=None):
    184. """
    185. Return a new pipeline object that can queue multiple commands for
    186. later execution. ``transaction`` indicates whether all commands
    187. should be executed atomically. Apart from making a group of operations
    188. atomic, pipelines are useful for reducing the back-and-forth overhead
    189. between the client and server.
    190. """
    191. def transaction(self, func, *watches, **kwargs):
    192. """
    193. Convenience method for executing the callable `func` as a transaction
    194. while watching all keys specified in `watches`. The 'func' callable
    195. should expect a single argument which is a Pipeline object.
    196. """
    197. def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None,
    198. lock_class=None, thread_local=True):
    199. """
    200. Return a new Lock object using key ``name`` that mimics
    201. the behavior of threading.Lock.
    202. If specified, ``timeout`` indicates a maximum life for the lock.
    203. By default, it will remain locked until release() is called.
    204. ``sleep`` indicates the amount of time to sleep per loop iteration
    205. when the lock is in blocking mode and another client is currently
    206. holding the lock.
    207. ``blocking_timeout`` indicates the maximum amount of time in seconds to
    208. spend trying to acquire the lock. A value of ``None`` indicates
    209. continue trying forever. ``blocking_timeout`` can be specified as a
    210. float or integer, both representing the number of seconds to wait.
    211. ``lock_class`` forces the specified lock implementation.
    212. ``thread_local`` indicates whether the lock token is placed in
    213. thread-local storage. By default, the token is placed in thread local
    214. storage so that a thread only sees its token, not a token set by
    215. another thread. Consider the following timeline:
    216. time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
    217. thread-1 sets the token to "abc"
    218. time: 1, thread-2 blocks trying to acquire `my-lock` using the
    219. Lock instance.
    220. time: 5, thread-1 has not yet completed. redis expires the lock
    221. key.
    222. time: 5, thread-2 acquired `my-lock` now that it's available.
    223. thread-2 sets the token to "xyz"
    224. time: 6, thread-1 finishes its work and calls release(). if the
    225. token is *not* stored in thread local storage, then
    226. thread-1 would see the token value as "xyz" and would be
    227. able to successfully release the thread-2's lock.
    228. In some use cases it's necessary to disable thread local storage. For
    229. example, if you have code where one thread acquires a lock and passes
    230. that lock instance to a worker thread to release later. If thread
    231. local storage isn't disabled in this case, the worker thread won't see
    232. the token set by the thread that acquired the lock. Our assumption
    233. is that these cases aren't common and as such default to using
    234. thread local storage. """
    235. def pubsub(self, **kwargs):
    236. """
    237. Return a Publish/Subscribe object. With this object, you can
    238. subscribe to channels and listen for messages that get published to
    239. them.
    240. """
    241. def close(self):
    242. """
    243. """
    244. def execute_command(self, *args, **options):
    245. "Execute a command and return a parsed response"
    246. def acl_list(self):
    247. "Return a list of all ACLs on the server"
    248. def acl_load(self):
    249. """
    250. Load ACL rules from the configured ``aclfile``.
    251. Note that the server must be configured with the ``aclfile``
    252. directive to be able to load ACL rules from an aclfile.
    253. """
    254. def acl_save(self):
    255. """
    256. Save ACL rules to the configured ``aclfile``.
    257. Note that the server must be configured with the ``aclfile``
    258. directive to be able to save ACL rules to an aclfile.
    259. """
    260. def acl_setuser(self, username, enabled=False, nopass=False,
    261. passwords=None, hashed_passwords=None, categories=None,
    262. commands=None, keys=None, reset=False, reset_keys=False,
    263. reset_passwords=False):
    264. """
    265. Create or update an ACL user.
    266. Create or update the ACL for ``username``. If the user already exists,
    267. the existing ACL is completely overwritten and replaced with the
    268. specified values.
    269. ``enabled`` is a boolean indicating whether the user should be allowed
    270. to authenticate or not. Defaults to ``False``.
    271. ``nopass`` is a boolean indicating whether the can authenticate without
    272. a password. This cannot be True if ``passwords`` are also specified.
    273. ``passwords`` if specified is a list of plain text passwords
    274. to add to or remove from the user. Each password must be prefixed with
    275. a '+' to add or a '-' to remove. For convenience, the value of
    276. ``add_passwords`` can be a simple prefixed string when adding or
    277. removing a single password.
    278. ``hashed_passwords`` if specified is a list of SHA-256 hashed passwords
    279. to add to or remove from the user. Each hashed password must be
    280. prefixed with a '+' to add or a '-' to remove. For convenience,
    281. the value of ``hashed_passwords`` can be a simple prefixed string when
    282. adding or removing a single password.
    283. ``categories`` if specified is a list of strings representing category
    284. permissions. Each string must be prefixed with either a '+' to add the
    285. category permission or a '-' to remove the category permission.
    286. ``commands`` if specified is a list of strings representing command
    287. permissions. Each string must be prefixed with either a '+' to add the
    288. command permission or a '-' to remove the command permission.
    289. ``keys`` if specified is a list of key patterns to grant the user
    290. access to. Keys patterns allow '*' to support wildcard matching. For
    291. example, '*' grants access to all keys while 'cache:*' grants access
    292. to all keys that are prefixed with 'cache:'. ``keys`` should not be
    293. prefixed with a '~'.
    294. ``reset`` is a boolean indicating whether the user should be fully
    295. reset prior to applying the new ACL. Setting this to True will
    296. remove all existing passwords, flags and privileges from the user and
    297. then apply the specified rules. If this is False, the user's existing
    298. passwords, flags and privileges will be kept and any new specified
    299. rules will be applied on top.
    300. ``reset_keys`` is a boolean indicating whether the user's key
    301. permissions should be reset prior to applying any new key permissions
    302. specified in ``keys``. If this is False, the user's existing
    303. key permissions will be kept and any new specified key permissions
    304. will be applied on top.
    305. ``reset_passwords`` is a boolean indicating whether to remove all
    306. existing passwords and the 'nopass' flag from the user prior to
    307. applying any new passwords specified in 'passwords' or
    308. 'hashed_passwords'. If this is False, the user's existing passwords
    309. and 'nopass' status will be kept and any new specified passwords
    310. or hashed_passwords will be applied on top.
    311. """
    312. def acl_users(self):
    313. "Returns a list of all registered users on the server."
    314. def acl_whoami(self):
    315. "Get the username for the current connection"
    316. def bgrewriteaof(self):
    317. "Tell the Redis server to rewrite the AOF file from data in memory."
    318. def bgsave(self):
    319. """
    320. Tell the Redis server to save its data to disk. Unlike save(),
    321. this method is asynchronous and returns immediately.
    322. """
    323. def client_kill(self, address):
    324. "Disconnects the client at ``address`` (ip:port)"
    325. def client_kill_filter(self, _id=None, _type=None, addr=None, skipme=None):
    326. """
    327. Disconnects client(s) using a variety of filter options
    328. :param id: Kills a client by its unique ID field
    329. :param type: Kills a client by type where type is one of 'normal',
    330. 'master', 'slave' or 'pubsub'
    331. :param addr: Kills a client by its 'address:port'
    332. :param skipme: If True, then the client calling the command
    333. will not get killed even if it is identified by one of the filter
    334. options. If skipme is not provided, the server defaults to skipme=True
    335. """
    336. def client_list(self, _type=None):
    337. """
    338. Returns a list of currently connected clients.
    339. If type of client specified, only that type will be returned.
    340. :param _type: optional. one of the client types (normal, master,
    341. replica, pubsub)
    342. """
    343. def client_getname(self):
    344. "Returns the current connection name"
    345. def client_id(self):
    346. "Returns the current connection id"
    347. def client_setname(self, name):
    348. "Sets the current connection name"
    349. def client_unblock(self, client_id, error=False):
    350. """
    351. Unblocks a connection by its client id.
    352. If ``error`` is True, unblocks the client with a special error message.
    353. If ``error`` is False (default), the client is unblocked using the
    354. regular timeout mechanism.
    355. """
    356. def client_pause(self, timeout):
    357. """
    358. Suspend all the Redis clients for the specified amount of time
    359. :param timeout: milliseconds to pause clients
    360. """
    361. def readwrite(self):
    362. "Disables read queries for a connection to a Redis Cluster slave node"
    363. def readonly(self):
    364. "Enables read queries for a connection to a Redis Cluster replica node"
    365. def config_get(self, pattern="*"):
    366. "Return a dictionary of configuration based on the ``pattern``"
    367. def config_set(self, name, value):
    368. "Set config item ``name`` with ``value``"
    369. def config_resetstat(self):
    370. "Reset runtime statistics"
    371. def config_rewrite(self):
    372. "Rewrite config file with the minimal change to reflect running config"
    373. def dbsize(self):
    374. "Returns the number of keys in the current database"
    375. def debug_object(self, key):
    376. "Returns version specific meta information about a given key"
    377. def echo(self, value):
    378. "Echo the string back from the server"
    379. def flushall(self, asynchronous=False):
    380. """
    381. Delete all keys in all databases on the current host.
    382. ``asynchronous`` indicates whether the operation is
    383. executed asynchronously by the server.
    384. """
    385. def flushdb(self, asynchronous=False):
    386. """
    387. Delete all keys in the current database.
    388. ``asynchronous`` indicates whether the operation is
    389. executed asynchronously by the server.
    390. """
    391. def swapdb(self, first, second):
    392. "Swap two databases"
    393. def info(self, section=None):
    394. """
    395. Returns a dictionary containing information about the Redis server
    396. The ``section`` option can be used to select a specific section
    397. of information
    398. The section option is not supported by older versions of Redis Server,
    399. and will generate ResponseError
    400. """
    401. def lastsave(self):
    402. """
    403. Return a Python datetime object representing the last time the
    404. Redis database was saved to disk
    405. """
    406. def migrate(self, host, port, keys, destination_db, timeout,
    407. copy=False, replace=False, auth=None):
    408. """
    409. Migrate 1 or more keys from the current Redis server to a different
    410. server specified by the ``host``, ``port`` and ``destination_db``.
    411. The ``timeout``, specified in milliseconds, indicates the maximum
    412. time the connection between the two servers can be idle before the
    413. command is interrupted.
    414. If ``copy`` is True, the specified ``keys`` are NOT deleted from
    415. the source server.
    416. If ``replace`` is True, this operation will overwrite the keys
    417. on the destination server if they exist.
    418. If ``auth`` is specified, authenticate to the destination server with
    419. the password provided.
    420. """
    421. def object(self, infotype, key):
    422. "Return the encoding, idletime, or refcount about the key"
    423. def memory_stats(self):
    424. "Return a dictionary of memory stats"
    425. def memory_usage(self, key, samples=None):
    426. """
    427. Return the total memory usage for key, its value and associated
    428. administrative overheads.
    429. For nested data structures, ``samples`` is the number of elements to
    430. sample. If left unspecified, the server's default is 5. Use 0 to sample
    431. all elements.
    432. """
    433. def memory_purge(self):
    434. "Attempts to purge dirty pages for reclamation by allocator"
    435. def ping(self):
    436. "Ping the Redis server"
    437. def save(self):
    438. """
    439. Tell the Redis server to save its data to disk,
    440. blocking until the save is complete
    441. """
    442. def sentinel(self, *args):
    443. "Redis Sentinel's SENTINEL command."
    444. def sentinel_get_master_addr_by_name(self, service_name):
    445. "Returns a (host, port) pair for the given ``service_name``"
    446. def sentinel_master(self, service_name):
    447. "Returns a dictionary containing the specified masters state."
    448. def sentinel_masters(self):
    449. "Returns a list of dictionaries containing each master's state."
    450. def sentinel_monitor(self, name, ip, port, quorum):
    451. "Add a new master to Sentinel to be monitored"
    452. def sentinel_remove(self, name):
    453. "Remove a master from Sentinel's monitoring"
    454. def sentinel_sentinels(self, service_name):
    455. "Returns a list of sentinels for ``service_name``"
    456. def sentinel_set(self, name, option, value):
    457. "Set Sentinel monitoring parameters for a given master"
    458. def sentinel_slaves(self, service_name):
    459. "Returns a list of slaves for ``service_name``"
    460. def shutdown(self, save=False, nosave=False):
    461. """Shutdown the Redis server. If Redis has persistence configured,
    462. data will be flushed before shutdown. If the "save" option is set,
    463. a data flush will be attempted even if there is no persistence
    464. configured. If the "nosave" option is set, no data flush will be
    465. attempted. The "save" and "nosave" options cannot both be set.
    466. """
    467. def slaveof(self, host=None, port=None):
    468. """
    469. Set the server to be a replicated slave of the instance identified
    470. by the ``host`` and ``port``. If called without arguments, the
    471. instance is promoted to a master instead.
    472. """
    473. def slowlog_get(self, num=None):
    474. """
    475. Get the entries from the slowlog. If ``num`` is specified, get the
    476. most recent ``num`` items.
    477. """
    478. def slowlog_len(self):
    479. "Get the number of items in the slowlog"
    480. def slowlog_reset(self):
    481. "Remove all items in the slowlog"
    482. def time(self):
    483. """
    484. Returns the server time as a 2-item tuple of ints:
    485. (seconds since epoch, microseconds into this second).
    486. """
    487. def wait(self, num_replicas, timeout):
    488. """
    489. Redis synchronous replication
    490. That returns the number of replicas that processed the query when
    491. we finally have at least ``num_replicas``, or when the ``timeout`` was
    492. reached.
    493. """
    494. def append(self, key, value):
    495. """
    496. Appends the string ``value`` to the value at ``key``. If ``key``
    497. doesn't already exist, create it with a value of ``value``.
    498. Returns the new length of the value at ``key``.
    499. """
    500. def bitcount(self, key, start=None, end=None):
    501. """
    502. Returns the count of set bits in the value of ``key``. Optional
    503. ``start`` and ``end`` paramaters indicate which bytes to consider
    504. """
    505. def bitfield(self, key, default_overflow=None):
    506. """
    507. Return a BitFieldOperation instance to conveniently construct one or
    508. more bitfield operations on ``key``.
    509. """
    510. def bitop(self, operation, dest, *keys):
    511. """
    512. Perform a bitwise operation using ``operation`` between ``keys`` and
    513. store the result in ``dest``.
    514. """
    515. def bitpos(self, key, bit, start=None, end=None):
    516. """
    517. Return the position of the first bit set to 1 or 0 in a string.
    518. ``start`` and ``end`` difines search range. The range is interpreted
    519. as a range of bytes and not a range of bits, so start=0 and end=2
    520. means to look at the first three bytes.
    521. """
    522. def decr(self, name, amount=1):
    523. """
    524. Decrements the value of ``key`` by ``amount``. If no key exists,
    525. the value will be initialized as 0 - ``amount``
    526. """
    527. # An alias for ``decr()``, because it is already implemented
    528. # as DECRBY redis command.
    529. def decrby(self, name, amount=1):
    530. """
    531. Decrements the value of ``key`` by ``amount``. If no key exists,
    532. the value will be initialized as 0 - ``amount``
    533. """
    534. def delete(self, *names):
    535. "Delete one or more keys specified by ``names``"
    536. def dump(self, name):
    537. """
    538. Return a serialized version of the value stored at the specified key.
    539. If key does not exist a nil bulk reply is returned.
    540. """
    541. def exists(self, *names):
    542. "Returns the number of ``names`` that exist"
    543. def expire(self, name, time):
    544. """
    545. Set an expire flag on key ``name`` for ``time`` seconds. ``time``
    546. can be represented by an integer or a Python timedelta object.
    547. """
    548. def expireat(self, name, when):
    549. """
    550. Set an expire flag on key ``name``. ``when`` can be represented
    551. as an integer indicating unix time or a Python datetime object.
    552. """
    553. def get(self, name):
    554. """
    555. Return the value at key ``name``, or None if the key doesn't exist
    556. """
    557. def getbit(self, name, offset):
    558. "Returns a boolean indicating the value of ``offset`` in ``name``"
    559. def getrange(self, key, start, end):
    560. """
    561. Returns the substring of the string value stored at ``key``,
    562. determined by the offsets ``start`` and ``end`` (both are inclusive)
    563. """
    564. def getset(self, name, value):
    565. """
    566. Sets the value at key ``name`` to ``value``
    567. and returns the old value at key ``name`` atomically.
    568. """
    569. def incr(self, name, amount=1):
    570. """
    571. Increments the value of ``key`` by ``amount``. If no key exists,
    572. the value will be initialized as ``amount``
    573. """
    574. def incrby(self, name, amount=1):
    575. """
    576. Increments the value of ``key`` by ``amount``. If no key exists,
    577. the value will be initialized as ``amount``
    578. """
    579. # An alias for ``incr()``, because it is already implemented
    580. # as INCRBY redis command.
    581. def incrbyfloat(self, name, amount=1.0):
    582. """
    583. Increments the value at key ``name`` by floating ``amount``.
    584. If no key exists, the value will be initialized as ``amount``
    585. """
    586. def keys(self, pattern='*'):
    587. "Returns a list of keys matching ``pattern``"
    588. def mget(self, keys, *args):
    589. """
    590. Returns a list of values ordered identically to ``keys``
    591. """
    592. def mset(self, mapping):
    593. """
    594. Sets key/values based on a mapping. Mapping is a dictionary of
    595. key/value pairs. Both keys and values should be strings or types that
    596. can be cast to a string via str().
    597. """
    598. def msetnx(self, mapping):
    599. """
    600. Sets key/values based on a mapping if none of the keys are already set.
    601. Mapping is a dictionary of key/value pairs. Both keys and values
    602. should be strings or types that can be cast to a string via str().
    603. Returns a boolean indicating if the operation was successful.
    604. """
    605. def move(self, name, db):
    606. "Moves the key ``name`` to a different Redis database ``db``"
    607. def persist(self, name):
    608. "Removes an expiration on ``name``"
    609. def pexpire(self, name, time):
    610. """
    611. Set an expire flag on key ``name`` for ``time`` milliseconds.
    612. ``time`` can be represented by an integer or a Python timedelta
    613. object.
    614. """
    615. def pexpireat(self, name, when):
    616. """
    617. Set an expire flag on key ``name``. ``when`` can be represented
    618. as an integer representing unix time in milliseconds (unix time * 1000)
    619. or a Python datetime object.
    620. """
    621. def psetex(self, name, time_ms, value):
    622. """
    623. Set the value of key ``name`` to ``value`` that expires in ``time_ms``
    624. milliseconds. ``time_ms`` can be represented by an integer or a Python
    625. timedelta object
    626. """
    627. def pttl(self, name):
    628. "Returns the number of milliseconds until the key ``name`` will expire"
    629. def randomkey(self):
    630. "Returns the name of a random key"
    631. def rename(self, src, dst):
    632. """
    633. Rename key ``src`` to ``dst``
    634. """
    635. def renamenx(self, src, dst):
    636. "Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"
    637. def restore(self, name, ttl, value, replace=False):
    638. """
    639. Create a key using the provided serialized value, previously obtained
    640. using DUMP.
    641. """
    642. def set(self, name, value,
    643. ex=None, px=None, nx=False, xx=False, keepttl=False):
    644. """
    645. Set the value at key ``name`` to ``value``
    646. ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
    647. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
    648. ``nx`` if set to True, set the value at key ``name`` to ``value`` only
    649. if it does not exist.
    650. ``xx`` if set to True, set the value at key ``name`` to ``value`` only
    651. if it already exists.
    652. ``keepttl`` if True, retain the time to live associated with the key.
    653. (Available since Redis 6.0)
    654. """
    655. def setbit(self, name, offset, value):
    656. """
    657. Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
    658. indicating the previous value of ``offset``.
    659. """
    660. def setex(self, name, time, value):
    661. """
    662. Set the value of key ``name`` to ``value`` that expires in ``time``
    663. seconds. ``time`` can be represented by an integer or a Python
    664. timedelta object.
    665. """
    666. def setnx(self, name, value):
    667. "Set the value of key ``name`` to ``value`` if key doesn't exist"
    668. def setrange(self, name, offset, value):
    669. """
    670. Overwrite bytes in the value of ``name`` starting at ``offset`` with
    671. ``value``. If ``offset`` plus the length of ``value`` exceeds the
    672. length of the original value, the new value will be larger than before.
    673. If ``offset`` exceeds the length of the original value, null bytes
    674. will be used to pad between the end of the previous value and the start
    675. of what's being injected.
    676. Returns the length of the new string.
    677. """
    678. def strlen(self, name):
    679. "Return the number of bytes stored in the value of ``name``"
    680. def substr(self, name, start, end=-1):
    681. """
    682. Return a substring of the string at key ``name``. ``start`` and ``end``
    683. are 0-based integers specifying the portion of the string to return.
    684. """
    685. def touch(self, *args):
    686. """
    687. Alters the last access time of a key(s) ``*args``. A key is ignored
    688. if it does not exist.
    689. """
    690. def ttl(self, name):
    691. "Returns the number of seconds until the key ``name`` will expire"
    692. def type(self, name):
    693. "Returns the type of key ``name``"
    694. def watch(self, *names):
    695. """
    696. Watches the values at keys ``names``, or None if the key doesn't exist
    697. """
    698. def unwatch(self):
    699. """
    700. Unwatches the value at key ``name``, or None of the key doesn't exist
    701. """
    702. def unlink(self, *names):
    703. "Unlink one or more keys specified by ``names``"
    704. # LIST COMMANDS
    705. def blpop(self, keys, timeout=0):
    706. """
    707. LPOP a value off of the first non-empty list
    708. named in the ``keys`` list.
    709. If none of the lists in ``keys`` has a value to LPOP, then block
    710. for ``timeout`` seconds, or until a value gets pushed on to one
    711. of the lists.
    712. If timeout is 0, then block indefinitely.
    713. """
    714. def brpop(self, keys, timeout=0):
    715. """
    716. RPOP a value off of the first non-empty list
    717. named in the ``keys`` list.
    718. If none of the lists in ``keys`` has a value to RPOP, then block
    719. for ``timeout`` seconds, or until a value gets pushed on to one
    720. of the lists.
    721. If timeout is 0, then block indefinitely.
    722. """
    723. def brpoplpush(self, src, dst, timeout=0):
    724. """
    725. Pop a value off the tail of ``src``, push it on the head of ``dst``
    726. and then return it.
    727. This command blocks until a value is in ``src`` or until ``timeout``
    728. seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
    729. forever.
    730. """
    731. def lindex(self, name, index):
    732. """
    733. Return the item from list ``name`` at position ``index``
    734. Negative indexes are supported and will return an item at the
    735. end of the list
    736. """
    737. def linsert(self, name, where, refvalue, value):
    738. """
    739. Insert ``value`` in list ``name`` either immediately before or after
    740. [``where``] ``refvalue``
    741. Returns the new length of the list on success or -1 if ``refvalue``
    742. is not in the list.
    743. """
    744. def llen(self, name):
    745. "Return the length of the list ``name``"
    746. def lpop(self, name):
    747. "Remove and return the first item of the list ``name``"
    748. def lpush(self, name, *values):
    749. "Push ``values`` onto the head of the list ``name``"
    750. def lpushx(self, name, value):
    751. "Push ``value`` onto the head of the list ``name`` if ``name`` exists"
    752. def lrange(self, name, start, end):
    753. """
    754. Return a slice of the list ``name`` between
    755. position ``start`` and ``end``
    756. ``start`` and ``end`` can be negative numbers just like
    757. Python slicing notation
    758. """
    759. def lrem(self, name, count, value):
    760. """
    761. Remove the first ``count`` occurrences of elements equal to ``value``
    762. from the list stored at ``name``.
    763. The count argument influences the operation in the following ways:
    764. count > 0: Remove elements equal to value moving from head to tail.
    765. count < 0: Remove elements equal to value moving from tail to head.
    766. count = 0: Remove all elements equal to value.
    767. """
    768. def lset(self, name, index, value):
    769. "Set ``position`` of list ``name`` to ``value``"
    770. def ltrim(self, name, start, end):
    771. """
    772. Trim the list ``name``, removing all values not within the slice
    773. between ``start`` and ``end``
    774. ``start`` and ``end`` can be negative numbers just like
    775. Python slicing notation
    776. """
    777. def rpop(self, name):
    778. "Remove and return the last item of the list ``name``"
    779. def rpoplpush(self, src, dst):
    780. """
    781. RPOP a value off of the ``src`` list and atomically LPUSH it
    782. on to the ``dst`` list. Returns the value.
    783. """
    784. def rpush(self, name, *values):
    785. "Push ``values`` onto the tail of the list ``name``"
    786. def rpushx(self, name, value):
    787. "Push ``value`` onto the tail of the list ``name`` if ``name`` exists"
    788. def sort(self, name, start=None, num=None, by=None, get=None,
    789. desc=False, alpha=False, store=None, groups=False):
    790. """
    791. Sort and return the list, set or sorted set at ``name``.
    792. ``start`` and ``num`` allow for paging through the sorted data
    793. ``by`` allows using an external key to weight and sort the items.
    794. Use an "*" to indicate where in the key the item value is located
    795. ``get`` allows for returning items from external keys rather than the
    796. sorted data itself. Use an "*" to indicate where in the key
    797. the item value is located
    798. ``desc`` allows for reversing the sort
    799. ``alpha`` allows for sorting lexicographically rather than numerically
    800. ``store`` allows for storing the result of the sort into
    801. the key ``store``
    802. ``groups`` if set to True and if ``get`` contains at least two
    803. elements, sort will return a list of tuples, each containing the
    804. values fetched from the arguments to ``get``.
    805. """
    806. def scan(self, cursor=0, match=None, count=None, _type=None):
    807. """
    808. Incrementally return lists of key names. Also return a cursor
    809. indicating the scan position.
    810. ``match`` allows for filtering the keys by pattern
    811. ``count`` provides a hint to Redis about the number of keys to
    812. return per batch.
    813. ``_type`` filters the returned values by a particular Redis type.
    814. Stock Redis instances allow for the following types:
    815. HASH, LIST, SET, STREAM, STRING, ZSET
    816. Additionally, Redis modules can expose other types as well.
    817. """
    818. def scan_iter(self, match=None, count=None, _type=None):
    819. """
    820. Make an iterator using the SCAN command so that the client doesn't
    821. need to remember the cursor position.
    822. ``match`` allows for filtering the keys by pattern
    823. ``count`` provides a hint to Redis about the number of keys to
    824. return per batch.
    825. ``_type`` filters the returned values by a particular Redis type.
    826. Stock Redis instances allow for the following types:
    827. HASH, LIST, SET, STREAM, STRING, ZSET
    828. Additionally, Redis modules can expose other types as well.
    829. """
    830. def sscan(self, name, cursor=0, match=None, count=None):
    831. """
    832. Incrementally return lists of elements in a set. Also return a cursor
    833. indicating the scan position.
    834. ``match`` allows for filtering the keys by pattern
    835. ``count`` allows for hint the minimum number of returns
    836. """
    837. def sscan_iter(self, name, match=None, count=None):
    838. """
    839. Make an iterator using the SSCAN command so that the client doesn't
    840. need to remember the cursor position.
    841. ``match`` allows for filtering the keys by pattern
    842. ``count`` allows for hint the minimum number of returns
    843. """
    844. def hscan(self, name, cursor=0, match=None, count=None):
    845. """
    846. Incrementally return key/value slices in a hash. Also return a cursor
    847. indicating the scan position.
    848. ``match`` allows for filtering the keys by pattern
    849. ``count`` allows for hint the minimum number of returns
    850. """
    851. def hscan_iter(self, name, match=None, count=None):
    852. """
    853. Make an iterator using the HSCAN command so that the client doesn't
    854. need to remember the cursor position.
    855. ``match`` allows for filtering the keys by pattern
    856. ``count`` allows for hint the minimum number of returns
    857. """
    858. def zscan(self, name, cursor=0, match=None, count=None,
    859. score_cast_func=float):
    860. """
    861. Incrementally return lists of elements in a sorted set. Also return a
    862. cursor indicating the scan position.
    863. ``match`` allows for filtering the keys by pattern
    864. ``count`` allows for hint the minimum number of returns
    865. ``score_cast_func`` a callable used to cast the score return value
    866. """
    867. def zscan_iter(self, name, match=None, count=None,
    868. score_cast_func=float):
    869. """
    870. Make an iterator using the ZSCAN command so that the client doesn't
    871. need to remember the cursor position.
    872. ``match`` allows for filtering the keys by pattern
    873. ``count`` allows for hint the minimum number of returns
    874. ``score_cast_func`` a callable used to cast the score return value
    875. """
    876. def sadd(self, name, *values):
    877. "Add ``value(s)`` to set ``name``"
    878. def scard(self, name):
    879. "Return the number of elements in set ``name``"
    880. def sdiff(self, keys, *args):
    881. "Return the difference of sets specified by ``keys``"
    882. def sdiffstore(self, dest, keys, *args):
    883. """
    884. Store the difference of sets specified by ``keys`` into a new
    885. set named ``dest``. Returns the number of keys in the new set.
    886. """
    887. def sinter(self, keys, *args):
    888. "Return the intersection of sets specified by ``keys``"
    889. def sinterstore(self, dest, keys, *args):
    890. """
    891. Store the intersection of sets specified by ``keys`` into a new
    892. set named ``dest``. Returns the number of keys in the new set.
    893. """
    894. def sismember(self, name, value):
    895. "Return a boolean indicating if ``value`` is a member of set ``name``"
    896. def smembers(self, name):
    897. "Return all members of the set ``name``"
    898. def smove(self, src, dst, value):
    899. "Move ``value`` from set ``src`` to set ``dst`` atomically"
    900. def spop(self, name, count=None):
    901. "Remove and return a random member of set ``name``"
    902. def srandmember(self, name, number=None):
    903. """
    904. If ``number`` is None, returns a random member of set ``name``.
    905. If ``number`` is supplied, returns a list of ``number`` random
    906. members of set ``name``. Note this is only available when running
    907. Redis 2.6+.
    908. """
    909. def srem(self, name, *values):
    910. "Remove ``values`` from set ``name``"
    911. def sunion(self, keys, *args):
    912. "Return the union of sets specified by ``keys``"
    913. def sunionstore(self, dest, keys, *args):
    914. """
    915. Store the union of sets specified by ``keys`` into a new
    916. set named ``dest``. Returns the number of keys in the new set.
    917. """
    918. def xack(self, name, groupname, *ids):
    919. """
    920. Acknowledges the successful processing of one or more messages.
    921. name: name of the stream.
    922. groupname: name of the consumer group.
    923. *ids: message ids to acknowlege.
    924. """
    925. def xadd(self, name, fields, id='*', maxlen=None, approximate=True):
    926. """
    927. Add to a stream.
    928. name: name of the stream
    929. fields: dict of field/value pairs to insert into the stream
    930. id: Location to insert this record. By default it is appended.
    931. maxlen: truncate old stream members beyond this size
    932. approximate: actual stream length may be slightly more than maxlen
    933. """
    934. def xclaim(self, name, groupname, consumername, min_idle_time, message_ids,
    935. idle=None, time=None, retrycount=None, force=False,
    936. justid=False):
    937. """
    938. Changes the ownership of a pending message.
    939. name: name of the stream.
    940. groupname: name of the consumer group.
    941. consumername: name of a consumer that claims the message.
    942. min_idle_time: filter messages that were idle less than this amount of
    943. milliseconds
    944. message_ids: non-empty list or tuple of message IDs to claim
    945. idle: optional. Set the idle time (last time it was delivered) of the
    946. message in ms
    947. time: optional integer. This is the same as idle but instead of a
    948. relative amount of milliseconds, it sets the idle time to a specific
    949. Unix time (in milliseconds).
    950. retrycount: optional integer. set the retry counter to the specified
    951. value. This counter is incremented every time a message is delivered
    952. again.
    953. force: optional boolean, false by default. Creates the pending message
    954. entry in the PEL even if certain specified IDs are not already in the
    955. PEL assigned to a different client.
    956. justid: optional boolean, false by default. Return just an array of IDs
    957. of messages successfully claimed, without returning the actual message
    958. """
    959. def xdel(self, name, *ids):
    960. """
    961. Deletes one or more messages from a stream.
    962. name: name of the stream.
    963. *ids: message ids to delete.
    964. """
    965. return self.execute_command('XDEL', name, *ids)
    966. def xgroup_create(self, name, groupname, id='$', mkstream=False):
    967. """
    968. Create a new consumer group associated with a stream.
    969. name: name of the stream.
    970. groupname: name of the consumer group.
    971. id: ID of the last item in the stream to consider already delivered.
    972. """
    973. def xgroup_delconsumer(self, name, groupname, consumername):
    974. """
    975. Remove a specific consumer from a consumer group.
    976. Returns the number of pending messages that the consumer had before it
    977. was deleted.
    978. name: name of the stream.
    979. groupname: name of the consumer group.
    980. consumername: name of consumer to delete
    981. """
    982. def xgroup_destroy(self, name, groupname):
    983. """
    984. Destroy a consumer group.
    985. name: name of the stream.
    986. groupname: name of the consumer group.
    987. """
    988. def xgroup_setid(self, name, groupname, id):
    989. """
    990. Set the consumer group last delivered ID to something else.
    991. name: name of the stream.
    992. groupname: name of the consumer group.
    993. id: ID of the last item in the stream to consider already delivered.
    994. """
    995. def xinfo_consumers(self, name, groupname):
    996. """
    997. Returns general information about the consumers in the group.
    998. name: name of the stream.
    999. groupname: name of the consumer group.
    1000. """
    1001. def xinfo_groups(self, name):
    1002. """
    1003. Returns general information about the consumer groups of the stream.
    1004. name: name of the stream.
    1005. """
    1006. def xinfo_stream(self, name):
    1007. """
    1008. Returns general information about the stream.
    1009. name: name of the stream.
    1010. """
    1011. def xlen(self, name):
    1012. """
    1013. Returns the number of elements in a given stream.
    1014. """
    1015. def xpending(self, name, groupname):
    1016. """
    1017. Returns information about pending messages of a group.
    1018. name: name of the stream.
    1019. groupname: name of the consumer group.
    1020. """
    1021. def xpending_range(self, name, groupname, min, max, count,
    1022. consumername=None):
    1023. """
    1024. Returns information about pending messages, in a range.
    1025. name: name of the stream.
    1026. groupname: name of the consumer group.
    1027. min: minimum stream ID.
    1028. max: maximum stream ID.
    1029. count: number of messages to return
    1030. consumername: name of a consumer to filter by (optional).
    1031. """
    1032. def xrange(self, name, min='-', max='+', count=None):
    1033. """
    1034. Read stream values within an interval.
    1035. name: name of the stream.
    1036. start: first stream ID. defaults to '-',
    1037. meaning the earliest available.
    1038. finish: last stream ID. defaults to '+',
    1039. meaning the latest available.
    1040. count: if set, only return this many items, beginning with the
    1041. earliest available.
    1042. """
    1043. def xread(self, streams, count=None, block=None):
    1044. """
    1045. Block and monitor multiple streams for new data.
    1046. streams: a dict of stream names to stream IDs, where
    1047. IDs indicate the last ID already seen.
    1048. count: if set, only return this many items, beginning with the
    1049. earliest available.
    1050. block: number of milliseconds to wait, if nothing already present.
    1051. """
    1052. # HASH COMMANDS
    1053. def hdel(self, name, *keys):
    1054. "Delete ``keys`` from hash ``name``"
    1055. def hexists(self, name, key):
    1056. "Returns a boolean indicating if ``key`` exists within hash ``name``"
    1057. def hget(self, name, key):
    1058. "Return the value of ``key`` within the hash ``name``"
    1059. def hgetall(self, name):
    1060. "Return a Python dict of the hash's name/value pairs"

    RedisCluster入参及使用说明见rediscluster.RedisCluster,以下为部分

    1. class RedisCluster(Redis):
    2. def __init__(self, host=None, port=None, startup_nodes=None, max_connections=None, max_connections_per_node=False, init_slot_cache=True,
    3. readonly_mode=False, reinitialize_steps=None, skip_full_coverage_check=False, nodemanager_follow_cluster=False,
    4. connection_class=None, read_from_replicas=False, cluster_down_retry_attempts=3, host_port_remap=None, **kwargs):
    5. """
    6. :startup_nodes:
    7. List of nodes that initial bootstrapping can be done from
    8. :host:
    9. Can be used to point to a startup node
    10. :port:
    11. Can be used to point to a startup node
    12. :max_connections:
    13. Maximum number of connections that should be kept open at one time
    14. :readonly_mode:
    15. enable READONLY mode. You can read possibly stale data from slave.
    16. :skip_full_coverage_check:
    17. Skips the check of cluster-require-full-coverage config, useful for clusters
    18. without the CONFIG command (like aws)
    19. :nodemanager_follow_cluster:
    20. The node manager will during initialization try the last set of nodes that
    21. it was operating on. This will allow the client to drift along side the cluster
    22. if the cluster nodes move around alot.
    23. :**kwargs:
    24. Extra arguments that will be sent into Redis instance when created
    25. (See Official redis-py doc for supported kwargs
    26. [https://github.com/andymccurdy/redis-py/blob/master/redis/client.py])
    27. Some kwargs is not supported and will raise RedisClusterException
    28. - db (Redis do not support database SELECT in cluster mode)
    29. """
    30. def set(self, name, value,
    31. ex=None, px=None, nx=False, xx=False, keepttl=False):
    32. """
    33. Set the value at key ``name`` to ``value``
    34. ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
    35. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
    36. ``nx`` if set to True, set the value at key ``name`` to ``value`` only
    37. if it does not exist.
    38. ``xx`` if set to True, set the value at key ``name`` to ``value`` only
    39. if it already exists.
    40. ``keepttl`` if True, retain the time to live associated with the key.
    41. (Available since Redis 6.0)
    42. """
    43. @classmethod
    44. def from_url(cls, url, db=None, skip_full_coverage_check=False, readonly_mode=False, read_from_replicas=False, **kwargs):
    45. """
    46. Return a Redis client object configured from the given URL, which must
    47. use either `the ``redis://`` scheme
    48. <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ for RESP
    49. connections or the ``unix://`` scheme for Unix domain sockets.
    50. For example::
    51. redis://[:password]@localhost:6379/0
    52. unix://[:password]@/path/to/socket.sock?db=0
    53. There are several ways to specify a database number. The parse function
    54. will return the first specified option:
    55. 1. A ``db`` querystring option, e.g. redis://localhost?db=0
    56. 2. If using the redis:// scheme, the path argument of the url, e.g.
    57. redis://localhost/0
    58. 3. The ``db`` argument to this function.
    59. If none of these options are specified, db=0 is used.
    60. Any additional querystring arguments and keyword arguments will be
    61. passed along to the ConnectionPool class's initializer. In the case
    62. of conflicting arguments, querystring arguments always win.
    63. """
    64. def set_result_callback(self, command, callback):
    65. "Set a custom Result Callback"
    66. def pubsub(self, **kwargs):
    67. """
    68. """
    69. def pipeline(self, transaction=None, shard_hint=None, read_from_replicas=False):
    70. """
    71. Cluster impl:
    72. Pipelines do not work in cluster mode the same way they do in normal mode.
    73. Create a clone of this object so that simulating pipelines will work correctly.
    74. Each command will be called directly when used and when calling execute() will only return the result stack.
    75. """
    76. def transaction(self, *args, **kwargs):
    77. """
    78. Transaction is not implemented in cluster mode yet.
    79. """
    80. def execute_command(self, *args, **kwargs):
    81. """
    82. Wrapper for CLUSTERDOWN error handling.
    83. If the cluster reports it is down it is assumed that:
    84. - connection_pool was disconnected
    85. - connection_pool was reseted
    86. - refereh_table_asap set to True
    87. It will try the number of times specified by the config option "self.cluster_down_retry_attempts"
    88. which defaults to 3 unless manually configured.
    89. If it reaches the number of times, the command will raises ClusterDownException.
    90. """
    91. def _execute_command(self, *args, **kwargs):
    92. """
    93. Send a command to a node in the cluster
    94. """
    95. def mget(self, keys, *args):
    96. """
    97. Returns a list of values ordered identically to ``keys``
    98. Cluster impl:
    99. Itterate all keys and send GET for each key.
    100. This will go alot slower than a normal mget call in Redis.
    101. Operation is no longer atomic.
    102. """
    103. def mset(self, *args, **kwargs):
    104. """
    105. Sets key/values based on a mapping. Mapping can be supplied as a single
    106. dictionary argument or as kwargs.
    107. Cluster impl:
    108. Itterate over all items and do SET on each (k,v) pair
    109. Operation is no longer atomic.
    110. """
    111. def msetnx(self, *args, **kwargs):
    112. """
    113. Sets key/values based on a mapping if none of the keys are already set.
    114. Mapping can be supplied as a single dictionary argument or as kwargs.
    115. Returns a boolean indicating if the operation was successful.
    116. Clutser impl:
    117. Itterate over all items and do GET to determine if all keys do not exists.
    118. If true then call mset() on all keys.
    119. """
    120. def rename(self, src, dst, replace=False):
    121. """
    122. Rename key ``src`` to ``dst``
    123. Cluster impl:
    124. If the src and dsst keys is in the same slot then send a plain RENAME
    125. command to that node to do the rename inside the server.
    126. If the keys is in crossslots then use the client side implementation
    127. as fallback method. In this case this operation is no longer atomic as
    128. the key is dumped and posted back to the server through the client.
    129. """
    130. def delete(self, *names):
    131. """
    132. "Delete one or more keys specified by ``names``"
    133. Cluster impl:
    134. Iterate all keys and send DELETE for each key.
    135. This will go a lot slower than a normal delete call in Redis.
    136. Operation is no longer atomic.
    137. """
    138. def renamenx(self, src, dst):
    139. """
    140. Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist
    141. Cluster impl:
    142. Check if dst key do not exists, then calls rename().
    143. Operation is no longer atomic.
    144. """
    145. def pubsub_channels(self, pattern='*', aggregate=True):
    146. """
    147. Return a list of channels that have at least one subscriber.
    148. Aggregate toggles merging of response.
    149. """
    150. def pubsub_numpat(self, aggregate=True):
    151. """
    152. Returns the number of subscriptions to patterns.
    153. Aggregate toggles merging of response.
    154. """
    155. def pubsub_numsub(self, *args, **kwargs):
    156. """
    157. Return a list of (channel, number of subscribers) tuples
    158. for each channel given in ``*args``.
    159. ``aggregate`` keyword argument toggles merging of response.
    160. """
    161. def brpoplpush(self, src, dst, timeout=0):
    162. """
    163. Pop a value off the tail of ``src``, push it on the head of ``dst``
    164. and then return it.
    165. This command blocks until a value is in ``src`` or until ``timeout``
    166. seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
    167. forever.
    168. Cluster impl:
    169. Call brpop() then send the result into lpush()
    170. Operation is no longer atomic.
    171. """
    172. def rpoplpush(self, src, dst):
    173. """
    174. RPOP a value off of the ``src`` list and atomically LPUSH it
    175. on to the ``dst`` list. Returns the value.
    176. Cluster impl:
    177. Call rpop() then send the result into lpush()
    178. Operation is no longer atomic.
    179. """
    180. def sdiff(self, keys, *args):
    181. """
    182. Return the difference of sets specified by ``keys``
    183. Cluster impl:
    184. Querry all keys and diff all sets and return result
    185. """
    186. def sdiffstore(self, dest, keys, *args):
    187. """
    188. Store the difference of sets specified by ``keys`` into a new
    189. set named ``dest``. Returns the number of keys in the new set.
    190. Overwrites dest key if it exists.
    191. Cluster impl:
    192. Use sdiff() --> Delete dest key --> store result in dest key
    193. """
    194. def sinter(self, keys, *args):
    195. """
    196. Return the intersection of sets specified by ``keys``
    197. Cluster impl:
    198. Querry all keys, intersection and return result
    199. """
    200. def sinterstore(self, dest, keys, *args):
    201. """
    202. Store the intersection of sets specified by ``keys`` into a new
    203. set named ``dest``. Returns the number of keys in the new set.
    204. Cluster impl:
    205. Use sinter() --> Delete dest key --> store result in dest key
    206. """
    207. def smove(self, src, dst, value):
    208. """
    209. Move ``value`` from set ``src`` to set ``dst`` atomically
    210. Cluster impl:
    211. SMEMBERS --> SREM --> SADD. Function is no longer atomic.
    212. """
    213. def sunion(self, keys, *args):
    214. """
    215. Return the union of sets specified by ``keys``
    216. Cluster impl:
    217. Querry all keys, union and return result
    218. Operation is no longer atomic.
    219. """
    220. def sunionstore(self, dest, keys, *args):
    221. """
    222. Store the union of sets specified by ``keys`` into a new
    223. set named ``dest``. Returns the number of keys in the new set.
    224. Cluster impl:
    225. Use sunion() --> Dlete dest key --> store result in dest key
    226. Operation is no longer atomic.
    227. """
    228. def pfcount(self, *sources):
    229. """
    230. pfcount only works when all sources point to the same hash slot.
    231. """
    232. def pfmerge(self, dest, *sources):
    233. """
    234. Merge N different HyperLogLogs into a single one.
    235. Cluster impl:
    236. Very special implementation is required to make pfmerge() work
    237. But it works :]
    238. It works by first fetching all HLL objects that should be merged and
    239. move them to one hashslot so that pfmerge operation can be performed without
    240. any 'CROSSSLOT' error.
    241. After the PFMERGE operation is done then it will be moved to the correct location
    242. within the cluster and cleanup is done.
    243. This operation is no longer atomic because of all the operations that has to be done.
    244. """