1, the introduction of
All data structures in Redis use a unique string key to obtain the corresponding value data. Redis has five basic data structures, which are:
- String (string)
- List (list)
- Hash (dictionary)
- Set
- Zset (Ordered set)
List, set, Hash, and zset are container data structures that share the following two general rules:
- Create if not exists: Creates a container if it does not exist
- Drop if no elements: If there are no elements in the container, the container is immediately dropped to free the memory
This article is about the set of Redis 5 basic data structures.
2, Set (set) related introduction
2.1 Internal structure of a set
Redis’s set is the Java equivalent of HashSet, with unordered and unique key-value pairs. It internally implements a special dictionary where all values are null. After the last element in the collection is removed, the data structure is automatically deleted and the memory is reclaimed. \
2.2 Usage scenarios of Set (Set)
Set (set) can be used to store the ID of a winning user in an activity because of its special de-duplication function. This ensures that a user does not win twice.
3, set(set) related instructions
Sadd -> Add set member, key set name, member set element, element cannot be repeated
Sadd key member [member…]
127.0.0.1:6379> sadd Name Zhangsan (integer) 1 127.0.0.1:6379> sadd name Zhangsan Repeat 0 (integer) 0 127.0.0.1:6379> sadd Name Lisi Wangwu Liumazi # Support adding multiple elements at once (integer) 3Copy the code
Smembers -> View all the elements in the collection, note that they are unordered
smembers key
1) lisi" 2) wangwu" 3) liumazi" 4) zhangsanCopy the code
Sismember -> Queries whether the collection contains an element
sismember key member
127.0.0.1:6379> sismember name lisi # contains return 1 (integer) 1 127.0.0.1:6379> sismember name tianqi # does not contain return 0 (integer) 0Copy the code
Scard -> Gets the length of the collection
scard key
127.0.0.1:6379> scard name
(integer) 4
Copy the code
Spop -> Pop elements, count refers to the number of pop elements
spop key [count]
1) "lisi" 2) "zhangsan" 3) "liumazi"Copy the code