Redis Getting Started Tutorial

Source: Internet
Author: User
Tags password protection value store

I. BASIC KNOWLEDGE 1.1 database

In Redis, the database is simply identified with a numeric number, and the default database number is 0. If you want to switch to a different database, you can use the Select command to implement it. Typing select 1,redis in the command line interface should reply to an OK message, and then the prompt in the command line interface will become similar to Redis 127.0.0.1:6379[1]>. If you want to switch back to the default database, simply type it at the command line interface select 0

1.2 commands, keywords, and values

Redis is more than just a simple keyword-value store, and from its core concept, each of the 5 data structures of Redis has at least one keyword and one value

Keys are used to identify data blocks, values are actual values associated with a keyword, and can be strings, integers, serialized objects (using JSON, XML, or other formats)

Basic composition of REDIS commands, such as:set Users:leto "{Name:leto, Planet:dune, likes: [Spice]}"

Keywords and values are the basic concepts of redis, and the Get and set commands are the simplest to use

1.3 Redis Query

For Redis, the keyword is everything, and the value doesn't make any sense. Redis is not allowed to query by value

1.4 Memory and persistence

Redis is a persistent in-memory store (in-memory persistent store) By default, Redis determines the number of keywords that have changed, and then creates a snapshot of the database (snapshot) on disk. You can set this, and if the X keyword has changed, store the database once every Y seconds. By default, if 1000 or more keywords are changed, Redis stores the database every 60 seconds, and if 9 or fewer keywords are changed, Redis stores the database every 15 minutes

As for memory, Redis retains all of the data in memory. Obviously, running Redis has a low cost: Because RAM is still the most expensive server hardware part

1.5 Summary

Keys are a string used to identify a piece of data

Values are an arbitrary sequence of bytes, and Redis does not care what they are essentially

Redis shows (and implements) 5 specialized data structures

The above points make redis fast and easy to use, but know that Redis is not suitable for all scenarios

II. data structure of Redis

About key

    • Key not too long, try not to exceed 1024 bytes, this not only consumes memory, but also reduces the efficiency of the lookup
    • Key also not too short, too short, the readability of key will be reduced
    • In a project, it is best to use a unified naming scheme, such as USER:10000:PASSWD
2.1 String strings
127.0.0.1:6379> set mynum "2"OK127.0.0.1:6379> get mynum"2"127.0.0.1:6379> incr mynum(integer) 3127.0.0.1:6379> get mynum"3"

Since the incr and other directives themselves have the characteristics of atomic operations, we can fully utilize Redis's incr, Incrby, DECR, Decrby and other instructions to achieve atomic count effect, if, in a certain scenario, there are 3 clients read the value of Mynum (value 2), Then add 1 to it at the same time, then the value of the last Mynum must be 5. Many websites use this feature of Redis to achieve statistical counting requirements on the business.

2.2 List Lists

Common operations of lists include Lpush, Rpush, Lrange and so on. We can use Lpush to insert a new element on the left side of lists, insert a new element on the right side of the lists with Rpush, and use the Lrange command to extract the element from the lists by specifying a range.

//新建一个list叫做mylist,并在列表头部插入元素"1"127.0.0.1:6379> lpush mylist "1"//返回当前mylist中的元素个数(integer) 1//在mylist右侧插入元素"2"127.0.0.1:6379> rpush mylist "2"(integer) 2//在mylist左侧插入元素"0"127.0.0.1:6379> lpush mylist "0"(integer) 3//列出mylist中从编号0到编号1的元素127.0.0.1:6379> lrange mylist 0 11) "0"2) "1"//列出mylist中从编号0到倒数第一个元素127.0.0.1:6379> lrange mylist 0 -11) "0"2) "1"3) "2"

The application of lists is quite extensive, just to cite a few examples:

    • We can use lists to implement a message queue, and we can ensure that sequencing does not need to be ordered by order by like MySQL.
    • The use of Lrange can also be very convenient to achieve the function of paging.
    • In the blogging system, comments for each blog post can also be stored in a single list.
2.3 Integrated Sets

A collection of Redis, an unordered collection of elements in a collection that has no precedence. Collection-related operations are also rich, such as adding new elements, deleting existing elements, taking intersections, taking sets, and taking sets of differences.

