Redis Database Notes

Source: Internet
Author: User
Tags key string lua memcached redis version set set sha1 redis server value store

What is 1.redis?
Redis (REmote DIctionary server) is a nosql, non-relational database developed using the C language; Redis is a language tool for manipulating data structures, which is a memory database or data structure server, which stores it directly in memory. However, it provides persistent support; it is a key-value pair database, which holds key-value pairs of data, which is equivalent to saving a variable and a variable, storing the data in a dictionary structure, and allowing other applications to read and write the contents of the dictionary through the TCP protocol, which is a substitute for the memcached cache server.
What can 2.redis be used for?
databases, queues, and cache systems, Sina Weibo is heavily used by Redis. Key-value Store is a popular topic nowadays, especially in the construction of large-scale Internet applications such as search engine, IM, peer-to-peer, game server, SNS and providing cloud computing services, ensuring the high performance, high reliability, high scalability, high availability and low cost of the system in the massive data environment.
Applicable occasions:
A. Operations that take the latest N data
B. Leaderboard application, TOP N operation
C. Applications that require precise setting of expiration time
D. Counter application INCR DECR
E.uniq operation, get all data row weight values for a certain period of time
F. Real-time system, anti-spam system set Set
G.pub/sub Building a real-time messaging system
H. Building a queue system
I. Caching
The pros and cons of 3.redis and memcashed
In performance, Redis is a single-threaded model, and memcached supports multithreading, so the latter performance is higher on multicore servers. However, as mentioned earlier, the performance of Redis is excellent enough that in most cases its performance will not be a bottleneck. So in the use of more should be concerned about the difference between the two, if you need to use advanced data types or persistent functions, Redis will be a good substitute for memcached.
As a caching system, Redis can also limit the maximum amount of memory space used by data, and can automatically retire unwanted keys after the data has reached space limits.
In addition to this, the Redis list type key can be used to implement queues and support blocking reads, which makes it easy to implement a high-performance priority queue. At the same time, Redis supports the "Publish/Subscribe" message pattern on a higher level, which can be built on systems such as chat rooms.
4.redis installation and start-up
Redis officially only provides the Redis version of the POSIX system version, http://download.redis.io/redis-stable.tar.gz can download the latest stable version. Redis has no other external dependencies. Installation in window requires the use of the Cygwin environment.
Server-side startup:
>redis-server: Direct boot, default port 6379
>redis-server--port 6380: Start on the specified port
>redis-server redis.conf: Use configuration file initialization at startup, redis.conf in the installation file.
>REDIS-CLI SHUTDOWN: Secure termination of Redis server
Client Startup:
>redis-cli-h 127.0.0.1-p 6379: Client starts and connects to server
5.redis command Execution return value (5 kinds)
A. Status reply reply command execution status, such as set and ping reply
B. Error reply command execution error, reply form is: (Error) ...
C. Integer reply to Redis although there is no integer type, a set of commands for character integer operations is provided, and replies to these commands return integers, such as incr,dbsize, in the form of: (integer) n
E. String reply When you request a key value for a string type key or an element in a different type key, you get a string reply, such as GET, which responds in the form: "..."
F. Multiple-line string replies, such as the keys command, will add a string line number when replying.
Multi-database of 6.redis
As MySQL can build multiple databases, the number of databases that Redis can establish is configured by the databases in redis.conf, which defaults to 16 and the database number from 0-15, and does not support custom database names. Client REDIS-CLI will automatically select database No. 0 after establishing a connection with Redis, but you can replace the database with the Select N command at any time.
7. Common commands
Keys Glob_pattern: Queries all key glob_pattern in the current database:? , *,[],\x
EXISTS key: Determine if a key exists, there is return 1, otherwise 0
DEL key [key ...]: delete one or more keys
Type key: Returns the data type of the key key
EXPIRE Key Time: Set the expiration of a key
PERSIST key: Remove the expiration time of the key
Move key N: Moves the key key of the current database to the N number database
Select N: Choose the N database as the current database, 0-15
Randomkey: Randomly returns a key for the current database
RENAME key Newkey: Rename a key
Server-related commands
PING: Test If the connection is alive
ECHO "..." : Print a line of content at the command line
Quit: Quit connection
Dbsize: Returns the number of keys in the current database
Info: Returns information and statistics for the server
MONITOR: Live dump of received requests
CONFIG get dir: Get server configuration information
FLUSHDB: Delete all keys in the current database
Flushall: Remove key from all databases

