Redis 学习笔记

Redis 学习笔记

原创编写: 王宇 
2016-11-07


 

 


Redis 环境

  • 安装Redis
  1. $sudo apt-getupdate
  2. $sudo apt-getinstall redis-server
  • 启动Redis
  1. $ redis-server
  • 检察Redis 是否工作正常
  1. $ redis-cli
  2. redis127.0.0.1:6379>ping
  3. PONG

配置Redis

  • 配置文件:redis.conf

    • 语法:

      1. redis127.0.0.1:6379>CONFIG GET CONFIG_SETTING_NAME
    • 例子

      1. redis127.0.0.1:6379>CONFIG GET loglevel
      2. redis127.0.0.1:6379>CONFIG GET*
  • 修改配置:
    • 语法:

      1. redis127.0.0.1:6379>CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
    • 例子

      1. redis127.0.0.1:6379>CONFIG SET loglevel"notice"
      2. OK
      3. redis127.0.0.1:6379>CONFIG GET loglevel

Redis 数据类型(5种)

  • Strings-字符串 
    例子:
  1. redis127.0.0.1:6379>SET name"tutorialspoint"
  2. OK
  3. redis127.0.0.1:6379>GET name
  4. "tutorialspoint"
  • Hashes-字典 
    例子:
  1. redis127.0.0.1:6379>HMSET user:1username tutorialspoint password tutorialspoint points200
  2. OK
  3. redis127.0.0.1:6379>HGETALL user:1
  4. 1)"username"
  5. 2)"tutorialspoint"
  6. 3)"password"
  7. 4)"tutorialspoint"
  8. 5)"points"
  9. 6)"200
  • Lists-列表 
    时间复杂度:O(N) 
    例子:
  1. redis127.0.0.1:6379>lpush tutoriallist redis
  2. (integer)1
  3. redis127.0.0.1:6379>lpush tutoriallist mongodb
  4. (integer)2
  5. redis127.0.0.1:6379>lpush tutoriallist rabitmq
  6. (integer)3
  7. redis127.0.0.1:6379>lrange tutoriallist010
  8. 1)"rabitmq"
  9. 2)"mongodb"
  10. 3)"redis"
  • Sets-集合 
    时间复杂度:O(1) 
    例子:
  1. redis127.0.0.1:6379>sadd tutoriallist redis
  2. (integer)1
  3. redis127.0.0.1:6379>sadd tutoriallist mongodb
  4. (integer)1
  5. redis127.0.0.1:6379>sadd tutoriallist rabitmq
  6. (integer)1
  7. redis127.0.0.1:6379>sadd tutoriallist rabitmq
  8. (integer)0
  9. redis127.0.0.1:6379>smembers tutoriallist
  10. 1)"rabitmq"
  11. 2)"mongodb"
  12. 3)"redis"
  • Stored Sets-有序集合 
    例子:
  1. redis127.0.0.1:6379>zadd tutoriallist0redis
  2. (integer)1
  3. redis127.0.0.1:6379>zadd tutoriallist0mongodb
  4. (integer)1
  5. redis127.0.0.1:6379>zadd tutoriallist0rabitmq
  6. (integer)1
  7. redis127.0.0.1:6379>zadd tutoriallist0rabitmq
  8. (integer)0
  9. redis127.0.0.1:6379>ZRANGEBYSCORE tutoriallist01000
  10. 1)"redis"
  11. 2)"mongodb"
  12. 3)"rabitmq"

Redis 命令

  • 服务器端
    1. $redis-cli-h host-p port-a password

Redis 操作Keys命令

S.N.Command & Description
1DEL key This command deletes the key, if exists
2DUMP key This command returns a serialized version of the value stored at the specified key.
3EXISTS key This command checks whether the key exists or not.
4EXPIRE key seconds Expires the key after the specified time
5EXPIREAT key timestamp Expires the key after the specified time. Here time is in Unix timestamp format
6PEXPIRE key milliseconds Set the expiry of key in milliseconds
7PEXPIREAT key milliseconds-timestamp Set the expiry of key in unix timestamp specified as milliseconds
8KEYS pattern Find all keys matching the specified pattern
9MOVE key db Move a key to another database
10PERSIST key Remove the expiration from the key
11PTTL key Get the remaining time in keys expiry in milliseconds.
12TTL key Get the remaining time in keys expiry.
13RANDOMKEY Return a random key from redis
14RENAME key newkey Change the key name
15RENAMENX key newkey Rename key, if new key doesn’t exist
16TYPE key Return the data type of value stored in key.

Redis-Strings 命令列表

