[Redis3] learning and practice of Redis database-Common commands and advanced applications of Redis

Source: Internet
Author: User
Keys * keysmy * # returns 1127.0.0.1: 6379 existsname (integer) 1 # returns 0127.0.0.1: 6379 existsyou (integer) 0127.0.0.1: 6379 delname (integer) 1127.0.0.1: 6379 delyou (integer) 0127.0.0.1: 6379expirename10 (integer) 1127.0.0.1

Keys * keys my * # returns 1 6379 exists name (integer) 1 # returns 0 6379 exists you (integer) 0 6379 del name (integer) 1 6379 del you (integer) 0 6379 expire name 10 (integer) 1

  • Keys *
  • Keys my *
  • # Returns 1 If yes
  • 6379> exists name
  • (Integer) 1
  • #0 is returned if no data exists.
  • 6379> exists you
  • (Integer) 0
  • 6379> del name
  • (Integer) 1
  • Wagner. 0.0.1: 6379> del you
  • (Integer) 0
  • 6379> expire name 10
  • (Integer) 1
  • 6379> get name
  • "Inter"
  • 6379> get name
  • "Inter"
  • 6379> get name
  • "Inter"
  • 6379> get name
  • (Nil)
  • 6379> select 0
  • OK
  • 6379> set sex boy
  • OK
  • 6379> get sex
  • "Boy"
  • 6379> move sex 1
  • (Integer) 1
  • 6379> get sex
  • (Nil)
  • 6379> select 1
  • OK
  • 6379 [1]> get sex
  • "Boy"
  • 6379> expire name 300
  • (Integer) 1
  • 6379> ttl name
  • (Integer) 296
  • 6379> persist name
  • (Integer) 1
  • 6379> ttl name
  • (Integer)-1
  • 6379> randomkey
  • "Name"
  • 6379> set name hello
  • OK
  • 6379> rename name you
  • OK
  • Wagner. 0.0.1: 6379> get you
  • "Hello"
  • 6379> type you
  • String
  • # Pong is returned after ping, indicating that the network connection is successful.
  • # Return cocould not connect to Redis at 6379: Connection refused, indicating network Connection failed
  • 6379> ping
  • PONG
  • 6379> echo you
  • "You"
  • 6379> select 10
  • OK
  • Wagner. 0.0.1: 6379 [10]>
  • 6379> quit
  • Djy @ ubuntu :~ /Toolkit/redis/src $
  • 6379> dbsize
  • (Integer) 2
  • Wagner. 0.0.1: 6379>
  • 6379> info
  • # Server
  • Redis_version: 2.8.13
  • Redis_git_sha1: 00000000
  • Redis_git_dirty: 0
  • Redis_build_id: b762f6d0aafec306
  • Redis_mode: standalone
  • OS: Linux 3.8.0-19-generic x86_64
  • Arch_bits: 64
  • Multiplexing_api: epoll
  • Gcc_version: 4.7.3
  • Process_id: 28321
  • Run_id: 8ebdbe81c7153e1e6bd0979d365ca9c8480f8c9f
  • Tcp_port: 6379
  • Uptime_in_seconds: 2155
  • Uptime_in_days: 0
  • Hz: 10
  • Lru_clock: 15851433
  • Config_file:/home/djy/toolkit/redis. conf
  • ...
  • ...
  • 6379> config get save
  • 1) "save"
  • 2) "900 1 300 10 60 10000"
  • Wagner. 0.0.1: 6379>
  • 6379> keys *
  • 1) "name"
  • 2) "you"
  • 3) "sex"
  • 4) "new_name"
  • 6379> flushdb
  • OK
  • 6379> keys *
  • (Empty list or set)
  • # Go To The redis folder and modify the redis. conf file.
  • # Requirepass foobared
  • Requirepass djy
  • # Then go to the client and perform authorization when operating the redis database.
  • Auth djy
  • # Or enter
  • Redis-cli-a djy
Redis database learning and practice-Common commands and advanced applications of Redis 1: Common commands of Redis provide a variety of commands to operate databases and various database types, these commands can be used on Linux terminals. 1: Key-value related commands. (1) keys
Returns all keys that meet the given pattern;
(2) exists
Check whether a key exists;
(3) del
Delete a key;
(4) expire
Set the expiration time of a key;
(5) move
Transfers keys in the current database to other databases;
(6) persist
Remove the expiration time of a given key;
(7) randomkey
Returns a random key of the key space;
(8) rename
Rename key;
(9) type
Type of the returned value. 2: Server-related commands. (1) ping
Test whether the connection is alive;
(2) echo
Print the content on the command line;
(3) select
Select a database. The Redis database number ranges from 0 ~ 15. We can select any database for data access;
(4) quit
Exit the connection;
(5) dbsize
(6) info
Redis server information;
(7) configget
Real-time dump of received requests and return related configuration parameters;
(8) flushdb
Delete all keys in the selected database;
(9) flushall
Delete all keys in all databases; 2: Advanced Redis utility features (1) security setting the password required before the client connection is made any other designation.
Warning because redis is quite fast, an external user can try a K password in one second on a better server, this means you need to specify a very powerful password to prevent brute-force cracking.
(2) master-slave Replication
Redis master-slave replication is easy to configure and use. Master-slave replication allows multiple slave servers to have the same database copies as the master server.