5 Big Data (key) types for 8.redis
String (string), hash (hash), List, collection (set), ordered set (Zset), each key is one of these 5 data types, depending on how the keys are created to decide which type to belong to. Redis does not support data type nesting. List, collection (set), ordered collection keys can only hold data of type string.
A. String type: A String type key allows the maximum capacity of stored data to be 512MB. The string type is the basis for the other 4 data types, and the differences between the other data types and string types are, in some ways, just the form of the organization string. For example, a list type organizes a string as a list, and the collection type organizes the string in the form of a collection.
Command:
Operations on strings
SET Key value: Creates a string variable and assigns a value
Get key: Returns an empty result when the key does not exist.
Setnx key value: If key key does not exist, the key is set, the presence returns 0, no setting
Setex Key Time value: Sets the key and specifies that the key is valid for the period, which can be viewed using the TTL
SETRANGE Key start Jointvalue: The key from the 8th character, replaced by the Jointvalue
APPEND Key value: Adds a value to the tail of a string
STRLEN key: Gets the string length
MSET key value [key value ...]: Setting values for multiple keys at the same time
MGET key [Key ...] : Gets the value of multiple keys at the same time
Msetnx key value [key value ...]: A key will not be set when it fails
Getset Key value: Sets and returns the value of key
GETRANGE Key Start end: Returns the child channeling from start to end in the key string
Operation on a real string
INCR key: Incrementing the number, incrementing the non-digit will return an error
Incrby key increment: increase by specified number
DECR key: decrements the number
Decrby key Decrement: Descending by specified number
Incrbyfloat key increment: add to floating point
4 large commands for bit manipulation of strings (bits operation in memory sense)
Getbit key offset: Gets the binary value of the total offset bit in the string
Setbit Key Offset value: Sets the binary value of the total offset bit in the string
Bitcount key [M] [n]: The number of 1 in a uniform string from byte m to nth byte of binary number
Bitop operation Destkey Key [key ...] : The Bitop command can perform bitwise operations on multiple string type keys and store the result in the key specified by the Destkey parameter. The operations supported by the Bitop command have and, or, XOR, and not
B. Hash type (dictionary type in Python)
The key value of a hash type (hash) is a dictionary structure that stores mappings for field and field values, but the field value can only be a string, no other data type, and a hash type key can contain
A maximum of 232-1 fields.
Assigning and taking values:
Hset key field value: Sets the key for the specified field
Hget key field: Gets the value of the specified field for the key
Hmset key field value [Field value ...]: Sets the value of the key for multiple fields
Hmget key field [field ...] : Gets the value of the key for multiple fields
Hgetall key: Gets all field names and domain values for the key
Hkeys key: Gets the key for all field names
Hvals key: Gets the value of all fields of the key
Hlen key: Gets the number of the key fields

Hexists key field: Determine if a field exists in the key
Hsetnx key field Value: Assignment When the field does not exist
Hincrby key field increment: Add increment to numeric strings
Hdel key field [field ...] : Delete a field

