Redis Basic Operations

Source: Internet
Author: User
Tags configuration settings redis cluster redis server

Introduction to Redis System Management experiment

The previous section of the experiment described the basic data types of Redis, and this experiment continues to explain Redis-related commands and management operations.

In Redis, the command case is not sensitive.

First, suitable for all types of common commands

Start the Redis service and the REDIS-CLI command interface to continue the follow-up experiment:

$ sudo service redis-server start$ redis-cli
(1) EXISTS and DEL

EXISTS key determines whether a key exists; returns 1; otherwise returns 0; DEL key Deletes a key, or a series of Key;del Key1 Key2 Key3 key4. Successful return 1, Failure returns 0 (key value does not exist).

> set mykey hello> exists mykey> del mykey> exists mykey

Operation:

(2) TYPE and KEYS

Type key: Returns the data type of a key element (none: Not present, string: Character, List,set,zset,hash), key does not exist return null. Keys Key-pattern: Returns a list of matching keys (keys foo*: Keys to find the beginning of foo)

> set mykey x> type mykey>keys my*> del mykey>keys my*> type mykey

Operation:

(3) Randomkey and CLEAR

Randomkey: Randomly obtains a key that already exists and returns an empty string if the current database is empty

> randomkey

Operation:

Clear: Clears the interface.

> clear
(4) RENAME and Renamenx

RENAME oldname newname: Changed key name, new key if present will be overwritten Renamenx oldname newname: Change key name, if name exists then change failed

The author Randomkey The result for mylist, renaming this key value to NewList.

> randomkey> rename mylist newlist> exists mylist> exists newlist

Operation:

(5) Dbsize

Dbsize: Returns the total number of keys for the current database

> dbsize

Operation:

Second, Redis time-related commands (1) Limit key survival time

This is also a command that ignores data types and is useful for temporary storage. Avoid a large number of Del operations.

EXPIRE: Set the expiration time of a key (in seconds), (EXPIRE Bruce 1000: Set Bruce this key1000 seconds after the system is automatically deleted) Note: If the value has been changed since it has not expired, then that value will be cleared.

set key some-value> expire key 10> get key (马上执行此命令)> get key (10s后执行此命令)

Operation:

The result shows that after executing the expire command, the get is immediately displayed and the key exists. After 10 seconds, the key has been automatically deleted.

(2) Query key remaining time to live

The time-limited operation can be implemented in the set command again, and the TTL command is used to query the remaining lifetime of the key. TTL: How long does it look for a key to expire, return seconds

> set key 100 ex 30> ttl key> ttl key

Operation:

(3) Clear key

FLUSHDB: Empties all keys in the current database

Flushall: Clears all keys from all databases

>flushdb>flushall
Iii. Redis Settings Related commands

Redis has its own configuration file that can be viewed or changed through the Client-command window. The relevant commands are described below:

(1) config GET and config SET

Config GET: Used to read configuration parameters for running Redis server. Config SET: Used to change configuration parameters for running Redis server. AUTH: An example of a redis password under the authentication password:

> config get requirepass (查看密码)> config set requirepass test123 (设置密码为test123 )> config get requirepass  (报错,没有认证)> auth test123> config get requirepass

Operation:

The result shows that at the beginning of the Reids did not set the password, the password query results are empty. Then set the password to test123, again query error. After auth command authentication, can be queried normally.

You can change the password by modifying the Redis configuration file redis.conf.

The CONFIG get command is displayed with the key-value of the list, such as the maximum entry for the query data type:

get *max-*-entries*

Operation:

(2) Reset report

CONFIG Resetstat: Resets the data statistics report, usually returning a value of ' OK '.

> CONFIG RESETSTAT

Operation:

Iv. Inquiry Information

info [section]: Query Redis related information. The info command can query almost all redis information, with the following command options:

    1. General Information for Server:redis server
    2. Connection options for Clients:client
    3. Memory: Storage usage Related information
    4. Persistence:rdb and AOF related information
    5. Stats: General Statistics
    6. Replication:master/slave Request Information
    7. CPU:CPU Occupancy Information Statistics
    8. Cluster:redis Cluster Information
    9. Keyspace: Database Information statistics
    10. All: Return all information
    11. Default: Returns general settings information

If the command argument is empty, the info command returns all information.

> info keyspace> info server

Operation:

Introduction to Redis's advanced application experiments

Before learning the basics and basic commands for Redis, go on to the advanced applications of Redis, including: Security settings, master-slave replication, transaction processing, persistence mechanism, virtual memory usage.

First, security

Set the password to be specified on the client connection (because the Redis speed is quite fast, a second can be 150K of password attempts, so you need to set a password strong passwords).

There are two ways to set a password:

(1) The Requirepass parameter of the config SET command is used, the format is config set requirepass "password". (2) Set the Requirepass property in configuration redis.conf, followed by the password.

There are two ways to enter authentication:

