Redis Use a detailed tutorial

Source: Internet
Author: User
Tags auth mkdir redis redis server
Redis Use a detailed tutorial

First, Redis basic part:

1, Redis introduction and installation faster than MySQL 10 times times more than

Redis applicable occasions ****************

1. Take the latest N data operations

2. List application, take top N operation

3. Applications requiring precise setting of expiration time

4. Counter Application

5.Uniq operation to get all data weight values for a certain period of time

6. Real-time system, anti-spam System 7. Pub/sub construction of real-time message system

7.pub/sub construction of real-time message system 8. Building a queue system

9. Caching

=============================================

Set operation 110,000 times per second, get operation 81,000 times per second, server configuration is as follows:

Linux 2.6, Xeon X3320 2.5Ghz.

The StackOverflow Web site uses Redis as a caching server.

The data is also written to the hard disk. So the data is safe (in addition to sudden power outages, the restart service will be written to the Dump.rdb file)

1. Installation:

Tar zxvf redis-2.6.9.tar.gz

CD redis-2.6.9

Make

CD src && make install

2. Mobile profile location (for ease of management)

cd/usr/local/

Mkdir-p/usr/local/redis/bin

Mkdir-p/usr/local/redis/etc

Mv/lamp/redis-2.6.9/redis.conf/usr/local/redis/etc

Cd/lamp/redis-2.6.9/src

MV mkreleasehdr.sh Redis-benchmark redis-check-aof redis-check-dump redis-cli redis-server/usr/local/redis/bin

3. Modify the configuration file

Vi/usr/local/redis/etc/redis.conf

First, the Daemonize no change to Yes[yes refers to the background run]

4. Start/start randomly:

Cd/usr/local/redis/bin

./redis-server/usr/local/redis/etc/redis.conf# starts the Redis and specifies the configuration file.

#vi/etc/rc.local #设置随机启动.

/usr/local/redis/bin/redis-server/usr/local/redis/etc/redis.conf

5. See if it starts successfully

Ps-ef | grep Redis

NETSTAT-TUNPL | grep 6379# to see if the port is occupied.

6. Enter the client/exit

Cd/usr/local/redis/bin

./redis-cli# entered

quit# exit

7. Close Redis

Pkill redis-server# off

./REDIS-CLI shutdown# Closed

Redis Safety ************************************

Security??? for Redis (By the following 4 ways)

1. Security with ACL controller.

2. By adding the following line of configuration to the redis.conf profile, you can bind the Redis to a single interface (but not only data that accepts the NIC).

Bind 127.0.0.1

3. Add a longer password to the Redis (no need to remember)

4. Enable the authentication feature in the redis.conf configuration.

5.SSL Agent

6. Disables the specified command.

Redis Configuration **********************************************

Daemonize If you need to run in the background, change the item to Yes

Pidfile configuration of multiple PID addresses defaults to/var/run/redis.pid

Bind bind IP, only accept requests from this IP after setting

Port listening ports, defaults to 6379

Timeout sets the timeout in seconds for client connections

LogLevel is divided into 4 levels, debug, verbose, notice, warning

LogFile Configuration log file address

Databases set the number of databases, the default database used is 0

Save sets the frequency of Redis database mirroring

Rdbcompression whether to compress when making a mirrored backup

Dbfilename the file name of the mirrored backup file

File placement path for DIR database mirroring backup

Slaveof set the database as a database from another database

Masterauth Password Authentication required for the primary database connection

Requirepass set the password to use when logging in

MaxClients Limit number of simultaneous customers

MaxMemory set the maximum memory that Redis can use

AppendOnly Open Append Only mode

The following can be understood:

Appendfsync sets the frequency of synchronization of appendonly.aof files

Vm-enabled whether virtual memory support is turned on

Vm-swap-file set the swap file path for virtual memory

Vm-max-memory sets the maximum physical memory size used by Redis

Vm-page-size set the page size of virtual memory

Vm-pages sets the total page number of the swap file

Vm-max-threads set the number of threads that VM IO uses simultaneously

GLUEOUTPUTBUF Store small output caches together

Hash-max-zipmap-entries set the critical value of the hash

Activerehashing Hash again

*******************************************************************

5 Types of data: strings, hashes, lists, collections, ordered collections.

