Writing in the front

  • See JAVA- Part 11 -Redis for other content

NoSQL

  • Not-only SQL: refers to non-relational databases as a supplement to relational databases
  • Solve the problem of massive users and high concurrency

The solution

  • Basic information about Mysql
  • Merchandise Additional information MongoDB
  • Product picture information distributed file system
  • Search for the keywords ES, Lucene, solr
  • Hotspot information (high frequency and band nature) Redis, memcache, and TAIR

Redis

  • MAC installationbrew install redis
  • Visualization toolAnother Redis Desktop Manager
  • Provide basic data to reduce the degree of coupling between business and data
  • Remote Dictionary Server, key-value database
  • Single thread mechanism, there is no necessary correlation between data
  • Data types string, list, hash, set, sorted_set (ordered set)
  • Persistence, data disaster recovery
  • Value maximum range +- long maximum
  • keynamed
Table name: Primary key: Primary key Value: Attribute name, for example, user: ID :3123: FANS // JSON format Table name: Primary key: primary key value -> {Attribute 1: value, Attribute 2: value, Attribute 3: value... }Copy the code

application

  • Hotspot Data Query
  • Task queue, second kill, buying, buying tickets
  • Instant information and time-sensitive information control
  • Distributed data

Start the

  • The clientredis-cliexitquitClosing the ServerSHUTDOWN
  • The service sideredis-server

Basic operation

  • Clear the screenclear
  • Help informationhelp
  • Get the current timetime

The data type

  • Key is always String

string

  • Storing single data
  • Integrity, one-time storage one-time read, emphasis on reading
  • addset key value
  • To obtainget key
  • deletedel key ...
  • Add multiple datamset k1 v1 k2 v2 ...
  • Get multiple datamget k1 k2
  • The number of charactersstrlen key
  • additionalappend key valueIf no, create a new one

Extend the operation

  • String is numeric and can be manipulated as numeric data
Incr num // +1 decr num // -1 incrby num increment // +increment Incrbyfloat NUM increment // Add decimal decrby num increment // -incrementCopy the code
  • Set the life cycle of the specified data. You can add or subtract data within the life cycle
Setex key seconds value setex TEL 100 10 psetex key milliseconds ValueCopy the code

hash

  • Map to map, shopping cart, order information, etc
  • The key corresponds to a heap of data, and the space of the heap is a hash, and the bottom is a hash table (red-black tree + array).
  • add
hset key field value
hset user name zhangsan
Copy the code
  • Add multiple
hmset key f1 v1 f2 v2...
hmset user name zhangsan weight 180
Copy the code
  • To obtain
hget key field
hget user name
Copy the code
  • Access to multiple
hmget k f1 f2..
hmget user name age weight
Copy the code
  • Access to all
hgetall key
hgetall user
Copy the code
  • delete
hdel key
hdel user name
Copy the code
  • Get the number of fields
hlen key
Copy the code
  • Whether the specified field exists
hexists key field
Copy the code

Extend the operation

  • Gets all fields for the specified key
hkeys key
hkeys user
Copy the code
  • Gets all values of the specified key
hvals key
hvals user
Copy the code
  • Increment, no deincrby
Hincrby Key Field increment Hincrby User age 1 // HincrByFloat Key field increment HincrByFloat User age 19.2Copy the code
  • Check whether the field has a value. If the field has a value, it is not modified; if the field does not have a value, it is added
hsetnx key field value
Copy the code

list

  • Time specific; New concerns, current events, etc
  • Stores multiple data and distinguishes the sequence of data entering the storage space
  • At the bottom is a bidirectional list
  • Add data
// The last data index on the right is 1 lpush key value1 value2... // From right to left, the right is the opening, push left value1 leftmost rpush key Value1 value2...Copy the code
  • To get the data
Lrange key start stop lrange key 0 -1 lindex key index lindex key -1 // List length llen keyCopy the code
  • Get and remove data
// Fetch the data lPOP key from the far left // Fetch the data rPOP key from the far rightCopy the code

Extend the operation

  • Retrieve and remove data at a specified time, as long as the data is available within a specified time
blpop key seconds
brpop key seconds
Copy the code
  • Removes the specified element, and removes the intermediate element
Lrem key count value // Remove two wangwu lrem name 2 wangwuCopy the code

Set

  • Random recommendation hot spot information, recommendation type information retrieval; The same type of array to duplicate, record access IP; Black and white list
  • The bottom layer is a Hashmap, which only uses the location of the key to store values
  • Insertion order is not guaranteed
  • Easy to find
  • Add data
sadd key member1 member2...
Copy the code
  • Get all data
smembers key
Copy the code
  • Delete the data
srem key member1 member2...
Copy the code
  • Get the number of sets
scard key
Copy the code
  • Determines whether the collection contains the specified data
sismember key member
Copy the code

Extend the operation

  • Retrieves a specified amount of data randomly from the collection, unchanged from the original collection
srandmember key [count]
Copy the code
  • Randomly retrieves some data from the collection and removes the collection
spop key [count]
Copy the code
  • Operation of two sets
Sinter Key1 [key2] // Stored in destination new set. Sintersrote destination key1 [key2] // SUnion key1 [key2] sunionStore Sdiff key1 [key2] sdiffStore Destination key1 [key2]Copy the code
  • Moves the specified data from the original collection to the target collection
// smove source destination memberCopy the code

