[crazy God says Redis] 3 five data types

Five data types

Official website document

Redis is an open source (BSD licensed) in memory data structure storage system, which can be used as database, cache and message middleware MQ. It supports many types of data structures, such as strings, hashes, lists, sets, sorted sets and range queries, bitmaps, hyperlogs and geospatial index radius queries. Redis has built-in replication, Lua scripting, LRU events, transactions and different levels of disk persistence, and provides high availability through redis Sentinel and Cluster.

String

Most java programmers use strings

  1. Common commands
# group 1: append strlen
set name qd					# set [key] [value]
append name 123				# append [key] [append_value] append string
strlen name					# strlen [key] determines the string length of the key
append name2 zhangsan		# append [key] [value] if there is no current key, it is equivalent to set name2 zhangsan

# group 2: self increase and self decrease according to step size self increase and self decrease according to step size incr decr incrby decrby
set views 0					# set [key] [value] set the browsing volume to 0
incr views					# incr [key] add one to the number of views = = "1
decr views					# decr [key] reduce the number of views by one = = "0", then you can't reduce it by yourself, and an error will be reported
incrby views 10				# incrby [key] [step] self increasing step size: 10
decrby views 10				# decrby [key] [step] self decreasing step size: 10

# group 3: string range getrange [startIndex] [endIndex] generally, both are greater than 0, and endindex > StartIndex
getrange name 0 3			# getrange [key] [startIndex] [endIndex] take the string according to the range: the value of index starts from 0 and will be taken from star to end. If it is a normal value, the length of the obtained string is end star + 1
getrange name 0 -1			#getrange [key] [startIndex] -1 get from starIndex to the last


#group 4: replace the String setrange starting at the specified position (equivalent to replace in String)
setrange name 2 sub 			# setrange [key] [startIndex] [subString] subString is used to replace the string with the same length as subString after starting from statIndex; The length returned is the length after substitution
get name # The result is lisubolu
# Example 2
setrange name 7 sub2
get name						# The result is lisubolsub2



# group 5: setex (same as expire) setnx
#setex (set with expire) sets the expiration time
#Set if setnex (set if not exit) does not exist (often used in distributed locks)
setex name 30 "hello"			# setex [key] [expireTime] [value] set the key survival time to expireTime, and set the value to value (if the key does not exist, it will be created)
setnx key1	"qd"			# setnx [key] [value] set the value to value when the key does not exist; Creation will fail if there is: (1 will be returned if the setting is successful, and 0 will be returned if the setting is failed)


# group 6: batch setting Mset mget msetex msetnx
mset k1 v1 k2 v2 k3 v3			# Batch setting (K1, V1), (K2, V2), (K3, V3) Mset [key1] [value1] [key2] [Value2] [Key3] [value3] The order of storage is set by the hash algorithm
mget k1 k2 						# Batch get K1 K2 mget [key1] [key2] ...
msetnx k1 v1 k4 v4				# msetnx is an atomic operation that either succeeds or fails together
# Advanced usage object
set user:1 {name:zhangsan,age:3}		# Set a user:1 object value to json string to save an object
# How to get individual attribute values????
mset user:1:name name1 user:1:age 2		# [object ID]:
mget user:1:name user:1:age				# Batch data acquisition


# Group 7: get before set
getset db redis							# Return (nil) gets the value before db. If it is not set before, return (nil). The value obtained later is the currently set value (redis)
get db									# redis returned this time
  1. String similar scenario: value can be either a string or a number
  2. Application: the counter counts the number of multi units and the number of fans. The object is cached and stored
  3. Extension: CAS: compare and exchange
    JRedis: the client of java operation. These commands will become methods
    The structure is the same

List

  1. Basic data types
  2. In redis, you can play the list into stack, queue and blocking queue
  3. Most list commands start with l: except lpush and rpush, all other l's represent list
  4. Basic command
# group 1 insert lpush rpush
lpush list one					# Insert one or more values into the header of the list (insert from the left end: header)
lpush list two
lpush list three
lrange list 0 -1				# Get the value in the list: the output is three two one (no rrange)
lrange list 0 1					# Obtain specific value through interval
rpush list four					# Insert one or more values at the end of the list (insert from the right end: tail insert)
lrange list 0 -1				# The result is: three two one four

# group 2 remove lpop rpop
lpop list						# Remove an element to the left and return the element content: three
rpop list						# Remove an element to the right and return the element content: four


# group 3 values by index
lindex list 0					# The index starts from 0, - 1 means that there is no rindex for the last element

# group 4 get list length len
llen list						# Return list length


# group 5 remove specified value count > 0 remove count (from front to back) count=0 remove all count < 0 remove count (from back to front)
lrem list 0 one					# Remove all one s in the list
lrem list 1 one					# Remove one from the list

# group 6 truncation operation
lpush list2 one two three four	# New list: list2[one,two,three,four]
ltrim list2 1 2					# Truncation: when truncating, the two parameters are index (starting from 0), which will change the list


# Group 7 rpolpush: remove the last element of the list and put it into a new list. The old list can be the same as the new list
lpush list3 one two three four	# New list: list3[one,two,three,four]
rpoplpush list3 list4			# "one"
lrange list3 0 -1				# The result is: four three two
lrange list4 0 -1				# The result is: one