C. List type (double-ended linked lists)
Press and eject elements to the end of the list
Lpush key value [value ...] : Adding elements to the left side of the list
Rpush key value [value ...] : Adding elements to the right side of the list
Lpop key: Popup element from the left side of the list
Rpop key: Popup element from the right side of the list
Llen key: Gets the number of elements in the list
Lrange key start stop: Get list fragment,-1, last element,-2 penultimate element
Lrem Key count Value: When count> removes the list from the left of the first count value of the element, the return value is the number of elements actually deleted, and when count<0 is removed from the right, count=0, all elements with value values are deleted.
LINDEX Key index: Gets the element value for the specified index, supporting negative indexing
LSET Key Index value: Sets the element values for the specified index
LTRIM key start end: Keep only the list specified fragment
Linsert Key before| After pivot value: finds an element with a value of pivot from left to right, inserts value into the element's before or after
Rpoplpush Source destination: POPs an element from the right side of a list to the left of another list

D. Collections (storing different strings)
Each element in the collection is different and has no order. A collection type (set) key can store a string of up to 2 32-1 (this number is already familiar to everyone). The common operation of a collection type is to add or remove elements to the collection, determine whether an element exists, and so on, because the collection type is implemented using a hash table with empty values inside the Redis, so the time complexity of these operations is 0 (1). The most convenient is that multiple collection type keys can also be set, intersect, and differential.
Sadd key member [member ...] : adding elements
Srem Key member [member ...] : Deleting an element
Smembers key: Gets all the elements in the collection
Sismember Key member: Determines whether the element is in the collection
Sdiff key [Key ...] : Difference Set
SINTER key [Key ...] : Intersection
Sunion key [Key ...] : and set
SCard key: Gets the number of elements in the collection
Sdiffstore destination key [key ...]: Perform a set operation and store the result
Sinterstore destination key [key ...]
Sunionstore destination key [key ...]
Srandmember key [count]: Randomly gets the elements in the collection (default 1) When Count is a positive number, srandmember randomly obtains count non-repeating elements from the collection. If the value of count is greater than the number of elements in the collection, Srandmember returns all elements in the collection, and when count is negative, srandmember randomly obtains |count| elements from the collection, which may be the same.
SPOP key: POPs an element from the collection
Smove Source Destination Value: Moves the value in the key source to destination.
E. Ordered collection type (sorted set)
An ordered collection type that is based on a collection type has a fraction associated with each element in the collection, which allows us to not only perform operations that are supported by collection types such as inserting, deleting, and judging whether an element exists, but also the highest (or lowest) fraction of the top n elements, Gets the fractional-related operation of the element within the specified fractional range. Although each element in the collection is different, their scores can be the same.
An ordered collection type is somewhat similar in some ways to a list type.
(1) both are orderly.
(2) Both can obtain a certain range of elements.
But there is a big difference between the two, which makes their application scenarios different.
(1) List types are implemented through linked lists, obtaining data near both ends is extremely fast, and when the elements increase, access to intermediate data is slower, so it is more suitable for applications such as "new" or "log" that rarely accesses intermediate elements.
(2) An ordered collection type is implemented using a hash table and a skip list, so even reading the data in the middle section is fast (the time complexity is O (log (N))).
(3) The position of an element cannot be easily adjusted in the list, but an ordered set can be (by changing the fraction of this element).
(4) Ordered collections are more memory-intensive than list types
An ordered collection type is considered to be the most advanced type of Redis's 5 data types.