Support: Push/pop, Add/remove, intersection, and set, difference set, sorting.

redis<=== Sync ====>mysql

The data is also written to the hard disk. So the data is safe (in addition to sudden power outages, the restart service will be written to the Dump.rdb file)

*******************************************************************

Select num# Choose Library, default in 0 libraries, a total of 16 libraries

Auth liweijie# The password required for the authorized user (the password is the password configured in redis.conf)

flushdb# empty the database.

String (String) type:

Set name lijie# The value of the key name is Lijie

Get name# Gets the value of name.

Keys * #查询所有的键.

Setnx name liweijie# returns 0 if the key already exists, and does not update to prevent overwriting.

Setex haircolor Red #设置键的值的有效期为10秒.

SetRange Email 6 lampbre.com# The value of the replacement key is changed from the 6th character to lampbre.com

Mset name1 li Dawei name2 Li Xiaowei # Sets the value of multiple keys.

Msetnxname1 John Name3 Dick # Determines whether the key exists, does not exist, or does not set the return 0

Mget name1 name2 name3# gets more than one key at a time.

Getset name1 tom# Reset the value of the key and return the old key value.

GetRange Email 6 18# Intercept the value of the email key, from the 第6-18位 between the characters.

INCR uid# 1 per time (if UID does not exist in key, set and start from 0, below)

Incrby UID 5# 5 per self

Incrby uid-5# every time since minus 5

DECR UID #每次自减1

Decrby uid 5# per self minus 5

Appendname1 @126.com# to Name1 value, add string @126.com

strlenname1# returns the length of the value of the key name1.

*************************************************************************

Hashes (hash) type:

Hset user:001 name liweijie# hash sets the name key value of the user user:001 to Liweijie

Hset user:001 Age 21# Same, add an age key value of 21

Hsetnx user:001 Age 22# Ibid, but the detection key exists. If no creation exists.

Hmset user:002 name Liweijie2 The age sex number sets the values of multiple keys at the same time.

Hget user:001 name# Hash Gets the value of the name key of the user user:001.

Hget user:001 age #同上.

Hmget user:001 name Age sex# Gets the value of multiple specified keys.

Hgetall user:001# Gets the value of all keys.

hincrbyuser:001 age-8# adds a given value to the specified key.

Hexists user:001 sex# detects whether the specified key value exists.

Hlen user:001# Returns the number of keys/fields for the specified hash.

Hdel user:001 sex# Deletes the specified field or key value for the specified (user:001) hash.

Hkeys user:003# returns Hashiri all fields or key values.

*********************************************************************

Lists (linked list) types and operations (Hoteis or queues):

Lpush mylist "World" #从头部插入字符串

Lpush mylist "Hello" #同上

Lrange mylist 0-1# gets from 0 to the last one as [1) "Hello" 2 "world"]

Rpush mylist "Jiejie" #在尾部插入

Linsert mylist before "Hello" "This is Linsert" #指定插入位置 (inserted before Hello).

LSet mylist 0 "what" #设置修改指定下标的值.

Lrem mylist 1 "Hello" #删除 (1) An element with a value of hello. (n<0 removed from the tail, n=0 all deleted)

LTrim mylist 1 2 #保留表中下标为1/2 element.

Lpop mylist# pops up the beginning element and returns.

Rpop mylist# ejects the tail element and returns.

Rpoplpush mylist mylist2 #从mylist尾部弹出插入到mylist2的头部.

Lindex mylist 0# Gets the element value labeled 0 for the table.

Llen mylist# Returns the number of table elements (equivalent to count ($arr)).

*********************************************************************

Sets (collection) type and operation (friend recommendation, blog, tag function):

Smembers myset# View all element values in the MySet collection.

Sadd myset "Hello" #向mysets集合中添加一个值hello

Srem myset "Hello" #删除myset集合中名称为hello的元素.

Spop MySet #随机弹出并返回mysets中的一个元素.

Sdiff Myset2 myset3# Returns the difference set (in Myset3) with Myset2 in Myset2.

Sdiffstore Myset4 Myset2 myset3# Returns the difference set between Myset2 and Myset3 in Myset4.

Sinter Myset2 myset3# Returns the intersection of Myset2 and Myset3.