S.N.Command & Description
1SET key value This command sets the value at the specified key
2GET key Get the value of a key.
3GETRANGE key start end Get a substring of the string stored at a key
4GETSET key value Set the string value of a key and return its old value
5GETBIT key offset Returns the bit value at offset in the string value stored at key
6MGET key1 [key2..] Get the values of all the given keys
7SETBIT key offset value Sets or clears the bit at offset in the string value stored at key
8SETEX key seconds value Set the value with expiry of a key
9SETNX key value Set the value of a key, only if the key does not exist
10SETRANGE key offset value Overwrite part of a string at key starting at the specified offset
11STRLEN key Get the length of the value stored in a key
12MSET key value [key value …] Set multiple keys to multiple values
13MSETNX key value [key value …] Set multiple keys to multiple values, only if none of the keys exist
14PSETEX key milliseconds value Set the value and expiration in milliseconds of a key
15INCR key Increment the integer value of a key by one
16INCRBY key increment Increment the integer value of a key by the given amount
17INCRBYFLOAT key increment Increment the float value of a key by the given amount
18DECR key Decrement the integer value of a key by one
19DECRBY key decrement Decrement the integer value of a key by the given number
20APPEND key value Append a value to a key

Redis-Hashes 命令列表

S.N.Command & Description
1HDEL key field2 [field2] Delete one or more hash fields
2HEXISTS key field Determine whether a hash field exists or not
3HGET key field Get the value of a hash field stored at specified key
4HGETALL key Get all the fields and values stored in a hash at specified key
5HINCRBY key field increment Increment the integer value of a hash field by the given number
6HINCRBYFLOAT key field increment Increment the float value of a hash field by the given amount
7HKEYS key Get all the fields in a hash
8HLEN key Get the number of fields in a hash
9HMGET key field1 [field2] Get the values of all the given hash fields
10HMSET key field1 value1 [field2 value2 ] Set multiple hash fields to multiple values
11HSET key field value Set the string value of a hash field
12HSETNX key field value Set the value of a hash field, only if the field does not exist
13HVALS key Get all the values in a hash
14HSCAN key cursor [MATCH pattern] [COUNT count] Incrementally iterate hash fields and associated values

Redis-Lists 命令列表

S.N.Command & Description
1BLPOP key1 [key2 ] timeout Remove and get the first element in a list, or block until one is available
2BRPOP key1 [key2 ] timeout Remove and get the last element in a list, or block until one is available
3BRPOPLPUSH source destination timeout Pop a value from a list, push it to another list and return it; or block until one is available
4LINDEX key index Get an element from a list by its index
5LINSERT key BEFORE
6LLEN key Get the length of a list
7LPOP key Remove and get the first element in a list
8LPUSH key value1 [value2] Prepend one or multiple values to a list
9LPUSHX key value Prepend a value to a list, only if the list exists
10LRANGE key start stop Get a range of elements from a list
11LREM key count value Remove elements from a list
12LSET key index value Set the value of an element in a list by its index
13LTRIM key start stop Trim a list to the specified range
14RPOP key Remove and get the last element in a list
15RPOPLPUSH source destination Remove the last element in a list, append it to another list and return it
16RPUSH key value1 [value2] Append one or multiple values to a list
17RPUSHX key value Append a value to a list, only if the list exists

Redis-Sets 命令列表

S.N.Command & Description
1SADD key member1 [member2] Add one or more members to a set
2SCARD key Get the number of members in a set
3SDIFF key1 [key2] Subtract multiple sets
4SDIFFSTORE destination key1 [key2] Subtract multiple sets and store the resulting set in a key
5SINTER key1 [key2] Intersect multiple sets
6SINTERSTORE destination key1 [key2] Intersect multiple sets and store the resulting set in a key
7SISMEMBER key member Determine if a given value is a member of a set
8SMEMBERS key Get all the members in a set
9SMOVE source destination member Move a member from one set to another
10SPOP key Remove and return a random member from a set
11SRANDMEMBER key [count] Get one or multiple random members from a set
12SREM key member1 [member2] Remove one or more members from a set
13SUNION key1 [key2] Add multiple sets
14SUNIONSTORE destination key1 [key2] Add multiple sets and store the resulting set in a key
15SSCAN key cursor [MATCH pattern] [COUNT count] Incrementally iterate Set elements

Redis-Sorted Sets 命令列表