sorted_set

  • A stock rally; One year salary; List data; Record the weight of the task, marked by numbers, each category should be the same length, such as employee 102 and manager 101, not simply 1 or 2, add 0 flexibly
  • Sort by their own characteristics
  • No duplicates are allowed and will be sorted in character order
  • Adds sortable fields to the storage structure of a set
  • Score is a double if it is not a number
ERR value is not a valid float
Copy the code
  • Add data
Zadd key score1 member1 score2 member2... Zadd scores 94 ZS zs 100 ls //Copy the code
  • Get all data
Zrange key start stop [withscores] zrange key 0-1 // descending zrevrange key start stopCopy the code
  • Delete the data
zrem key member ...
Copy the code
  • Get data by conditions
Zrangebyscore key min Max [withscores] [limit] Zrevrangebyscore key Max main [withscores] [limit]Copy the code
  • Conditional deletion of data
Zremrangebyrank scores 0 2 // Zremrangebyscore key min Max // delete zremrangebyScore scores between 50 and 90Copy the code
  • Get aggregate data
zcard key
zcount key min max
Copy the code
  • Set operations
Zinterstore ss 3 s1 s2 s3 zinterstore ss 3 s1 s2 s3 zinterstore ss 3 s1 s2 s3 Calculate the minimum value for the same data zinterstore SSS 3 S1 S2 S3 aggregate min //weights Zinterstore SSS 3 S1 S2 S3 weights 2 3 4 // Union zunionStore destination numkeys key1 key2Copy the code

Extend the operation

  • Gets the index corresponding to the data
// zrevrank key member // zrevrank key memberCopy the code
  • Obtaining and modifying the SCARE value
zscore key member
zincrby key increment member
Copy the code

case

  • When the number of times of detection is needed, for example, there are only ten chances, the maximum value -10 is used and incR is used to increase. If the maximum value is exceeded, the fault is reported
  • Wechat session sequence management, using the non-repetitive characteristics of set to store the top content, two lists (stack form, one end operation) respectively store ordinary and specified message queues for queuing

  • tips1 2 3 string
  • tips4 5 hash
  • tips5 6 list
  • tips8 9 10 11 12 set
  • tips 13 14 15 sorted_set

Advanced data types

Bitmaps

  • Operating binary
  • Gets the bit value at the offset of the specified keygetbit key offset
  • Set up thesetbit key offset valueValue can only be 1 or 0
  • Through the numberbitcount key [start end]
  • Contract, union, non, xor
//and or not xor bitop op destkey key1 [key2...Copy the code

HyperLogLog

  • The number of statistics that are not repeated, the number of cardinals (after deduplication)
  • The stored data is not real, only the quantity is recorded, the core is the cardinality estimation algorithm, the final value has an error (0.81%)
  • Each memory that uses the 12K upper limit will gradually increase as the base increases until it reaches 12K
  • Add datapfadd key element [element ...]
  • statisticspfcount key [key ...]
  • Consolidated statisticspfmerge destkey sourcekey [sourcekey ...], the default is 12K

GEO

  • When you’re dealing with geographical locations, you’re only dealing with horizontal locations
  • Add coordinate pointsGeoadd Key Longitude Latitude Member [....]
  • Get coordinate pointgeopos key member [member ...]
  • Compute the coordinate point distanceGeodist key member1 member2 [unit]
  • Find the data in the range according to the coordinatesgeoradius key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count [ANY]] [ASC|DESC] [STORE key] [STOREDIST key]Draw a circle with this point as the center and radius as the radius
  • Find the data in the range of the pointsgeoradiusbymember key member radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count [ANY]] [ASC|DESC] [STORE key] [STOREDIST key]Draw a circle with this member as the center and radius as the radius
  • Gets the hash value of the coordinates of the specified pointgeohash key member [member ...]

General command

key

  • It’s just a string
  • Deleting a specified key
del key
Copy the code
  • Gets the type of the key
type key
Copy the code
  • Gets whether the key exists
exists key
Copy the code

Extend the operation

  • Set the validity period for the key
Expire key seconds pexpire key milliseconds // Timestamp expireat key timestamp pexpireat key milliseconds-timestampCopy the code
  • Gets the validity time of the key
// Returns -1 permanent, -2 expired, no TTL key exists // ms PTTL keyCopy the code
  • The toggle key is converted from valid to permanent
persist key
Copy the code
  • Query key
Keys pattern // Query all keys *? Match a character [] Matches a specified characterCopy the code

Other operating

  • Change the name to newkey, which overwrites the original content
Rename key newKey // If there is a rename key newkey, do not change renamenx key newkeyCopy the code
  • Sort the contents of keys
// Can only operate on list or set, Don't change the order of the original collection sort key sort key [BY the pattern] [LIMIT offset count] [GET pattern [GET pattern...]] [ASC | DESC] [ALPHA] [STORE  destination]Copy the code
  • help
help @generic
Copy the code

General database instruction

  • Switching databases
// Select index from 0 to 15Copy the code
  • Other operating
Quit // Test the server. If the server is connected, PONG ping is returned. // The client outputs log echo messageCopy the code
  • Mobile database
Move key db // Move name to 0 move name 0Copy the code
  • Data to remove
Flushdb: flushhall: flushhall: flushhall: flushhallCopy the code

Publish and subscribe

// Subscribe name // subscribe value pulish name valueCopy the code