//向集合myset中加入一个新元素"one"127.0.0.1:6379> sadd myset "one"(integer) 1127.0.0.1:6379> sadd myset "two"(integer) 1//列出集合myset中的所有元素127.0.0.1:6379> smembers myset1) "one"2) "two"//判断元素1是否在集合myset中,返回1表示存在127.0.0.1:6379> sismember myset "one"(integer) 1//判断元素3是否在集合myset中,返回0表示不存在127.0.0.1:6379> sismember myset "three"(integer) 0//新建一个新的集合yourset127.0.0.1:6379> sadd yourset "1"(integer) 1127.0.0.1:6379> sadd yourset "2"(integer) 1127.0.0.1:6379> smembers yourset1) "1"2) "2"//对两个集合求并集127.0.0.1:6379> sunion myset yourset1) "1"2) "one"3) "2"4) "two"

There are also some common ways to use collections, such as QQ, which has a social function called a "friend tag".

2.4 Ordered set sorted sets

Redis also provides an ordered set (sorted sets). Each element in an ordered collection is associated with an ordinal (score), which is the basis for sorting. Most of the time, we're calling an ordered set of zsets in Redis, because in Redis, an ordered set of related operations directives start with Z, such as Zrange, Zadd, Zrevrange, Zrangebyscore, and so on.

//新增一个有序集合myzset,并加入一个元素baidu.com,给它赋予的序号是1:127.0.0.1:6379> zadd myzset 1 baidu.com(integer) 1//向myzset中新增一个元素360.com,赋予它的序号是3127.0.0.1:6379> zadd myzset 3 360.com(integer) 1//向myzset中新增一个元素google.com,赋予它的序号是2127.0.0.1:6379> zadd myzset 2 google.com(integer) 1//列出myzset的所有元素,同时列出其序号,可以看出myzset已经是有序的了。127.0.0.1:6379> zrange myzset 0 -1 withscores1) "baidu.com"2) "1"3) "google.com"4) "2"5) "360.com"6) "3"//只列出myzset的元素127.0.0.1:6379> zrange myzset 0 -11) "baidu.com"2) "google.com"3) "360.com"
2.5 hash Hashes

Hashes a mapping between a string and a string value, such as a user storing its full name, last name, age, and so on, is a good place to use a hash

//建立哈希,并赋值127.0.0.1:6379> HMSET user username antirez password P1pp0 age 34OK//列出哈希的内容127.0.0.1:6379> HGETALL user1) "username"2) "antirez"3) "password"4) "P1pp0"5) "age"6) "34"//更改哈希中的某一个值127.0.0.1:6379> HSET user password 12345(integer) 0//再次列出哈希的内容127.0.0.1:6379> HGETALL user1) "username"2) "antirez"3) "password"4) "12345"5) "age"6) "34"
Iii. Redis Persistent-rdb and aof

Persistence does not belong to the entry range, found a few relatively good articles, interested in Welcome to read

    • Redis Persistent RDB and aof
    • [Redis Persistence Rdb and aof comparison]
    • [Redis Series: Rdb persistence and aof persistence]
Iv.. redis.conf File Configuration Items

