Redis Beginner Notes

Source: Internet
Author: User
Tags redis server

1. Introduction to Redis
    • Redis is an efficient cache memory database, open source, free, key-value format
    • Compared to other cache products in key-value format, the features/benefits are :
      • Support persistence, can save in-memory data on disk, restart when loading again using
      • Not only supports simple key-value format, but also supports the storage of list, set, Zset, hash and other data structures.
      • Support for data backup, i.e. Master-slave mode data backup
      • High performance, read speed is 110,000 times/s, write speed is 81,000 times/s
2. Redis installation
  • Window under Installation
      • : Https://github.com/MSOpenTech/redis/releases.

        Redis supports 32bit and 64bit to download. Depending on your actual situation, select the 64bit content CP to the custom drive letter installation directory named Redis. such as C:\reids

        Open a CMD window using the CD command to switch directories to C:\redis run redis-server.exe redis.conf .

        If you want to be convenient, you can add the path of Redis to the environment variables of the system, so as to save the path again, the latter redis.conf can be omitted, if omitted, the default is enabled. After entering, the following interface is displayed:

        At this time another cmd window, the original do not close, otherwise you will not be able to access the server.

        Switch to the Redis directory to run the redis-cli.exe-h 127.0.0.1-p 6379 .

        Set the key-value pair set MyKey ABC

        Remove key value pair get MyKey


  • Install under Linux
      • : http://redis.io/download, download the latest version of the document. upload to Linux server $ tar xzf redis-2.8.17.tar.gz$ CD redis-2.8.17$ make done The redis-2.8.17 directory will appear under the compiled Redis service program Redis-server, as well as the client program for testing REDIS-CLI, two programs located in the installation directory SRC directory: Under the start Redis service. $ cd src $./redis-server note this way to start Redis is using the default configuration. You can also tell Redis to start with the following command using the specified configuration file through the startup parameters. $ cd src$./redis-server redis.conf redis.conf is a default configuration file. We can use our own configuration files as needed. Once the Redis service process is started, you can use the test client program REDIS-CLI to interact with the Redis service. For example: $ cd src$ ./redis-cliredis> set foo barokredis> get foo "bar"
3. Redis Configuration
      • The file name is redis.conf by modifying the Redis installation directory

1. Redis is not running as a daemon by default and can be modified by this configuration item, enabling the daemon with Yes

daemonize No

2. When Redis is running as a daemon, Redis writes the PID to the/var/run/redis.pid file by default and can be specified by pidfile

Pidfile/var/run/redis.pid

3. Specify the Redis listening port, the default port is 6379, the author in his own article blog post explains why 6379 as the default port, because 6379 Merz the corresponding number on the phone keypad, and Merz from Italy showgirl Alessia Merz name

Port 6379

4. The host address of the binding

bind 127.0.0.1

5. If the client closes the connection after a long period of inactivity, if it is specified as 0, the function is turned off

Timeout

6. Specify logging level, Redis supports four levels in total: Debug, verbose, notice, warning, default is verbose

loglevel Verbose

7. Logging mode, default to standard output, if Redis is configured to run as daemon, and this 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 use the Select <dbid> command to specify the database ID on the connection

Databases

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 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. Specify whether to compress the data when storing to the local database, the default is Yes,redis with LZF compression, if you want to save CPU time, you can turn off this option, but it will cause the database file to become huge

rdbcompression Yes

11. Specify the local database file name, the default value is Dump.rdb

dbfilename Dump.rdb

12. Specify the local database to hold the 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 is password protected, the Slav service connects the password of master

Masterauth <master-password>

15. Set up the Redis connection password, if the connection password is configured, the client will need to provide the password via auth <password> command when connecting to Redis, turn off by default

Requirepass foobared

16. Set the maximum number of client connections at the same time, the default is unlimited, Redis can open the 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

17. Specify the maximum Redis memory limit, Redis will load data into memory when it is started, Redis will try to clear expired or expiring key first, when this method processing, 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 and, if not turned on, may result in data loss over a period of time when power is lost. 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. Specify the update log file name, default to Appendonly.aof

appendfilename appendonly.aof

20. Specify the update log condition, a total of 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. Specify whether to enable the virtual memory mechanism, 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 multiple pages is automatically swapped out into memory by the disk (in a later article I will carefully analyze the Redis VM mechanism)

vm-enabled No

22. Virtual memory file path, default value is/tmp/redis.swap, cannot be shared by multiple Redis instances

Vm-swap-file/tmp/redis.swap

23. Store all data greater than vm-max-memory in virtual memory, regardless of the vm-max-memory settings, all index data is memory stored (REDIS index data is keys), that is, when the vm-max-memory is set to 0, In fact, all value is present on disk. The default value is 0

vm-max-memory 0

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

25. Set the number of pages in the swap file, since the page table (a bitmap that indicates that the page is idle or used) is in memory and consumes 1byte of memory per 8 pages on disk.

vm-pages 134217728