# group 8 lset modifies the value of the existing index for an existing list: equivalent to the update operation
lpush list5 one two three four	# New list: list5[one,two,three,four]
exists list5					# Judge whether it exists, and return 0 (not exists) or 1 (exists)
lset list5 0 item				# Set the 0th element in list5 to "item", and pay attention to the position of index	


# group 9 linsert inserts a specific value before or after an element in the list
lpush list6 one one three four	# New list: list6[one,one,three,four]
linsert list6 before one qd		# Insert qd in front of one: list6[qd,one,one,three,four]
linsert list6 after one qd2		# Insert qd2 after one: list6[qd,one,qd2,one,three,four]
# If there is repetition, the first one will be the standard

Summary:

  1. In fact, it is a linked list. Before node, after, left and right can insert values
  2. If the key does not exist, create a new linked list
  3. If the key has new content
  4. If all values are removed, that is, the empty linked list, it also means that it does not exist
  5. When inserting or changing values on both sides, the efficiency is the highest; When operating intermediate elements, the relative efficiency will be lower
  1. Applications: message queuing, message queuing (lpush, rpop), stack (lpush, lpop)

Set set

  1. Unordered cannot duplicate values
  2. Basic command
sadd set0 "one" "two" "three" "four"		# Add element to set0 collection
smembers set0								# View the value of set0
sismember set0 one							# Determine whether the one element exists in set0
scard set0 									#View the number of elements in set0
srem set0 one								# Removes the specified element from set0
srandmember set0 							# Randomly take elements from set0. The default is to take one
srandmember	set0 2							# Randomly take two elements from set0
spop set0									# Randomly remove an element in set0; The return value is the removed value
spop set0 2									# Randomly remove two elements in set0; The return value is the removed value


sadd set1 "hello" "123" "qd"				# Create set1
sadd set2 "hello2" "1232" "qd2"				# Create set2
smove set1 set2 "hello"						# Move "hello" in set1 to set2



# Difference set sdiff intersection sunion union sinter
sadd key1 a b c								# Create key1
sadd key2 b c d								# Create key2
sdiff key1 key2								# Find the difference set between key1 and key2
sinter key1 key2							# Find the intersection of key1 and key2
sunion key1 key2							# Find the union of key1 and key2
  1. Application: microblog, user A puts all his concerns in one set and his fans in one set: he can seek common concerns and hobbies of other users, second degree friends (six degree segmentation theory), and recommend friends (six degree segmentation theory)

Hash (hash)

  1. Think of a map set: key value (map): the value here is the type of map
  2. Basic command
# group 1
hset myhash field1 lxl 					# Create a hash: myhash
hmset myhash field1 lxl field2 qd		# You can assign more than one value at a time (you can also use hset operation)
hget myhash field1						# Gets the value of a field
hmget myhash field1 field2				# Get the value of multiple field s
hgetall myhash 							# Get all the data


# group 2
hdel myhash field1						# Deleting the field specified by hash will also delete the corresponding value
hlen myhash								# Check the number of key value pairs in the hash
hexists myhash field1					# Judge whether there is a corresponding field in the hash and return 1 or 0



# group 3 gets only key and only value
hkeys myhash							# Get all field s
hvals myhash							# Get all value s


# group 4 hincrby hsetnx
hset myhash field3 5					# Set a field3 value of 5 for myhash
hincrby myhash field3 2					# Make field3 in myhash increase by 2 (step size cannot be omitted)
hincrby myhash field3 -2				# Make field3 in myhash subtract 2 by itself (step size cannot be omitted, and there is no hdecrby method)
hsetnx myhash field4 hello				# If it does not exist, it will be created. If it exists, it will fail
  1. Application:
    • hash stores some changed data: name, age... Especially frequently changing information such as user information
    • hash is more suitable for object storage, and String is more suitable for String storage
hset user:1 name qd age 20				# Set the name and age of the user with id 1
hget user:1 name						# Get the name of user: 1
hmset user:1 name age					# Get the name and age of user:1

Zset (ordered set)

  1. A value is added to set: set k1 v1 zset k1 score1 v1
  2. The underlying data structure of an ordered set is a jump linked list (a common interview site)
  3. Basic command
# The score can be repeated, and the element value is not repeated
zadd myset 1 one						# Create zset and add a value
zadd myset 2 two 3 three 				# Add multiple values at once


# group 2 sorting
zadd salary 2500 xiaohong
zadd salary 5000 zhangsan 
zadd salary 500 qd
zrangebyscore salary -inf +inf			# Display all users from small to large: [- inf,+inf] (the former < the latter, cannot be equal). The returned value is only the element value without score 
# zrevrangebyscore can be used to arrange from large to small. At this time, the value passed by the former should be greater than the latter, and it can not be equal
zrangebyscore salary 500 5500
zrangebyscore salary -inf +inf withscores	# With score

# remove
zrem salary xiaohong 					# Remove an element xiaohong and remove score at the same time


# Gets the number of members in the specified interval
zcard salary							# Gets the number of elements in an ordered collection
zcount salary 500 5500					# Count the number of people whose salary is [5005500]
  1. Application:
    • set sort storage class grade table salary table sort ranking list
    • Judge with weight

Keywords: Linux Redis

Added by dibyajyotig on Thu, 17 Feb 2022 10:05:52 +0200