Redis usage tutorial (go)

Source: Internet
Author: User

I. redis basics:

1. redis introduction and installation are more than 10 times faster than MySQL

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

1. Operations for retrieving the latest n data

2. Ranking application, Top N operations

3. Applications that need to precisely set the expiration time

4. Counter application

5. uniq operation to obtain the values of all data records in a certain period of time

6. Real-Time System. The Anti-Spam system 7.pub/ sub constructs a real-time message system.

7. Build a Real-Time Message System Using pub/sub 8. Build a queue system

9. Cache

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

The set operation is performed 110000 times per second, and the get operation is performed 81000 times per second. The server configuration is as follows:

Linux 2.6, Xeon x3320 2.5 GHz.

The stackoverflow website uses redis as the cache server.

Data is also written to the hard disk. Therefore, data is safe (except for 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. Move the configuration file 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

 

1. Change No in daemonize no to Yes [Yes indicates running in the background]

4. Start/random start:

CD/usr/local/redis/bin

./Redis-server/usr/local/redis/etc/redis. conf # Start redis and specify the configuration file.

# Vi/etc/rc. Local # Set random start.

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

5. Check whether the startup is successful.

PS-Ef | grep redis

Netstat-tunpl | grep 6379 # Check whether the port is occupied.

6. Enter the client/exit

CD/usr/local/redis/bin

./Redis-cli # Enter

Quit # exit

7. Disable redis

Pkill redis-server # disable

./Redis-cli shutdown # disable

* ************************************ Redis Security ** **********************************

 

Redis Security ??? (In the following four ways)

1. Use ACL controller for security.

2. Add the following configuration in the redis. conf configuration file to bind redis to a single interface (but not only accept the data of this Nic ).

Bind 127.0.0.1

3. Add a long password to redis (no need to remember)

4. enable authentication in redis. conf.

5. SSL Proxy

6. Disable the specified command.

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

To run daemonize in the background, change the value to yes.

The IP address of multiple PIDs configured in pidfile is/var/run/redis. PID by default.

Bind to an IP address. After setting, only requests from this IP address are accepted.

Port listening port. The default value is 6379.

Timeout sets the timeout time for client connection, in seconds

Loglevel is divided into four levels: Debug, verbose, notice, warning

Logfile configuration log file address

Databases: sets the number of databases. The default value is 0.

Save sets the frequency of redis database Mirroring

Whether to compress rdbcompression during image backup

Name of the backup file of the dbfilename Image

Directory of the Dir database image backup file

Slaveof sets the database as a slave database of another database

Password verification required for masterauth primary database connection

Requirepass: Set the password used for logon.

Maxclients limits the number of customers connected at the same time

Maxmemory sets the maximum memory available for redis

Appendonly enabled append only mode

See the following:

Appendfsync sets the synchronization frequency for appendonly. aof files

VM-enabled: whether to enable virtual memory support

VM-Swap-file: Set the swap file path of the virtual memory

VM-max-memory: sets the maximum physical memory size used by redis.

VM-page-size: sets the page size of the virtual memory.

VM-pages: sets the total number of pages for file exchanges.

VM-max-threads sets the number of threads simultaneously used by VM Io

Glueoutputbuf stores small output caches together

Hash-max-zipmap-entries sets the hash Critical Value

Activerehashing re-Hash

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

Five data types: String, hash, linked list, set, and ordered set.

Supported: Push/pop, Add/Remove, intersection, union, difference set, and sorting.

Redis <=== synchronization ==> MySQL

Data is also written to the hard disk. Therefore, data is safe (except for sudden power outages, the Restart service will be written to the dump. RDB file)

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

Select num # select the database. The default value is 0. There are 16 databases in total.

Auth liweijie # Password required to authorize the user (the password is the password configured in redis. conf)

Flushdb # Clear the database.

String type:

Set Name Lijie # Set the key name to Lijie

Get name # Get the value of name.

Keys * # query all keys.

Setnx name liweijie # If the key already exists, 0 is returned without updating to prevent overwriting.

Setex haircolor 10 Red # Set the key value to be valid for 10 seconds.

Setrange email 6 lampbre.com # Replace the key value from 6th characters to lampbre.com

Mset name1 Li Dawei name2 Li Xiaowei # Set the values of multiple keys.

Msetnxname1 Zhang San name3 Li Si # judge whether the key exists. If it does not exist, set it. Otherwise, 0 is returned if it is not set.

Mget name1 name2 name3 # obtain the values of multiple keys at a time.

GetSet name1 Tom # reset the key value and return the old key value.

Getrange email 6 18 # truncate the email key value, which is a string between 6 and 18 characters.

Incr uid # increase by 1 each time (if the uid in the key does not exist, set and start from 0, the same below)

Incrby uid 5 # auto-increment 5 each time

Incrby UID-5 # auto-minus 5 each time

Decr uid # auto-minus 1 each time

Decrby uid 5 # auto-minus 5 each time

Appendname1 @ 126.com# Add a string @ 126.com to the name1 Value

Strlenname1 # length of the value of the Return key name1.

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

Hashes (hash) type:

Hset User: 001 name liweijie # hash setting the name key value of user User: 001 is liweijie

Hset User: 001 age 21 # Similarly, add an age key value of 21

Hsetnx User: 001 age 22 # Same as above, but check whether the key exists. If creation does not exist.

Hmset User: 002 name liweijie2 age 26 sex 1 # Set the values of multiple keys at the same time.

Hget User: 001 name # hash to obtain the name key value of user User: 001.

Hget User: 001 age # Same as above.

Hmet User: 001 name age sex # obtain the values of multiple specified keys.

Hgetall User: 001 # obtain the values of all keys.

Hincrbyuser: 001 age-8 # Add the given value to the specified key.

Hexists User: 001 sex # Check whether the specified key value exists.

Hlen User: 001 # Return the number of keys/fields in the specified hash.

Hdel User: 001 sex # Delete the specified field or key value of the specified (User: 001) hash.

Hkeys User: 003 # return all fields or key values in the hash.

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

Lists (linked list) type and operation (queue or Queue ):

Lpush mylist "world" # insert a string from the header

Lpush mylist "hello" # Same as above

Lrange mylist 0-1 # obtain from 0 to the last one, for example, [1) "Hello" 2) "world"]

Rpush mylist "jiejie" # Insert at the end

Linsert mylist before "hello" "This is linsert" # specify the Insert Location (before Hello ).

Lset mylist 0 "what" # Set and modify the value of the specified subobject.

Lrem mylist 1 "hello" # Delete (1) an element with a value of hello. (N <0 is deleted from the end, n = 0 is all deleted)

Ltrim mylist 1 2 # Keep the element whose subscript is 1/2.

Lpop mylist # The start element is displayed and returned.

Rpop mylist # pop up the tail element and return it.

Rpoplpush mylist mylist2 # the header inserted to mylist2 is displayed at the end of mylist.

Lindex mylist 0 # obtain the element value whose subscript is 0.

Llen mylist # returns the number of table elements (equivalent to count ($ ARR )).

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

Sets (SET) Types and operations (friend recommendation, blog, and tag functions ):

Smembers myset # view all element values in the myset set.

Sadd myset "hello" # Add a value hello to the mysets set

Srem myset "hello" # delete an element named hello in the myset set.

Spop myset # randomly pops up and returns an element in mysets.

Sdiff myset2 myset3 # Return the difference set between myset2 and myset3 (whichever is myset2 ).

Sdiffstore myset4 myset2 myset3 # Return the difference set between myset2 and myset3, and store it in myset4.

Sinter myset2 myset3 # returns the intersection of myset2 and myset3.

Sinterstore myset5 myset2 myset3 # returns the intersection of myset2 and myset3 and stores it in myset5.

Sunion myset2 myset3 # Union (deduplication)

Sunionstore myset6 myset2 myset3 # calculates the Union and stores it in myset6.

Smove myset2 myset3 "three" # Move three in myset2 to myset3.

Scard myset2 # returns the number of elements.

Sismember myset2 "one" # determine whether the element one is a set of myset2 (equivalent to is_array ()).

Srandmember myset2 # returns an element in the myset2 set at random, but does not delete it (equivalent to array_rand ()).

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

Sorted sets (sorted sets) Types and operations (sorted by scores ):

Zadd myzset 1 "one" # Add one element to sequence 1

Zadd myzset 2 "two" # Same as above.

Zadd myzset 3 "two" # equivalent to the value in the update Order of 2

Zrange myzset 0-1 withscores # view all elements and sort them in ascending order by default ).

Zrem myzset "two" # Delete two

Zincrby myzset 2 "two" # add the two Sequence Value to 2

Zrank myzset "two" # Return the index value of the element in the set.

Zrevrank myzset two # The element is reversed and a new value is returned.

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

Zrangebyscore myzset 1 10 withscores # returns elements in the order of 1-10 (paging ).

Zcount myzset 1 10 # returns the number of elements in the order between 1 and 10.

Zcard myzset # returns the number of all elements in the set.

Zremrangebyrank myzset 1 2 # Delete the Elements marked as 1 to 2 in the set.

Zremrangebyscore myzset 1 10 # Delete elements from the set in the order of 1 to 10.

Common redis commands

Key/value-related commands.

Keys * # query all

Keys user * # query the specified

Exists User: 001 # determine whether the user exists.

Del name # Delete the specified key.

Expire ADDR 10 # Set the expiration time

Ttl addr # query the expiration time

Select 0 # select database

Move age 1 # Move age to database 1.

Get age # Get

Persist age # The expiration time of the age to be removed.

Randomkey # returns a random key.

Rename name1 name2 # rename the key

Type myset # type of the Return key.

Ping # test whether the redis connection is alive.

Echo lamp # output a lamp

Select 10 # select a database.

Quit/exit/crtl + C # exit the client

Dbsize # Return the number of keys in the database.

Server commands:

Info # displays information about the redis server.

Config get */loglevel # returns all/specified configuration information.

Flushdb # delete all keys/tables in the current database.

Flushall # delete all keys/tables in all databases

 

Ii. redis advanced section:

1. redis security:

1. Use ACL controller for security.

2. Add a long password to redis

# Requirepass foobared

Requirepass Beijing

3. enable authentication in redis. conf.

Method 1: AUTH Beijing

Method 2:./redis-cli-a Beijing

4. Add the following configuration in the redis. conf configuration file to bind redis to a single interface (but not only accept the data of this Nic ).

Bind 127.0.0.1)