Zadd key score member [score member ...]: add element, score can be any real number
Zscore Key member: Gets the fraction of the specified element
Zrange key start Stop [Withscores]: Gets the list of elements ranked in a range (ascending), such as the first three Zrange key 0 2, [withscores] returns the member while returning the score
Zrevrange key start Stop [Withscores]: Return by fractional descending order
Zrangebyscore key min Max [withscores] [limit offset count]: Gets the member (ascending) of the specified fractional range, [limit offset count] starts with the offset member and returns count members
Example Zrangebyscore Scoreboard (+inf LIMIT 5 3 returns more than 80 (excluding 80) of 3 persons starting from the 5th person
Z Incrby key Increment member: Increase the score of an element, increment can be a negative
Zcard key: Gets the number of elements in the collection
Zcount key min Max: Gets the number of elements in the specified fraction range
Zrem key member [member ...] : Delete one or more elements
Zremrangebyrank key start stop: Remove elements in ascending rank range
Zremrangebyscore Key min Max: deleting elements by fractional range
Zrank Key member: Gets the ascending rank of the specified element
Zrevrank Key member: Gets the descending rank of the specified element
Zinterstore destination Numkeys key [key ...] [WEIGHTS weight [weight ...] [Agregate sum| min| MAX]: Calculates the intersection of an ordered set, and if the weights are the same, the score is pressed [agregate sum| min| MAX] Calculation

9.redis of transactions
A. Transaction syntax
A Redis transaction is a collection of a set of commands that require atomic execution. The principle of a transaction is to send a command that belongs to a transaction to Redis, and then let Redis execute the commands sequentially. Multi-exec keywords
Redis>multi
Ok
Redis>sadd "User:1:following" 2
QUEUED
Redis>sadd "User:2:followers" 1
QUEUED
Redis>exec
1) (integer) 1
2) (integer) 1
If there is a syntax error during execution, leave to return, or if other errors (such as a mismatch between the command and the key value type) do not return, continue executing the following command until the end. However, because Redis does not support rollback, Redis can remain concise and fast on the transaction. Also review the two errors mentioned earlier that would cause the transaction to fail, where syntax errors can be found and resolved entirely at development time, and if the use of a well-planned database (with guaranteed key-name specifications, etc.) does not occur, such as a command-to-data type mismatch.
B. Monitoring-watch key
The watch command can monitor one or more keys, and once a key has been modified (or deleted), subsequent transactions will not be executed. Monitoring continues until the first EXEC command executed after watch (the commands in the transaction are executed after exec, so you can modify the watch Monitor's key values after the multi command).
Example:
Redis>set Key 1
Ok
Redis>watch Key
Ok
Redis>set Key 2
Ok
Redis>multi
Ok
Redis>set Key 3
QUEUED
Redis>exec//The key value of watch monitoring was modified before exec was executed, so the exec immediately following the watch was not executed.
(nil)
Redis>get Key
"2"

C. un-monitor-unwatch-can be considered as canceling monitoring before exec
10. Key time to live-expire key seconds set the lifetime of a key, when the time arrives, the key is deleted; TTL key to see the remaining time; PERSIST key to cancel the time to live
Example:
Redis>set Foo Bar
Ok
Redis>expire Foo 20
(integer) 1
Redis>ttl Foo
(integer) 15
Redis>ttl Foo
(integer) 7
redis> TTL foo
(integer)-1//key does not exist, or the key does not have a time to live

Redis>expire Foo 20
(integer) 1
Redis>set foo Bar//re-assigns the key using SET, which is equivalent to deleting the key and re-establishing a new key
Ok
Redis>ttl Foo
(integer)-1
If you use the Watch command to monitor a time-to-live key, the key time expiration is automatically deleted and will not be considered altered by the watch command.
Expireat key stamps timestamp, s unit
Pexpireat Key Stamps Timestamp, MS unit

11. Sorting
Sorting can use an ordered collection, or you can use the sort command.
The sort command can be sorted by multiple list, SET, and zset types of keys.
A. Command format: Sort key [alpha] [DESC] LIMIT start end: [Alpha] means alphabetically; by default ascending; The LIMIT start end takes a sort result from the start to end result returned
The by parameter of the B.sort: the by parameter has the syntax "by reference key". Where the reference key can be a string type key or a field of the hash type key (denoted as the key Name-> field name). If the by parameter is provided, the sort command will no longer be sorted by the value of the element itself, instead the first "*" in the reference key is substituted for each element using the value of the element and the value is obtained, and the elements are sorted based on that value. The reference key can be a hash or a string type.
Example:
Redis>sort tag:ruby:posts by Post:*->time DESC
1) "12"
2) "26"
3) "6"
4) "2"