26. Set the number of threads to access swap files, preferably do not exceed the machine's core number, if set to 0, then all the swap file operation is serial, may cause a relatively long delay. The default value is 4

Vm-max-threads 4

27. Set when replying to the client, whether to merge the smaller package into one package send, the default is to turn on

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

Hash-max-zipmap-value 512

29. Specify whether to activate the reset hash, which is on by default (described later in the introduction of the Redis hashing algorithm)

activerehashing Yes

30. Specify other profiles that can use the same configuration file across multiple Redis instances on the same host, while each instance has its own specific configuration file

include/path/to/local.conf

4. Redis command
  • 1. Start Redis server: ./redis-server redis.conf
  • 2. Redis Client Login:$ redis-cli-h host-p port-a Password
      • Cases:
  • To see which database is currently in, the following table in front of the command indicates the current database, default to the first database, the subscript displays 0,
  • Select database:
  • Common commands:
      • 1) View key in the current library:, where pattern is an expression
        • Example: or
      • 2) New key: (The remaining hash, list, set, Zset Add command in the data type section)
      • 3) Get key:
      • 4) Delete key:, delete successful return 1, otherwise return 0
      • 5) Delete all keys in the library:
      • 6) randomly returns a key from the key in the current library:
      • 7) Serialization of key:
      • 8) Determine if key exists:, there is return 1, otherwise return 0
      • 9) Set the expiration time:, the expiration time to after the key will disappear
      • 10) Remove failure time:, removal success is 1, otherwise 0
      • 11) Check the remaining expiry time of key:
      • 12) Move key to a library:, return 1 successfully, otherwise return 0
      • 13) Change Key name:, successful return OK, otherwise return error content, in addition:
        • The new name and the old name are the same times wrong
        • Overwrite the original value when the new name exists
      • 14) Change Key name:, successful return 1, only if the new name does not exist, will succeed
      • 15) Return the type of key:
5. Redis Data Type
      • Redis supports five types of data: string (String), hash (hash), list, set (set), and Zset (sorted set: Ordered set).

    • 1) string (string)
    • A key to a value
    • can store any data, such as pictures, objects, binary, etc.
    • A key-value pair can store up to 512MB of data
    • Storing data
      • Format:
      • Cases:
    • Get Data
      • Format:
      • Cases:
    • Delete data
    • 2) hash (hash)
    • A set of key-value pairs
    • Each hash can store 232-1 key-value pairs (more than 4 billion)
    • Suitable for storing objects
    • To store data:
      • Format: OR
      • Cases:
    • Get Data:
      • Format: OR
      • Example: or
    • Delete data
    • 3) List (list)
    • A list of strings that can be added to the head or tail of an element
    • Allow duplicates
    • The list can store up to 232-1 elements (4294967295, each of which can store more than 4 billion).

    • Storing data
      • Format: OR
      • Example: or
    • Get Data
      • Format:
      • Example:
    • 4) Set (set)
    • Set is an unordered collection of type string and is implemented by a hash table.
    • duplicate is not allowed , data inserted for the second time is ignored
    • The maximum number of members in the collection is 232-1 (4294967295, each of which can store 40多亿个 members).

    • Storing data
      • Format:
      • Example: repeating will ignore
    • Get Data
      • Format:
      • Example:
    • 5) Zset (ordered set)
    • Set, ordered, duplicate not allowed
    • Storing data
      • Format: Zadd key numeric value, sorted by number size
      • Example:
    • Get Data
      • Format:
      • Example:
6.Redis Publishing and Subscriptions
    • Redis Publishing and subscription is a message communication pattern
      • Sender (pub) sends a message, the Subscriber (sub) receives the message
      • Redis clients can subscribe to any number of channels.

    • Example:
      • 1) Subscribers create channels first:
      • 2) Sender Pub message:
      • 3) Subscribers will automatically display messages from other client pub
7.Redis Transactions
    • Multiple commands can be executed in a single transaction, with success or failure at the same time
    • Grammar:
      • Start transaction:multi
      • Write command:set command, no final execution at this time
      • Execute command:exec, at which point the final execution
      • Cancel transaction:Discard
8.Redis Data backup and recovery
    • Save:
      • Save command, saved to the Dump.rdb file
      • Bgsave command, background execution
    • Recovery:
      • If you need to recover your data, simply copy the backup file (DUMP.RDB)
9.Redis Security
    • Password
      • To see if the password is turned on: identity is not turned on
      • Set Password:
        • 1) The first kind:
          • Edit redis.conf file, add config, test123 as password, restart still valid
        • 2) The second type:
          • Through command:, test is password, restart after failure
      • Login:, test is password
10. Using Redis in Java
    • 1) Download the Redis driver "Http://repo1.maven.org/maven2/redis/clients/jedis/2.1.0/jedis-2.1.0-sources.jar"
    • 2) In the project's Lib directory, and configured into the environment variable
    • 3) Coding, for example:

Redis Beginner 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.