1. 程式人生 > >15天玩轉redis —— 第五篇 集合物件型別

15天玩轉redis —— 第五篇 集合物件型別

  1 /*
  2  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
  3  * All rights reserved.
  4  *
  5  * Redistribution and use in source and binary forms, with or without
  6  * modification, are permitted provided that the following conditions are met:
  7  *
  8  *   * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer. 10 * * Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13
* * Neither the name of Redis nor the names of its contributors may be used 14 * to endorse or promote products derived from this software without 15 * specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27 * POSSIBILITY OF SUCH DAMAGE. 28 */ 29 30 #include "redis.h" 31 32 /*----------------------------------------------------------------------------- 33 * Set Commands 34 *----------------------------------------------------------------------------*/ 35 36 void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op); 37 38 /* Factory method to return a set that *can* hold "value". When the object has 39 * an integer-encodable value, an intset will be returned. Otherwise a regular 40 * hash table. */ 41 robj *setTypeCreate(robj *value) { 42 if (isObjectRepresentableAsLongLong(value,NULL) == REDIS_OK) 43 return createIntsetObject(); 44 return createSetObject(); 45 } 46 47 int setTypeAdd(robj *subject, robj *value) { 48 long long llval; 49 if (subject->encoding == REDIS_ENCODING_HT) { 50 if (dictAdd(subject->ptr,value,NULL) == DICT_OK) { 51 incrRefCount(value); 52 return 1; 53 } 54 } else if (subject->encoding == REDIS_ENCODING_INTSET) { 55 if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) { 56 uint8_t success = 0; 57 subject->ptr = intsetAdd(subject->ptr,llval,&success); 58 if (success) { 59 /* Convert to regular set when the intset contains 60 * too many entries. */ 61 if (intsetLen(subject->ptr) > server.set_max_intset_entries) 62 setTypeConvert(subject,REDIS_ENCODING_HT); 63 return 1; 64 } 65 } else { 66 /* Failed to get integer from object, convert to regular set. */ 67 setTypeConvert(subject,REDIS_ENCODING_HT); 68 69 /* The set *was* an intset and this value is not integer 70 * encodable, so dictAdd should always work. */ 71 redisAssertWithInfo(NULL,value,dictAdd(subject->ptr,value,NULL) == DICT_OK); 72 incrRefCount(value); 73 return 1; 74 } 75 } else { 76 redisPanic("Unknown set encoding"); 77 } 78 return 0; 79 } 80 81 int setTypeRemove(robj *setobj, robj *value) { 82 long long llval; 83 if (setobj->encoding == REDIS_ENCODING_HT) { 84 if (dictDelete(setobj->ptr,value) == DICT_OK) { 85 if (htNeedsResize(setobj->ptr)) dictResize(setobj->ptr); 86 return 1; 87 } 88 } else if (setobj->encoding == REDIS_ENCODING_INTSET) { 89 if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) { 90 int success; 91 setobj->ptr = intsetRemove(setobj->ptr,llval,&success); 92 if (success) return 1; 93 } 94 } else { 95 redisPanic("Unknown set encoding"); 96 } 97 return 0; 98 } 99 100 int setTypeIsMember(robj *subject, robj *value) { 101 long long llval; 102 if (subject->encoding == REDIS_ENCODING_HT) { 103 return dictFind((dict*)subject->ptr,value) != NULL; 104 } else if (subject->encoding == REDIS_ENCODING_INTSET) { 105 if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) { 106 return intsetFind((intset*)subject->ptr,llval); 107 } 108 } else { 109 redisPanic("Unknown set encoding"); 110 } 111 return 0; 112 } 113 114 setTypeIterator *setTypeInitIterator(robj *subject) { 115 setTypeIterator *si = zmalloc(sizeof(setTypeIterator)); 116 si->subject = subject; 117 si->encoding = subject->encoding; 118 if (si->encoding == REDIS_ENCODING_HT) { 119 si->di = dictGetIterator(subject->ptr); 120 } else if (si->encoding == REDIS_ENCODING_INTSET) { 121 si->ii = 0; 122 } else { 123 redisPanic("Unknown set encoding"); 124 } 125 return si; 126 } 127 128 void setTypeReleaseIterator(setTypeIterator *si) { 129 if (si->encoding == REDIS_ENCODING_HT) 130 dictReleaseIterator(si->di); 131 zfree(si); 132 } 133 134 /* Move to the next entry in the set. Returns the object at the current 135 * position. 136 * 137 * Since set elements can be internally be stored as redis objects or 138 * simple arrays of integers, setTypeNext returns the encoding of the 139 * set object you are iterating, and will populate the appropriate pointer 140 * (eobj) or (llobj) accordingly. 141 * 142 * When there are no longer elements -1 is returned. 143 * Returned objects ref count is not incremented, so this function is 144 * copy on write friendly. */ 145 int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele) { 146 if (si->encoding == REDIS_ENCODING_HT) { 147 dictEntry *de = dictNext(si->di); 148 if (de == NULL) return -1; 149 *objele = dictGetKey(de); 150 } else if (si->encoding == REDIS_ENCODING_INTSET) { 151 if (!intsetGet(si->subject->ptr,si->ii++,llele)) 152 return -1; 153 } 154 return si->encoding; 155 } 156 157 /* The not copy on write friendly version but easy to use version 158 * of setTypeNext() is setTypeNextObject(), returning new objects 159 * or incrementing the ref count of returned objects. So if you don't 160 * retain a pointer to this object you should call decrRefCount() against it. 161 * 162 * This function is the way to go for write operations where COW is not 163 * an issue as the result will be anyway of incrementing the ref count. */ 164 robj *setTypeNextObject(setTypeIterator *si) { 165 int64_t intele; 166 robj *objele; 167 int encoding; 168 169 encoding = setTypeNext(si,&objele,&intele); 170 switch(encoding) { 171 case -1: return NULL; 172 case REDIS_ENCODING_INTSET: 173 return createStringObjectFromLongLong(intele); 174 case REDIS_ENCODING_HT: 175 incrRefCount(objele); 176 return objele; 177 default: 178 redisPanic("Unsupported encoding"); 179 } 180 return NULL; /* just to suppress warnings */ 181 } 182 183 /* Return random element from a non empty set. 184 * The returned element can be a int64_t value if the set is encoded 185 * as an "intset" blob of integers, or a redis object if the set 186 * is a regular set. 187 * 188 * The caller provides both pointers to be populated with the right 189 * object. The return value of the function is the object->encoding 190 * field of the object and is used by the caller to check if the 191 * int64_t pointer or the redis object pointer was populated. 192 * 193 * When an object is returned (the set was a real set) the ref count 194 * of the object is not incremented so this function can be considered 195 * copy on write friendly. */ 196 int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele) { 197 if (setobj->encoding == REDIS_ENCODING_HT) { 198 dictEntry *de = dictGetRandomKey(setobj->ptr); 199 *objele = dictGetKey(de); 200 } else if (setobj->encoding == REDIS_ENCODING_INTSET) { 201 *llele = intsetRandom(setobj->ptr); 202 } else { 203 redisPanic("Unknown set encoding"); 204 } 205 return setobj->encoding; 206 } 207 208 unsigned long setTypeSize(robj *subject) { 209 if (subject->encoding == REDIS_ENCODING_HT) { 210 return dictSize((dict*)subject->ptr); 211 } else if (subject->encoding == REDIS_ENCODING_INTSET) { 212 return intsetLen((intset*)subject->ptr); 213 } else { 214 redisPanic("Unknown set encoding"); 215 } 216 } 217 218 /* Convert the set to specified encoding. The resulting dict (when converting 219 * to a hash table) is presized to hold the number of elements in the original 220 * set. */ 221 void setTypeConvert(robj *setobj, int enc) { 222 setTypeIterator *si; 223 redisAssertWithInfo(NULL,setobj,setobj->type == REDIS_SET && 224 setobj->encoding == REDIS_ENCODING_INTSET); 225 226 if (enc == REDIS_ENCODING_HT) { 227 int64_t intele; 228 dict *d = dictCreate(&setDictType,NULL); 229 robj *element; 230 231 /* Presize the dict to avoid rehashing */ 232 dictExpand(d,intsetLen(setobj->ptr)); 233 234 /* To add the elements we extract integers and create redis objects */ 235 si = setTypeInitIterator(setobj); 236 while (setTypeNext(si,NULL,&intele) != -1) { 237 element = createStringObjectFromLongLong(intele); 238 redisAssertWithInfo(NULL,element,dictAdd(d,element,NULL) == DICT_OK); 239 } 240 setTypeReleaseIterator(si); 241 242 setobj->encoding = REDIS_ENCODING_HT; 243 zfree(setobj->ptr); 244 setobj->ptr = d; 245 } else { 246 redisPanic("Unsupported set conversion"); 247 } 248 } 249 250 void saddCommand(redisClient *c) { 251 robj *set; 252 int j, added = 0; 253 254 set = lookupKeyWrite(c->db,c->argv[1]); 255 if (set == NULL) { 256 set = setTypeCreate(c->argv[2]); 257 dbAdd(c->db,c->argv[1],set); 258 } else { 259 if (set->type != REDIS_SET) { 260 addReply(c,shared.wrongtypeerr); 261 return; 262 } 263 } 264 265 for (j = 2; j < c->argc; j++) { 266 c->argv[j] = tryObjectEncoding(c->argv[j]); 267 if (setTypeAdd(set,c->argv[j])) added++; 268 } 269 if (added) { 270 signalModifiedKey(c->db,c->argv[1]); 271 notifyKeyspaceEvent(REDIS_NOTIFY_SET,"sadd",c->argv[1],c->db->id); 272 } 273 server.dirty += added; 274 addReplyLongLong(c,added); 275 } 276 277 void sremCommand(redisClient *c) { 278 robj *set; 279 int j, deleted = 0, keyremoved = 0; 280 281 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL || 282 checkType(c,set,REDIS_SET)) return; 283 284 for (j = 2; j < c->argc; j++) { 285 if (setTypeRemove(set,c->argv[j])) { 286 deleted++; 287 if (setTypeSize(set) == 0) { 288 dbDelete(c->db,c->argv[1]); 289 keyremoved = 1; 290 break; 291 } 292 } 293 } 294 if (deleted) { 295 signalModifiedKey(c->db,c->argv[1]); 296 notifyKeyspaceEvent(REDIS_NOTIFY_SET,"srem",c->argv[1],c->db->id); 297 if (keyremoved) 298 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",c->argv[1], 299 c->db->id); 300 server.dirty += deleted; 301 } 302 addReplyLongLong(c,deleted); 303 } 304 305 void smoveCommand(redisClient *c) { 306 robj *srcset, *dstset, *ele; 307 srcset = lookupKeyWrite(c->db,c->argv[1]); 308 dstset = lookupKeyWrite(c->db,c->argv[2]); 309 ele = c->argv[3] = tryObjectEncoding(c->argv[3]); 310 311 /* If the source key does not exist return 0 */ 312 if (srcset == NULL) { 313 addReply(c,shared.czero); 314 return; 315 } 316 317 /* If the source key has the wrong type, or the destination key 318 * is set and has the wrong type, return with an error. */ 319 if (checkType(c,srcset,REDIS_SET) || 320 (dstset && checkType(c,dstset,REDIS_SET))) return; 321 322 /* If srcset and dstset are equal, SMOVE is a no-op */ 323 if (srcset == dstset) { 324 addReply(c,setTypeIsMember(srcset,ele) ? shared.cone : shared.czero); 325 return; 326 } 327 328 /* If the element cannot be removed from the src set, return 0. */ 329 if (!setTypeRemove(srcset,ele)) { 330 addReply(c,shared.czero); 331 return; 332 } 333 notifyKeyspaceEvent(REDIS_NOTIFY_SET,"srem",c->argv[1],c->db->id); 334 335 /* Remove the src set from the database when empty */ 336 if (setTypeSize(srcset) == 0) { 337 dbDelete(c->db,c->argv[1]); 338 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",c->argv[1],c->db->id); 339 } 340 signalModifiedKey(c->db,c->argv[1]); 341 signalModifiedKey(c->db,c->argv[2]); 342 server.dirty++; 343 344 /* Create the destination set when it doesn't exist */ 345 if (!dstset) { 346 dstset = setTypeCreate(ele); 347 dbAdd(c->db,c->argv[2],dstset); 348 } 349 350 /* An extra key has changed when ele was successfully added to dstset */ 351 if (setTypeAdd(dstset,ele)) { 352 server.dirty++; 353 notifyKeyspaceEvent(REDIS_NOTIFY_SET,"sadd",c->argv[2],c->db->id); 354 } 355 addReply(c,shared.cone); 356 } 357 358 void sismemberCommand(redisClient *c) { 359 robj *set; 360 361 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL || 362 checkType(c,set,REDIS_SET)) return; 363 364 c->argv[2] = tryObjectEncoding(c->argv[2]); 365 if (setTypeIsMember(set,c->argv[2])) 366 addReply(c,shared.cone); 367 else 368 addReply(c,shared.czero); 369 } 370 371 void scardCommand(redisClient *c) { 372 robj *o; 373 374 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL || 375 checkType(c,o,REDIS_SET)) return; 376 377 addReplyLongLong(c,setTypeSize(o)); 378 } 379 380 void spopCommand(redisClient *c) { 381 robj *set, *ele, *aux; 382 int64_t llele; 383 int encoding; 384 385 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL || 386 checkType(c,set,REDIS_SET)) return; 387 388 encoding = setTypeRandomElement(set,&ele,&llele); 389 if (encoding == REDIS_ENCODING_INTSET) { 390 ele = createStringObjectFromLongLong(llele); 391 set->ptr = intsetRemove(set->ptr,llele,NULL); 392 } else { 393 incrRefCount(ele); 394 setTypeRemove(set,ele); 395 } 396 notifyKeyspaceEvent(REDIS_NOTIFY_SET,"spop",c->argv[1],c->db->id); 397 398 /* Replicate/AOF this command as an SREM operation */ 399 aux = createStringObject("SREM",4); 400 rewriteClientCommandVector(c,3,aux,c->argv[1],ele); 401 decrRefCount(ele); 402 decrRefCount(aux); 403 404 addReplyBulk(c,ele); 405 if (setTypeSize(set) == 0) { 406 dbDelete(c->db,c->argv[1]); 407 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",c->argv[1],c->db->id); 408 } 409 signalModifiedKey(c->db,c->argv[1]); 410 server.dirty++; 411 } 412 413 /* handle the "SRANDMEMBER key <count>" variant. The normal version of the 414 * command is handled by the srandmemberCommand() function itself. */ 415 416 /* How many times bigger should be the set compared to the requested size 417 * for us to don't use the "remove elements" strategy? Read later in the 418 * implementation for more info. */ 419 #define SRANDMEMBER_SUB_STRATEGY_MUL 3 420 421 void srandmemberWithCountCommand(redisClient *c) { 422 long l; 423 unsigned long count, size; 424 int uniq = 1; 425 robj *set, *ele; 426 int64_t llele; 427 int encoding; 428 429 dict *d; 430 431 if (getLongFromObjectOrReply(c,c->argv[2],&l,NULL) != REDIS_OK) return; 432 if (l >= 0) { 433 count = (unsigned) l; 434 } else { 435 /* A negative count means: return the same elements multiple times 436 * (i.e. don't remove the extracted element after every extraction). */ 437 count = -l; 438 uniq = 0; 439 } 440 441 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) 442 == NULL || checkType(c,set,REDIS_SET)) return; 443 size = setTypeSize(set); 444 445 /* If count is zero, serve it ASAP to avoid special cases later. */ 446 if (count == 0) { 447 addReply(c,shared.emptymultibulk); 448 return; 449 } 450 451 /* CASE 1: The count was negative, so the extraction method is just: 452 * "return N random elements" sampling the whole set every time. 453 * This case is trivial and can be served without auxiliary data 454 * structures. */ 455 if (!uniq) { 456 addReplyMultiBulkLen(c,count); 457 while(count--) { 458 encoding = setTypeRandomElement(set,&ele,&llele); 459 if (encoding == REDIS_ENCODING_INTSET) { 460 addReplyBulkLongLong(c,llele); 461 } else { 462 addReplyBulk(c,ele); 463 } 464 } 465 return; 466 } 467 468 /* CASE 2: 469 * The number of requested elements is greater than the number of 470 * elements inside the set: simply return the whole set. */ 471 if (count >= size) { 472 sunionDiffGenericCommand(c,c->argv+1,1,NULL,REDIS_OP_UNION); 473 return; 474 } 475 476 /* For CASE 3 and CASE 4 we need an auxiliary dictionary. */ 477 d = dictCreate(&setDictType,NULL); 478 479 /* CASE 3: 480 * The number of elements inside the set is not greater than 481 * SRANDMEMBER_SUB_STRATEGY_MUL times the number of requested elements. 482 * In this case we create a set from scratch with all the elements, and 483 * subtract random elements to reach the requested number of elements. 484 * 485 * This is done because if the number of requsted elements is just 486 * a bit less than the number of elements in the set, the natural approach 487 * used into CASE 3 is highly inefficient. */ 488 if (count*SRAN