The Master can have multiple slave instances;

Multiple Server Load balancer instances can connect to the same master and other Server Load balancer instances;

Master-slave replication does not block the master node. During data synchronization, the master node can continue to process client requests;

Improve system scalability.

Master-slave replication process:

Slave establishes a connection with the master and sends the sync command

The Master starts a background process, saves database snapshots to files, and the master processes start to collect new write commands and cache them.

After saving the file in the background, send the file to slave.

Slave saves this file to the hard disk

Configure Master/Slave servers

Add the following configuration to the slave configuration file (redis. conf:

Slaveof 6379 # specify the master's ip address and port

Masterauth lamp # This is the host Password

# After setting, you can run the info command to view the master/slave information (role: master/slave)

(3) Transaction Processing

Redis's support for transactions is still relatively simple. Redis can only ensure that the commands in the transaction initiated by one client can be executed continuously without inserting commands from other clients. When a client sends a multi command in a connection, the connection enters a transaction context, and subsequent commands of the connection are not executed immediately, but placed in a queue first, when the exec command is executed, redis will execute all the commands in the queue sequentially.

Simple transaction processing: 6379> get age

"30" 6379> multi

OK 6379> set age 10

QUEUED 6379> set age 20

QUEUED 6379> exec

1) OK

2) OK 6379> get age


Cancel a transaction: 6379> get age

"20" 6379> multi

OK 6379> set age 30

QUEUED 6379> set age 50

QUEUED 6379> discard

OK 6379> get age


Redis transaction defects. Generally, every transaction in the transaction must be successfully executed, and all operations in the transaction will take effect. However, the defect of the Redis transaction is that when one of the operations in the transaction fails, the other operation still succeeds. In this way, when a transaction is wrong, there is no rollback mechanism, which is something to be improved.

Optimistic lock: complex transaction control

Most of them are implemented based on the data version record mechanism. Add a version for the data. In the database table-based version solution, when you add a "version" field to the database table to read the data, read the version number together, and Add 1 to the version number when updating later. In this case, the version number of the submitted data is compared with the current version number of the corresponding record of the database table. If the submitted data version number is greater than the current version number of the database, it is updated; otherwise, it is deemed as expired data.

Redis optimistic lock instance:

Suppose there is an age key. We open two sessions to assign values to the age. Let's take a look at the result.

# Step 1 session1 6379> get age

"20" 6379> watch age

OK 6379> multi


# Step 2 session2 6379> set age 30

OK 6379> get age


# Step 3 session1 6379> set age 20

QUEUED 6379> exec

(Nil) 6379> get age


The Watch command will see the given key. When exec, if the monitored key has changed since the watch call, the entire transaction will fail. You can also call watch to monitor multiple keys multiple times. In this way, you can apply an optimistic lock to the specified key. Note that the key of watch is valid for the entire connection, and the transaction is the same. If the connection is disconnected, monitoring and transactions are cleared automatically. Of course, the exec, discard, and unwatch commands will clear all monitoring in the connection.

(4) Persistence Mechanism

Redis is a persistent memory database. That is to say, redis often needs to synchronize data in the memory to the hard disk to ensure persistence.

Redis supports two persistence Methods: snapshotting (snapshot) is also the default method; Append-only file (aof) method.

(5) Publish and subscribe to messages

Publishing and subscription (pub/sub) is a message communication mode. The main purpose is to contact the coupling between message publishers and message subscribers. Redis is a pub/sub server, message routing is enabled between the subscriber and the publisher. The subscribe and psubscribe commands subscribe to the redis server to subscribe to the Message type that you are interested in. redis calls the information type channel ). When the publisher sends a specific type of information to the redis server through the publish command, all clients that subscribe to this type of information will receive this message.

(6) use of virtual memory

The virtual memory of Redis is not the same as the virtual memory of the operating system, but the idea and purpose are the same. These are all temporarily switching infrequently accessed data from memory to disk, so as to free up valuable memory space for other data to be accessed. Especially for memory databases such as redis, the memory is always insufficient. Data can be divided into multiple redisservers. In addition, the way to increase the database capacity is to use virtual memory to swap infrequently accessed data to the disk.

Vm-enabled yes # enable the vm Function

Vm-swap-file/tmp/redis. swap # path of the file for storing the exchanged values

Vm-max-memory 1000000 # maximum memory used by redis

Vm-page-size 32 # size of each page 32 bytes

Vm-pages 13417728 # maximum number of pages used

Vm-max-threads4 # Number of worker threads used to execute value object swap into the affected area

Note: The Redis series blogs are all made up of the notes and practices of the brother-in-law Redis learning video.

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.