Sort string: Reference key is String
Redis>lpush sortbylist 2 1 3
(integer) 3
redis>set itemscore:1
OK
Redis>set Itemscore:2
OK
Redis>set itemscore:3 -10
OK
redis>sort sortbylist by itemscore:* DESC
1) "2"
2) " 1 "
3)" 3 "
Example Anytext is a constant key name (even if the Anytext key can not exist), at which point the result of sort is the same as the result of Lrange, no sort operation is performed, and if the reference key values of several elements are the same, The sort command then compares the values of the elements themselves to determine the order of the elements. The get parameter of the
C.sort: The Get parameter does not affect the sort, it does so that the return result of the sort command is no longer the value of the element itself, but the key value specified in the Get parameter. The get parameter has the same rules as the by parameter, and the get parameter also supports the key for the string type and hash type, and uses "*" as the placeholder.
Redis>sort tag:ruby:posts by Post:*->time DESC GET post:*->title
1) "Windows 8 app Designs"
2) "Rethinkdb-an O Pen-source distributed database built with Love "
3)" Uses for CURL "
4)" The Nature of Ruby "  
Sorted back not ID, but the article that corresponds to the ID. (Can redis only sort numbers and letters, not strings?)
D.sort's Store parameter: By default, sort returns the sorting results directly, and if you want to save the sort results, you can use the store parameter.
Example:
SORT some.list STORE cache.sort

12. Message Notification
A. Task queue
When it comes to queues, it's natural to think of Redis's list types. If you want to implement a task queue, you only need to have the producer use the Lpush command to join a key, and let the consumer use the Rpop command to remove the task from the key in a constant way. The Brpop (right-hand stack) and Blpop (left-side stack) commands enable blocking of requests.
The Brpop command receives two parameters, the first is the key name, the second is the time-out, and the unit is seconds. Nil is returned when the new element is still not obtained at this time. The timeout in the previous example is "0", which means that there is no limit on the time to wait, that is, if no new element is added to the list, it will be blocked forever. When an element is obtained, the Brpop command returns two values, namely the key name and the element value.
Example: (implement producer and consumer models in multiple client instances)
In instance A:
Redis A>brpop Queue 0
When you type carriage return, instance 1 is blocked, and an element is added to the queue in instance B:
Redis B>lpush Queue Task
(integer) 1
After the Lpush command executes, instance a immediately returns the result:
1) "Queue"
2) "Task"

B. Priority queue
The Brpop command and the Blpop command can actually simultaneously block read multiple keys at the same time, with the topmost key having the highest precedence, and if all keys have no elements, then the element of the first key is read first.
Blpop key [key ...] timeout: The first key has a higher priority
>lpush queue2 Task2
1) (integer) 1
>lpush Queue3 TASK3
1) (integer) 1
Redis>brpop queue1 queue2 queue3 0
1) "Queue:2"
2) "Task2"

C. " The Publish/Subscribe mode
Publish/Subscribe mode also enables interprocess messaging, as follows: The Publish/subscribe pattern contains two roles, publisher and Subscriber, respectively. Subscribers can subscribe to one or several
channels, and publishers can send messages to the specified channel, and all subscribers who subscribe to the channel receive this message. The
Publisher's command to publish a message is PUBLISH, using
PUBLISH channel message, such as saying "HI" to CHANNEL.1:
redis>publish channel.1 Hi
( Integer) 0 The return value of the
Publish command indicates the number of subscribers that receive this message the Subscription Channel command is subscribe, can subscribe to multiple channels at the same time, use
Subscribechannel[channel ...]   Now open a new REDIS-CLI instance a, use it to subscribe to CHANNEL.1:
Redis a>subscribe channel.1
Reading messages ... (Press Ctrl-c to quit)
1) "Subscribe"
2) "CHANNEL.1"
3) (integer) 1
Executes the subscribe command after the client enters the subscription state, in this state the client cannot use except subscribe/ Unsubscribe/psubscribe/punsubscribe These 4 commands that belong to the "Publish/Subscribe" mode (the following 3 commands are described below), otherwise an error will be issued. Equivalent to blocking in subscription mode. Unsubscribe unsubscribe.