S.N.Command & Description
1ZADD key score1 member1 [score2 member2] Add one or more members to a sorted set, or update its score if it already exists
2ZCARD key Get the number of members in a sorted set
3ZCOUNT key min max Count the members in a sorted set with scores within the given values
4ZINCRBY key increment member Increment the score of a member in a sorted set
5ZINTERSTORE destination numkeys key [key …] Intersect multiple sorted sets and store the resulting sorted set in a new key
6ZLEXCOUNT key min max Count the number of members in a sorted set between a given lexicographical range
7ZRANGE key start stop [WITHSCORES] Return a range of members in a sorted set, by index
8ZRANGEBYLEX key min max [LIMIT offset count] Return a range of members in a sorted set, by lexicographical range
9ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT] Return a range of members in a sorted set, by score
10ZRANK key member Determine the index of a member in a sorted set
11ZREM key member [member …] Remove one or more members from a sorted set
12ZREMRANGEBYLEX key min max Remove all members in a sorted set between the given lexicographical range
13ZREMRANGEBYRANK key start stop Remove all members in a sorted set within the given indexes
14ZREMRANGEBYSCORE key min max Remove all members in a sorted set within the given scores
15ZREVRANGE key start stop [WITHSCORES] Return a range of members in a sorted set, by index, with scores ordered from high to low
16ZREVRANGEBYSCORE key max min [WITHSCORES] Return a range of members in a sorted set, by score, with scores ordered from high to low
17ZREVRANK key member Determine the index of a member in a sorted set, with scores ordered from high to low
18ZSCORE key member Get the score associated with the given member in a sorted set
19ZUNIONSTORE destination numkeys key [key …] Add multiple sorted sets and store the resulting sorted set in a new key
20ZSCAN key cursor [MATCH pattern] [COUNT count] Incrementally iterate sorted sets elements and associated scores

Redis-HyperLogLog-计算基数

  • 例子
  1. redis127.0.0.1:6379>PFADD tutorials"redis"
  2. 1)(integer)1
  3. redis127.0.0.1:6379>PFADD tutorials"mongodb"
  4. 1)(integer)1
  5. redis127.0.0.1:6379>PFADD tutorials"mysql"
  6. 1)(integer)1
  7. redis127.0.0.1:6379>PFCOUNT tutorials
  8. (integer)3
S.N.Command & Description
1PFADD key element [element …] Adds the specified elements to the specified HyperLogLog.
2PFCOUNT key [key …] Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
3PFMERGE destkey sourcekey [sourcekey …] Merge N different HyperLogLogs into a single one.

Redis - Publish Subscribe

Redis的pub sub 实现了发送、接受message 的系统。

  • 例子
  1. redis127.0.0.1:6379>SUBSCRIBE redisChat
  2. Readingmessages...(pressCtrl-C to quit)
  3. 1)"subscribe"
  4. 2)"redisChat"
  5. 3)(integer)1
  1. redis127.0.0.1:6379>PUBLISH redisChat"Redis is a great caching technique"
  2. (integer)1
  3. redis127.0.0.1:6379>PUBLISH redisChat"Learn redis by tutorials point"
  4. (integer)1
  5. 1)"message"
  6. 2)"redisChat"
  7. 3)"Redis is a great caching technique"
  8. 1)"message"
  9. 2)"redisChat"
  10. 3)"Learn redis by tutorials point"
S.N.Command & Description
1PSUBSCRIBE pattern [pattern …] Subscribe to channels matching the given patterns.
2PUBSUB subcommand [argument [argument …]] Tells the state of pubsub system eg which clients are active on the server.
3PUBLISH channel message Post a message to a channel.
4PUNSUBSCRIBE [pattern [pattern …]] Stop listening for messages posted to channels matching the given patterns.
5SUBSCRIBE channel [channel …] Listen for messages published to the given channels.
6UNSUBSCRIBE [channel [channel …]] Stop listening for messages posted to the given channels.

Redis-Transaction 事务

执行一组命令

  • 例子
  1. redis127.0.0.1:6379>MULTI
  2. OK
  3. redis127.0.0.1:6379>SET tutorial redis
  4. QUEUED
  5. redis127.0.0.1:6379>GET tutorial
  6. QUEUED
  7. redis127.0.0.1:6379>INCR visitors
  8. QUEUED
  9. redis127.0.0.1:6379>EXEC
  10. 1)OK
  11. 2)"redis"
  12. 3)(integer)1
S.N.Command & Description
1DISCARD Discard all commands issued after MULTI
2EXEC Execute all commands issued after MULTI
3MULTI Mark the start of a transaction block
4UNWATCH Forget about all watched keys
5WATCH key [key …] Watch the given keys to determine execution of the MULTI/EXEC block

Redis-Scripting

  • 语法
  1. redis127.0.0.1:6379>EVAL script numkeys key[key...]arg[arg...]
  • 例子
  1. redis127.0.0.1:6379>EVAL"return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"2key1 key2 first second
  2. 1)"key1"
  3. 2)"key2"
  4. 3)"first"
  5. 4)"second"