Sinterstore Myset5 Myset2 myset3# returns the intersection of Myset2 and Myset3, and is deposited in MYSET5.

Sunion Myset2 myset3# Collection (to repeat)

Sunionstore Myset6 Myset2 myset3# of the collection, and deposited in the MYSET6.

Smove Myset2 Myset3 "three" #将myset2中的three移到myset3中去.

SCard myset2# Returns the number of elements.

Sismember Myset2 "One" #判断元素one是不是myset2集合的 (equivalent to Is_array ()).

Srandmember myset2# randomly returns an element in the Myset2 collection, but does not delete (equivalent to Array_rand ()).

*********************************************************************

Sorted sets (ordered collection) types and operations (sorted by scores):

Zadd Myzset 1 "one" #向顺序1的添加元素one

Zadd Myzset 2 "two" #同上.

Zadd Myzset 3 "two" #相当于更新顺序为2的值

Zrange Myzset 0-1 withscores# View all the elements and bring up the sort (default ascending order).

Zrem Myzset "Two" #删除two

Zincrby Myzset 2 "two" #将two的顺序值加上2

Zrank Myzset "Two" #返回集合中元素的索引下标值.

Zrevrank Myzset the two# element to reverse and return the new subscript value.

Zrevrange myzset 0-1 withscores# reverse order (equivalent to descending sort)

Zrangebyscore Myzset 1 withscores# Returns an element with an order of 1-10 (pagination).

Zcount Myzset The number of elements between 1 #返回顺序在1-10.

Zcard myzset# Returns the number of all the elements in the collection.

Zremrangebyrank Myzset 1 2# deletes the elements in the collection that are labeled 1 through 2.

Zremrangebyscore Myzset 1 10# deletes the elements in the collection in order 1 through 10.

Redis Common Commands

Key/value related commands.

Keys * #查询所有

Keys user* #查询指定的

Exists user:001# judge whether there is.

Del name# deletes the specified key.

Expire addr 10# Set expiration time

TTL addr# Query Expiration Time

Select 0 #选择数据库

Move Age # Moves the age to the 1 database.

Get Age #获取

Persist age# removes the expiration time of the age.

randomkey# returns a key at random

Rename name1 name2# Rename key

Type myset# returns the types of the keys.

Ping #测试redis连接是否存活.

echo lamp# output a lamp

Select 10# Choose the database.

quit/exit/crtl+c# Exit Client

dbsize# returns the number of keys in the library.

Server-related commands:

info# displays information about the Redis server.

Config get */loglevel #返回所有/specified configuration information.

flushdb# deletes all keys/tables in the current library.

flushall# Delete all keys/tables in all databases

Ii. Redis Advanced Section:

1, Redis Security:

1. Security with ACL controller.

2. Add a longer password to the Redis

# Requirepass Foobared

Requirepass Beijing

3. Enable the authentication feature in the redis.conf configuration.

Way one: Auth Beijing

Mode two:./redis-cli-a Beijing

4. By adding the following line of configuration to the redis.conf profile, you can bind the Redis to a single interface (but not only data that accepts the NIC).

Bind 127.0.0.1 (when a single machine can be configured, distributed or master-slave replication is best not to configure)

5.SSL Agent

6. Disables the specified command.

2, Redis master and slave copy:

Redis can only be configured from the server (slave):

IP and port of slaveof 211.122.11.11 6379 #指定master

Masterauth beijing# This is the master master's password

info# View the status of the primary/from server.

3, Redis transaction processing:

Redis affairs are not perfect.

4, Redis persistence mechanism:

1. Two ways: First, backup data to disk (snapshot) [Snapshotting (snapshot) is also the default way]

Second, the record Operation command [Append-only file (abbreviated AOF) way]

One, backup data to disk (snapshot) [Snapshotting (snapshot) is also the default method]

Save 900 1 #900秒内如果超过1个key被修改, a snapshot save is initiated

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

Save 60 10000

The way to record Operation command [Append-only file (abbreviated AOF)] (more secure persistence)

AppendOnly Yes #启用aof persistent way

# Appendfsync always//write to disk immediately, slowest, but guaranteed to be completely persistent

Appendfsync everysec//write disk once per second, making a good compromise in performance and persistence

# Appendfsync no//completely dependent on OS, best performance, no guarantee of persistence

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.