REDIS.CONF configuration items are described below:

  1. Redis defaults to not run as a daemon, can be modified by this configuration item, and the daemon is enabled with Yes
    daemonize no
  2. When Redis is running as a daemon, Redis writes the PID to the file by default /var/run/redis.pid and can be specified by pidfile
    pidfile /var/run/redis.pid
  3. Specify the Redis listening port, the default port is 6379 , here is a story, because 6379 Merz the corresponding number on the phone keypad, and Merz from the Italian showgirl Alessia Merz name
    port 6379
  4. The host address of the binding
    bind 127.0.0.1
  5. When the client closes the connection after a period of inactivity, if 0 is specified, the feature is turned off
    timeout 30
  6. Specify logging level, Redis supports four levels in total: Debug, verbose, notice, warning, default = verbose
    loglevel verbose
  7. logging mode, default to standard output, if Redis is configured to run as Daemon, and here it is configured as logging mode as standard output, the log will be sent to/dev/null
    logfile stdout
  8. Set the number of databases, the default database is 0, you can specify the database ID on the connection using the Select <dbid> command
    databases 16
  9. Specify how many times the update operation will synchronize the data to the data file and can be combined with multiple conditions
    save <seconds> <changes>
    There are three conditions available in the Redis default configuration file:
    ' Save 900 1
    Save 300 10
    Save 60 10000 '
    Represents 1 changes in 900 seconds (15 minutes), 5 changes in 300 seconds (10 minutes), and 60 changes in 10,000 seconds .
  10. Specifies whether to compress data when stored to a local database, by default Yes,redis with LZF compression, which can be turned off if you want to save CPU time, but will cause the database file to become huge
    rdbcompression yes
  11. Specifies the local database file name, the default value is Dump.rdb
    dbfilename dump.rdb
  12. Specify local Database storage directory

    "Dir./"
  13. Set the IP address and port of the master service when this machine is a Slav service, and it will automatically synchronize data from master when Redis boots

    "' Slaveof <masterip> <masterport>"
  14. When the master service has password protection set, the Slav service connects the password of master

    "' Masterauth <master-password> '
  15. Set the Redis connection password, if the connection password is configured, the client needs to provide a password via auth <password> command when connecting to Redis, which is turned off by default

    "' Requirepass foobared '"
  16. Set the maximum number of client connections at the same time, the default is unlimited, Redis can open at the same number of client connections for the Redis process can open the maximum number of file descriptors, if set maxclients 0, indicating no restrictions. When the number of client connections reaches the limit, Redis closes the new connection and returns the max number of clients reached error message to the client
    maxclients 128
  17. Specify the Redis maximum memory limit, Redis will load the data into memory when it is started, Redis will try to clear the expired or expiring key first, when this method is processed, still reach the maximum memory setting, will no longer write operation, but still can read operation. Redis new VM mechanism will store key memory, value will be stored in swap area

    "' MaxMemory <bytes> '
  18. Specifies whether logging occurs after each update operation, which, by default, writes data to disk asynchronously, which, if not turned on, may cause data loss over time for a power outage. Because the Redis itself synchronizes data files in sync with the save conditions above, some data will only exist in memory for a period of time. Default is No
    appendonly no
  19. Specifies the update log file name, which defaults to appendonly.aof
    appendfilename appendonly.aof
  20. Specify an update log condition with 3 optional values:

    No: Indicates that the data cache of the operating system is synchronized to disk (fast)
    Always: Represents a manual call to Fsync () to write data to disk (slow, secure) after each update operation
    Everysec: Indicates synchronization once per second (trade-offs, default values)
    Appendfsync everysec
  21. Specifies whether the virtual memory mechanism is enabled, the default value is no, a simple introduction, the VM mechanism to store data paging, by Redis will be less accessible pages, such as cold data swap to disk, access to more pages from the disk automatically swapped out into memory
    vm-enabled no
  22. Virtual memory file path, default value of/tmp/redis.swap, not available for multiple Redis instance shares
    vm-swap-file /tmp/redis.swap
  23. All data larger than Vm-max-memory is stored in virtual memory, regardless of how small the vm-max-memory setting is, all index data is in memory (Redis's index data is keys), that is, when Vm-max-memory is set to 0, In fact, all value is present on disk. The default value is 0
    vm-max-memory 0
  24. The Redis swap file is divided into a number of page, an object can be saved on more than one page, but a page can not be shared by multiple objects, Vm-page-size is based on the size of the stored data to set, the author suggests that if you store many small objects, The page size is best set to 32 or 64bytes, and if you store large objects, you can use a larger page, and if you are unsure, use the default values
    vm-page-size 32
  25. Set the number of pages in the swap file, which consumes 1byte of memory per 8 pages on disk because the page table (a bitmap that indicates that the page is idle or used) is in memory.
    vm-pages 134217728
  26. Set the number of threads to access the swap file, preferably without exceeding the machine's number of cores, if set to 0, all operations on the swap file are serial and may cause a long delay. The default value is 4
    vm-max-threads 4
  27. Sets whether to merge smaller packages into a single package when answering to the client, which is turned on by default
    glueoutputbuf yes
  28. Specifies that a special hashing algorithm is used when more than a certain number or maximum element exceeds a critical value
    ' Hash-max-zipmap-entries 64
    Hash-max-zipmap-value 512 '
  29. Specifies whether to activate the reset hash, which is turned on by default
    activerehashing yes
  30. Specifies that other configuration files can be used to use the same profile between multiple Redis instances on the same host, while each instance has its own specific configuration file

    include /path/to/local.conf

    • What is a daemon process?
      The daemon (Daemon process), which is usually called the Daemon process (daemon), is the background service process in Linux. It is a long-lived process, usually independent of the control terminal and periodically performs some sort of task or waits to handle certain occurrences. The daemon is a special orphan process that is out of the terminal and why is it out of the terminal? The reason for leaving the terminal is to prevent the process from being interrupted by information generated by any terminal, and its information during execution is not displayed on any terminal. Because in Linux, each system communicates with the user interface called the terminal, every process that starts from this terminal will be attached to this terminal, this terminal is called the control terminal of these processes, when the control terminal is closed, the corresponding process will automatically shut down.
V. Transaction processing

MULTI, EXEC, DISCARD, watch directives form the basis of REDIS transaction processing

Multi used to assemble a business;

exec is used to perform a transaction;

Discard used to cancel a transaction;

Watch is used to monitor some keys and cancel the execution of a transaction once the key has been changed before the transaction executes.

Original address: 1190000016649276

Redis Getting Started Tutorial

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.