Subscribe to wildcard rules: You can subscribe to the rules specified by the wildcard rules by using the Psubscribe command
>psubscribe channel.? *
Reading messages ... (Press Ctrl-c to quit) 1) "Psubscribe"
2) "channel.? *"
3) (integer) 1

Redis b>publish CHANNEL.1 hi!
(integer) 2
The Subscriber returns the result:
1) "Pmessage"
2) "channel.? *"
3) "CHANNEL.1"
4) "hi!"
You can use the Psubscribe command to subscribe to a channel repeatedly, such as a client performing a psubscribe channel. Channel.? *, when a message is posted to CHANNEL.2, the client receives two messages, while the Publish command returns a value of 2 instead of 1.
The Punsubscribe command allows you to unsubscribe from the specified rule, using the
Punsubscribe [Pattern[pattern ...]
If no parameters are set, all rules will be retired.
The unsubscribe command can only unsubscribe from rules that are subscribed through the Psubscribe command, and does not affect the channels subscribed directly through the Subscribe command, nor does the unsubscribe command affect the rules subscribed by the Psubscribe command. Another error is that using the Punsubscribe command to unsubscribe from a rule does not expand the wildcard character, but rather strict string matching, so punsubscribe* can not unsubscribe channel.* rules, but must use Punsubscribe Channel.* to unsubscribe.

13. Piping
The underlying communication protocol for Redis provides support for pipelines (pipelining). A pipeline can send multiple commands at once and return the results one time after execution, and the set of commands can be sent together through a pipeline when each command in a set of commands does not depend on the result of the previous command's execution. Pipelines reduce the cumulative value of round-trip delays by reducing the number of client-to-Redis communications. Reduce the number of TCP message packets.

14.redis and Python
Redis's official recommended Python client is redis-py, see https://github.com/andymccurdy/redis-py.
How the A.redis python client is used in Python programming:
Import Redis//First need to introduce redis-py:
R=redis. Strictredis ()///The following code will create a Redis connection with the default connection to address 127.0.0.1, Port 6379:
R=redis. Strictredis (host= ' 127.0.0.1 ', port=6379, db=0)//You can also explicitly specify an address that needs to be connected:
R.set (' foo ', ' Bar ') # True
A=r.get (' foo ') # ' bar '
b Hmset/hgetall
Hmset supports storing dictionaries as parameters, while the return value of Hgetall is also a dictionary, which is very convenient to use:
R.hmset (' Dict ', {' name ': ' Bob '})
People=r.hgetall (' Dict ')
Print people # {' name ': ' Bob '}
C. Transactions and pipelines
Redis-py transactions are used in the following ways:
Pipe=r.pipeline ()
Pipe.set (' foo ', ' Bar ')
Pipe.get (' foo ')
Result=pipe.execute ()
Print result # [True, ' Bar ']
Pipelines are used in the same way as transactions, except that they need to be created with parameter transaction=false:
Pipe=r.pipeline (Transaction=false)
Transactions and pipelines also support chained calls:
Result=r.pipeline (). Set (' foo ', ' Bar '). Get (' foo '). Execute ()
# [True, ' Bar ']

15.redis Script
Redis launched the scripting feature in version 2.6, allowing developers to write scripts in the Lua language to be executed in Redis. Most Redis commands can be called in a LUA script
The benefits of using scripts are as follows:
(1) Reduce network overhead: The first piece of code in section 6.1 needs to send 5 requests to Redis, while using the scripting function to do the same requires only one request to be sent, reducing the network round-trip latency.
(2) Atomic manipulation: Redis executes the entire script as a whole, without being inserted by other commands. In other words, there is no need to worry about a race condition when writing a script, or to use a transaction. All the functions that a transaction can accomplish can be implemented with a script.
(3) Multiplexing: Scripts sent by clients are permanently stored in Redis, which means that other clients (projects that can be developed in other languages) can reuse this script without having to use code to complete the same logic.
Here's a LUA script named A.lua.
Local Times=redis.call (' incr ', keys[1])
If Times==1 then--keys[1] key was just created, so set the time to live for it
Redis.call (' expire ', keys[1], argv[1])
End
If Times>tonumber (argv[2]) then
return 0
End
Return 1
So, how do you test this script? First save the code as A.lua, and then enter it in the name line:
Redis-cli--eval A.lua rate.limiting:127.0.0.1, 10 3

The--eval parameter is to tell Redis-cli to read and run the following Lua script, followed by the parameters passed to the Lua script. of which "," before the
rate.limiting:127.0.0.1 is the key to manipulate, which can be obtained in script using keys[1], "," followed by 10 and 3 are parameters, in the script
can be obtained using argv[1] and argv[2]. In combination with the contents of the script, the purpose of this command is to limit the frequency of access to a maximum of 3 times per 10 seconds.
So running this command continuously in the terminal will find that when the frequency of access is less than or equal to 3 times in 10 seconds, 1 is returned, otherwise 0 is returned. Watch the top.
In the command "," the spaces on either side cannot be omitted, otherwise an error will occur.
16.redis and Lua
A. Calling the Redis command in a script
Redis commands can be called using the Redis.call function in the script. Just like this:
Redis.call (' Set ', ' foo ', ' Bar ')
Local Value=redis.call (' Get ', ' foo ') The value of--value is bar
The return value of the Redis.call function is the result of the Redis command execution. The 2nd chapter describes the 5 types of return values for Redis commands
Type, the Redis.call function converts these 5 types of replies to the corresponding LUA data types.
Redis also provides the Redis.pcall function, the same function as Redis.call, the only difference is that when the command execution error Redis.pcall log the error and continue execution, and Redis.call will return the error directly, will not continue execution.
B. Returning a value from a script return
The return statement can be used in the script to return the value to the client, and nil is returned by default if no return statement is executed. Because we can call our own scripts like we call other Redis built-in commands
C. Scripting-related commands
eval command: The format of the eval command is: The number of the Eval script content key parameter [key ...] [Arg ...]
Data can be passed to the script through both the key and ARG parameters, whose values can be accessed in the script using the keys and argv two table-type global variables
For example, we want to implement a set command with the scripting feature (which we don't do in reality, of course), and the script content is like this:
Return Redis.call (' SET ', keys[1], argv[1])
Now open REDIS-CLI to execute this script:
Redis>eval "Return Redis.call (' SET ', keys[1], argv[1])" 1 foo bar
Ok
Redis>get Foo
"Bar"
Evalsha command:
Given the length of the script, if each invocation of the script requires that the entire script be passed to Redis
and more bandwidth. To solve this problem, Redis provides a Evalsha command that allows developers to SHA1 through the contents of the script
Digest to execute the script, which uses the same command as Eval, but replaces the script content with the SHA1 of the script content
Summary.
The general flow of using the Evalsha command in your program is as follows.
(1) First calculate the SHA1 summary of the script and execute the script using the Evalsha command.
(2) The return value is obtained, and if the "NOSCRIPT" error is returned, the script is re-executed using the eval command.
While this process is a little cumbersome, it is fortunate that many of the REDIS clients in the programming language will replace the developer
into this process. For example, when using the Node_redis client to perform the eval command, Node_redis will first attempt to execute the Evalsha
command, the eval command is executed if it fails

This article from "Tech record" blog, declined reprint!

Redis Database Notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.