S.N.Command & Description
1EVAL script numkeys key [key …] arg [arg …] Execute a Lua script.
2EVALSHA sha1 numkeys key [key …] arg [arg …] Execute a Lua script.
3SCRIPT EXISTS script [script …] Check existence of scripts in the script cache.
4SCRIPT FLUSH Remove all the scripts from the script cache.
5SCRIPT KILL Kill the script currently in execution.
6SCRIPT LOAD script Load the specified Lua script into the script cache.

Redis - Connections

  • 例子
  1. redis127.0.0.1:6379>AUTH"password"
  2. OK
  3. redis127.0.0.1:6379>PING
  4. PONG
  • 链接命令
S.N.Command & Description
1AUTH password Authenticate to the server with given password
2ECHO message Print the given string
3PING Check whether server is running or not
4QUIT Close the current connection
5SELECT index Change the selected database for the current connection

Redis - Server

  • 例子
  1. redis127.0.0.1:6379>INFO
  • Redis server 命令列表
S.N.Command & Description
1BGREWRITEAOF Asynchronously rewrite the append-only file
2BGSAVE Asynchronously save the dataset to disk
3CLIENT KILL [ip:port] [ID client-id] Kill the connection of a client
4CLIENT LIST Get the list of client connections connection to the server
5CLIENT GETNAME Get the name of current connection
6CLIENT PAUSE timeout Stop processing commands from clients for specified time
7CLIENT SETNAME connection-name Set the current connection name
8CLUSTER SLOTS Get array of Cluster slot to node mappings
9COMMAND Get array of Redis command details
10COMMAND COUNT Get total number of Redis commands
11COMMAND GETKEYS Extract keys given a full Redis command
12BGSAVE Asynchronously save the dataset to disk
13COMMAND INFO command-name [command-name …] Get array of specific Redis command details
14CONFIG GET parameter Get the value of a configuration parameter
15CONFIG REWRITE Rewrite the configuration file with the in memory configuration
16CONFIG SET parameter value Set a configuration parameter to the given value
17CONFIG RESETSTAT Reset the stats returned by INFO
18DBSIZE Return the number of keys in the selected database
19DEBUG OBJECT key Get debugging information about a key
20DEBUG SEGFAULT Make the server crash
21FLUSHALL Remove all keys from all databases
22FLUSHDB Remove all keys from the current database
23INFO [section] Get information and statistics about the server
24LASTSAVE Get the UNIX time stamp of the last successful save to disk
25MONITOR Listen for all requests received by the server in real time
26ROLE Return the role of the instance in the context of replication
27SAVE Synchronously save the dataset to disk
28SHUTDOWN [NOSAVE] [SAVE] Synchronously save the dataset to disk and then shut down the server
29SLAVEOF host port Make the server a slave of another instance, or promote it as master
30SLOWLOG subcommand [argument] Manages the Redis slow queries log
31SYNC command used for replication
32TIME Return the current server time

Redis - 备份

  • 语法 和例子
  1. 127.0.0.1:6379>SAVE
  2. OK
  • 恢复Redis数据

    • 通过CONFIG 命令获得数据的存储路径:

      1. 127.0.0.1:6379>CONFIGgetdir
      2. 1)"dir"
      3. 2)"/user/tutorialspoint/redis-2.8.13/src"
    • 恢复(BGSAVE)

      1. 127.0.0.1:6379>BGSAVE
      2. Backgroundsaving started

Redis - 安全

默认状态下,Redis没有密码,要在设置密码:

  1. 127.0.0.1:6379>CONFIGsetrequirepass"tutorialspoint"
  2. OK
  3. 127.0.0.1:6379>CONFIGgetrequirepass
  4. 1)"requirepass"
  5. 2)"tutorialspoint"
  6. 127.0.0.1:6379>AUTH"tutorialspoint"
  7. OK
  8. 127.0.0.1:6379>SET mykey"Test value"
  9. OK
  10. 127.0.0.1:6379>GET mykey
  11. "Test value"

Redis 监控执行效率(Benchmarks)

  • 语法
  1. redis-benchmark[option][option value]
  2. 例如:
  3. redis-benchmark-n100000