5. SSL Proxy

6. Disable the specified command.

2. redis master-slave replication:

Redis only needs to be configured on the slave server (slave:

Slaveof 211.122.11.11 6379 # specify the master's IP address and port

Masterauth Beijing # This is the password of the master host

Info # view the status of the Master/Slave server.

3. redis transaction processing:

Redis transactions are not perfect.

4. redis persistence mechanism:

1. Two Methods: 1. Back up data to a disk (snapshot) [snapshotting (snapshot) is also the default method]

Ii. Record the Operation Command [append-only file (AOF) method]

I. Back up data to a disk (snapshot) [snapshotting (snapshot) is also the default mode]

Save 900 1 # if more than one key is modified within 900 seconds, the snapshot is saved.

Save 300 10 #300 seconds if more than 10 keys are modified, the snapshot is saved.

Save 60 10000

Ii. Record the Operation Command [append-only file (AOF) method] (more secure and persistent)

Appendonly yes # enable aof persistence

# Appendfsync always // writes data to the disk immediately after receiving the write command, which is the slowest, but ensures full persistence.

Appendfsync everysec // writes data to the disk every second, which compromises performance and persistence.

# Appendfsync no // fully dependent on OS, which has the best performance and is not guaranteed for persistence

Redis usage tutorial (go)

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.