(1) You can redis-cli-a password when you log in

(2) Use auth after login password

(1) Set password

The first method of password setting has been mentioned in the previous experiment (in the example of Config set command), here we look at the second way to set the password.

You first need to go to the Redis installation directory and then modify the configuration file redis.conf. Based on the results of the grep command, use the VI editor to modify "# Requirepass foobared" to "Requirepass test123" and then save the exit.

$ grep -n requirepass /etc/redis/redis.conf$ sudo vim /etc/redis/redis.conf

To edit the results of redis.conf:

(2) Restart Redis-server and REDIS-CLI

Restart Redis server.

$ sudo service redis-server restart

Enter into the REDIS-CLI interface for verification

$ redis-cli> info> auth test123> info> exit

Operation:

The result indicates that the first info command failed, and the info command returned normally after Auth authentication. Finally exit Redis-cli.

Another type of password authentication method:

-a test123> info

Operation:

Second, master-slave replication

Due to the environmental reasons, here the author roughly explain the master-slave replication workflow, do not do experiments.

The master-slave replication configuration and use of Redis is relatively straightforward, and master-slave replication allows multiple slave servers to have the same database copy as master server.

The server is read-only and cannot be written.

Redis master-slave replication features:

1, master can have multiple slave.

2, more than one slave can connect to the same master, you can also connect to other slave. (When Master is down, the connected slave turns to master)

3, master-slave replication does not block master, and then synchronize the data, the primary can continue to process client requests.

4, improve the scalability of the system.

Redis master-slave replication process:

1, slave and master to establish a connection, send Sync Sync command.

2. Master starts a background process, saves the database snapshot to a file, and the master master process starts collecting new write commands and caches.

3. After the background is finished saving, send this file to slave.

4. Slave save this file to disk.

Third, transaction processing

The transaction processing of Redis is relatively straightforward. Only the commands in the client-initiated transaction can be guaranteed to execute consecutively, and no other client commands are inserted, and when a client issues the multi command in the connection, the connection enters the context of a transaction, and the subsequent command of the connection is not executed but is stored in a queue. When the EXEC command is executed, Redis executes all the commands in the queue sequentially. If an error occurs in the execution, the correct execution is not rolled back, unlike the relational database transaction.

> multi> set name a> set name b> exec> get name

Operation:

Iv. persistence mechanism

Redis is an in-memory database that supports persistence, and Redis needs to frequently synchronize the in-memory data to disk to ensure persistence.

Redis supports two persistence modes:

1, snapshotting (snapshot), the data stored in the file, the default way.

is to write a snapshot of the in-memory data into a binary file, the default file Dump.rdb, which can be automatically persisted by configuration settings. Redis can be configured to automatically save snapshots in n seconds if more than M key is modified.

Save 1 #900秒内如果超过1个key被修改 to initiate a snapshot save

Save #300秒内如果超过10个key被修改, the snapshot is saved

2, Append-only file (abbreviated as AOF), the read and write operations are stored in the file.

Because the snapshot is done at a certain interval, if Redis is accidentally down, all modifications after the last snapshot are lost.

AOF is more persistent than snapshot, because Redis writes each received write command through the Write function to a file, and when Redis starts, it re-establishes the contents of the entire database in memory by re-executing the Write command saved in the file.

Because the OS caches write modifications in the kernel, it may not be written to disk immediately, so the persistence of aof mode may also result in the loss of some data. You can tell Redis through the configuration file that we want to force the OS to write to disk through the Fsync function.

Configurable parameters in the configuration file:

appendonly   yes     //启用aof持久化方式#appendfsync  always //收到写命令就立即写入磁盘,最慢,但是保证了数据的完整持久化appendfsync   everysec  //每秒中写入磁盘一次,在性能和持久化方面做了很好的折中#appendfsync no //完全依赖os,性能最好,持久化没有保证

In the REDIS-CLI command, the Save command is to write data to disk.

help save>save

Operation:

V. Use of virtual memory

Virtual memory management was canceled at 2.6 and above, and in the installation experiment, 2.8.9 Redis, no configuration options for the virtual memory management feature are available in the configuration files in the experiment. This is the only explanation

Redis's virtual memory is temporarily swapping infrequently accessed data from memory to disk, freeing up memory space for other access data, especially for memory databases such as Redis, where memory is not always sufficient. In addition to separating multiple Redis servers, the way to increase the capacity of a database is to use virtual memory to exchange infrequently accessed data to disk.

By configuring the VM-related redis.config configuration:

vm-enable  yes                   #开启vm功能vm-swap-file    /tmp/redis.swap  #交换出来的value保存的文件路径vm-max-memory    10000000        #redis使用的最大内存上线 vm-page-size 32 #每个页面的大小32字节vm-pages 123217729 #最多使用多小个页面vm-max-threads 4 #用于执行value对象换入的工作线程数量

Redis Basic Operations

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.