S.N.OptionDescriptionDefault Value
1-hSpecifies server host name127.0.0.1
2-pSpecifies server port6379
3-sSpecifies server socket 
4-cSpecifies number of parallel connections50
5-nSpecifies total number of requests10000
6-dSpecifies data size of SET/GET value in bytes2
7-k1=keep alive 0=reconnect1
8-rUse random keys for SET/GET/INCR, random values for SADD 
9-pPipeline requests1
10-qForces Quiet to redis. Just show query/sec values 
11–csvOutput in CSV format 
12-lGenerates loop, Run the tests forever 
13-tOnly run the comma-separated list of tests. 
14-IIdle mode. Just open N idle connections and wait. 
  • 例子
  1. redis-benchmark-h127.0.0.1-p6379-tset,lpush-n100000-q
  2. SET:146198.83requests per second
  3. LPUSH:145560.41requests per second

Redis - 客户端连接(Client Connection)

  • 客户端最大连接数
  1. configgetmaxclients
  2. 1)"maxclients"
  3. 2)"10000"
  • Client 命令列表
S.N.CommandDescription
1CLIENT LISTReturns the list of clients connected to redis server
2CLIENT SETNAMEAssigns a name to the current connection
3CLIENT GETNAMEReturns the name of the current connection as set by CLIENT SETNAME.
4CLIENT PAUSEThis is a connections control command able to suspend all the Redis clients for the specified amount of time (in milliseconds).
5CLIENT KILLThis command closes a given client connection.

Redis 管道(Pipelining)

请求-应答模式

Redis - 分区(Partitioning)

将数据分布到不同的redis实例中

  • 分区动机

    更好的利用多台机器的存储资源横向扩展,毕竟单台机器的存储资源是有限的。 
    更好的利用多台计算机的处理器资源、网络带宽资源。

Redis - Java

  1. importredis.clients.jedis.Jedis;
  2. publicclassRedisJava{
  3. publicstaticvoidmain(String[]args){
  4. //Connecting to Redis server on localhost
  5. Jedisjedis=newJedis("localhost");
  6. System.out.println("Connection to server sucessfully");
  7. //check whether server is running or not
  8. System.out.println("Server is running: "+jedis.ping());
  9. }
  10. }
  11. $javacRedisJava.java
  12. $javaRedisJava
  13. Connectionto server sucessfully
  14. Serverisrunning:PONG
  • Redis Java String Example
  1. importredis.clients.jedis.Jedis;
  2. publicclassRedisStringJava{
  3. publicstaticvoidmain(String[]args){
  4. //Connecting to Redis server on localhost
  5. Jedisjedis=newJedis("localhost");
  6. System.out.println("Connection to server sucessfully");
  7. //set the data in redis string
  8. jedis.set("tutorial-name","Redis tutorial");
  9. // Get the stored data and print it
  10. System.out.println("Stored string in redis:: "+jedis.get("tutorial-name"));
  11. }
  12. }
  13. $javacRedisStringJava.java
  14. $javaRedisStringJava
  15. Connectionto server sucessfully
  16. Storedstringinredis::Redistutorial
  • Redis Java List Example
  1. importredis.clients.jedis.Jedis;
  2. publicclassRedisListJava{
  3. publicstaticvoidmain(String[]args){
  4. //Connecting to Redis server on localhost
  5. Jedisjedis=newJedis("localhost");
  6. System.out.println("Connection to server sucessfully");
  7. //store data in redis list
  8. jedis.lpush("tutorial-list","Redis");
  9. jedis.lpush("tutorial-list","Mongodb");
  10. jedis.lpush("tutorial-list","Mysql");
  11. // Get the stored data and print it
  12. List<String>list=jedis.lrange("tutorial-list",0,5);
  13. for(inti=0;i<list.size();i++){
  14. System.out.println("Stored string in redis:: "+list.get(i));
  15. }
  16. }
  17. }
  18. $javacRedisListJava.java
  19. $javaRedisListJava
  20. Connectionto server sucessfully
  21. Storedstringinredis::Redis
  22. Storedstringinredis::Mongodb
  23. Storedstringinredis::Mysql
  • Redis Java Keys Example
  1. importredis.clients.jedis.Jedis;
  2. publicclassRedisKeyJava{
  3. publicstaticvoidmain(String[]args){
  4. //Connecting to Redis server on localhost
  5. Jedisjedis=newJedis("localhost");
  6. System.out.println("Connection to server sucessfully");
  7. //store data in redis list
  8. // Get the stored data and print it
  9. List<String>list=jedis.keys("*");
  10. for(inti=0;i<list.size();i++){
  11. System.out.println("List of stored keys:: "+list.get(i));
  12. }
  13. }
  14. }
  15. $javacRedisKeyJava.java
  16. $javaRedisKeyJava
  17. Connectionto server sucessfully
  18. Listof stored keys::tutorial-name
  19. Listof stored keys::tutorial-list

参考资料

 


版权声明:本文为MrWangyu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。