Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

NoSQL-- redis installation master-slave configuration details common commands

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Redis is also the key-value storage system, the official site http://redis.io, but compared to memcache, it has the following advantages:

1. Support more value types (string, hash, lists, sets, sorted sets, etc.)

2. Data persistence is supported to prevent the need for re-storage after service restart.

Redis has two file formats: full data (RDB=redis database) and incremental request (aof=append only file).

The former is to write the data in memory to disk, so that the file can be loaded directly the next time the file is read.

The latter records the instructions executed by redis and executes it again on restart, similar to binlog storage.

The two methods can be used at the same time. If you restart at this time, AOF will be preferred for recovery.

Without either, redis becomes an in-memory database, such as memcache

Redis storage: memory storage, disk storage, log file three parts

Installation

First, wget downloads the source code package, https://code.google.com/archive/p/redis/downloads.

For example: wget https://codeload.github.com/antirez/redis/tar.gz/2.8.21

Decompress: tar zxvf 2.8.21 & & cd redis-2.8.21

Install some tools before yum install-y gcc epel-release; yum install-y jemalloc-devel / / make

Compile: make / / because makefile has been written, no need to compile, just make directly

Error: if there is an error in make, you can't find something. # I used centos7, but there was no error

Solution: cd deps & & make hiredis lua jemalloc linenoise & & cd.. / & & make

Installation: make PREFIX=/usr/local/redis install / / for ease of management, the following directory is specified

Create: mkdir / usr/local/redis/etc & & / usr/local/redis/var

Wget http://www.apelearn.com/study_v2/.redis_init-O / etc/init.d/redis / / teacher's startup script

User: useradd-s / sbin/nologin redis

Permission: chmod 777 / usr/local/redis/var & & chmod 755 / etc/init.d/redis

Self-boot: chkconfig-- add redis & & chkconfig redis on & & service redis start

Data type

String: it can be understood as the same type as memcache, and one key corresponds to one value. It has more functions than mem, and is the simplest type.

Set: collections, which are often found in intercourse and difference sets, such as common followers, common fans in Weibo, qq friend tags and other functions.

Lists: linked list structure, function push, pop, access range, etc., easy to achieve ranking and other functions

Hash: in mem, structured information is packaged into hashmap, serialized and stored in one character, such as age, sex, etc.

Sorted set: ordered set with more weight parameter score than set, so that it can be arranged by score and inserted in order.

Disposition of documents

# General configuration daemonize no # by default, redis does not run in daemon format. Pidfile / path/to/redis.pid # when running as daemon, point to the generated pid file bind 192.168.1.2 10.8.4.2 # to specify the bound ip, which can have multiple Space separated port 6379 # specify listening port unixsocket / tmp/redis.sock # can also monitor socketunixsocketperm 755 # when listening to sockets, you can specify the permission of 755timeout 0 # the client does not send a request to the server within the time limit, and the server closes the connection with this value. 0 means never turn off the tcp-keepalive 0 # TCP connection activation policy, and check whether the client has hung up. 0 means loglevel notice # log level is not enabled. There are four types of debug, verbose, notice, warninglogfile "" # define log path, "means default syslog-ident redis # controls printing to syslog through syslog-enabled. This value specifies the log flag in syslog, syslog-facility local0 #, specifies the device of syslog. It can be USER or local0-local7databases 16 # set the total number of databases # Snapshot configuration save 9001 # means that every 15 minutes and at least one key change is triggered, save 30010 # means every 5 minutes and at least 10 key changes Triggering a persistent save 60 10000 # means at least 10000 key changes every 60 seconds, triggering a persistent save "" # so that you can disable rdb persistent stop-writes-on-bgsave-error yes # after a write failure to disk Immediately stop writing operation rdbcompression yes # whether to compress rdbchecksum yes # whether to perform data verification dbfilename dump.rdb # define the name of snapshot file dir / usr/local/redis # define snapshot file storage strength # Security related configuration requirepass teng # set redis-server password # # Test: redis-cli & & get key1 After restart: redis-cli-a teng & & get key1 will output rename-command CONFIG teng.config # # rename the CONFIG command to teng.config Avoid misoperation, but if AOF persistence is used, it is recommended not to enable this feature rename-command CONFIG "" # can also be defined as empty, so the CONFIG command # limits the related configuration maxclients 10000 # limits the maximum number of client connections maxmemory # sets the maximum memory usage The unit is bytemaxmemory-policy volatile-lru # to specify the memory removal rule maxmemory-samples 3 # LRU and the TTL algorithm are estimates. So you can set the sample size. # Snapshot key triggers, then you can change the number of key samples. # AOF persistence appendonly no # if it is no, enable aof persistence appendfilename "apponly.aof" # specify aof file name appendfsync everysec # three modes, the fastest no (do not call fsync), the most secure always (call fsync for each write), and the default everysec (call fsync once per second). No-appendfsync-on-rewrite no # set yes to avoid disk io blocking when the amount of writing is very large auto-aof-rewrite-percentage 10 # 10 write = when the growth of aof files reaches 10%, it will trigger the rewriting mechanism uto-aof-rewrite-min-size 64mb # rewriting will have a condition That is, it cannot be lower than 64Mb### slow log related slowlog-log-slower-than 10000 # if it is slower than 10000ms, log slowlog-max-len 128log length Delete the oldest log when it is greater than 128 # online example # daemonize yespidfile / usr/local/redis/var/redis.pidport 6379timeout 300loglevel debuglogfile / usr/local/redis/var/redis.logdatabases 16save 900 1save 300 10save 60 10000rdbcompression yesdbfilename dump.rdbdir / usr/local/redis/var/appendonly noappendfsync always

Master and slave step at the same time

Master master192.168.1.1 Slave slave192.168.1.2

Install redis and start it as described above, leave the master configuration file unchanged, and add the following line to the slave configuration file:

Slaveof 192.168.1.1 6379 / / Primary ip and port

Masterauth passwd / / if a password is set on the host, add this line

Restart the test:

Master > > redis-cli set key0 1 & & redis-cli get key0 = = output 1

Slave > > redis-cli get key0 = = output 1

Slave-read-only yes # sets the frequency of slave initiating ping to master from read-only repl-ping-slave-period 10 #, and initiates repl-timeout 60 every 10 seconds. # set slave ping to time out after master is disabled. After repl-disable-tcp-nodelay no # is turned on, less bandwidth will be used, but there will be delay. It is recommended to turn off repl-backlog-size 1mb # after the master slave is disconnected. The master first writes the data to the buffer backuplog, and then reads the data from the connection again. After the master-slave disconnection, the validity period of the buffer. By default, more than one hour slave-priority 3600 # slave sets priority. The smaller the value, the higher the priority. It is applied to the cluster. When min-slaves-to-write 3 # is used together with the following, the master finds that the delay of more than 3 slave is higher than 10s. Min-slaves-max-lag 10 # then the master pauses the write operation. If either of these two values is 0, the feature is turned off.

Commonly used orders

String:

Set key1 teng / / set assignment

Set key1 teng / / A key corresponds to a value. Multiple assignments will overwrite the previous value.

Value of get key1 / / get

Setnx key2 aaa / / return 1 get key2 to view

Setnx key2 bbb / / returns 0. If key exists, 0 is returned and will not be created.

Setex key3 10 1 / / this is used to set the expiration time of the key view time ttl key3

Mset key1 1 key2 2 c 3 / / set multiple key at the same time

Mget key1 key2 c

Hash:

Hset user1 name teng / / create hash, which can store multiple information such as user name, sex, age, etc.

Hset user1 age 24

Hset user1 job it

Hgetall user1 / / get all values

Hmset user2 name teng age 24 job it / / batch build key-value pairs

Hmget user2 / / get all values

Hmget user2 name age / / get the specified value

Hdel user2 job / / Delete the specified filed

Hkeys user2 / / print all key

Hvals user2 / / print all values

Hlen user2 / / check how many filed (keys) hash has, and return numbers

Lists:

Lpush lista a / / Press an element from the left

Lpush lista b

Rpush lista 1 / / Press an element from the right

Rpush lista 2

Lpop lista / / is taken out from the left. By default, it is the first one on the left. After taking it out, this value no longer exists.

Rpop lista / / take the first element from the right

Lrange lista 0-1 / / 0 is the first on the left side of the head,-1 is the first on the right side of the tail, and there is no rrange

Linsert lista before 2 3 / / insert an element with an element of 3 before the value 2 of the element

Lset lista 4 bbb / / modify the fifth element to bbb

Lindex lista 0 / / look at the first element, where the number is the index

Lindex lista 3 / / View the fourth element

Llen lista / / check how many elements are in the linked list

Set:

Sadd seta aaa / / put elements into the collection seta

Smembers seta / / View all elements in the collection

Srem seta aaa / / Delete elements

Spop seta / / randomly take out an element and delete it

Sdiff seta setb / / difference set, taking seta as the standard

Sinter seta setb / / find the intersection

Sunion seta setb / / Union set

Sdiffstore setc seta setb / / subtractive set, and stored in setc, view SMEMBMERS setc

Sinterstore setd seta setb / / ask for intersection, and store setd, view SMEMBMERS setd

Sunionstore sete seta setb / / join set and store it in sete

Sismember seta aaa / / determines whether an element belongs to a collection

Srandmember seta / / randomly take out an element but do not delete it

Zset:

Zadd zseta 11123 / / create ordered collections. Commands such as uppercase ZADD can be completed by tab.

Zrange zseta 0-1 / / displays all elements, in order

Zrange zseta 0-1 withscores / / can take a score

Zrangebyscore zseta 1 10 / / returns elements with a score of 1-10

Zrank zseta 22 / / returns the index value of the element, which starts at 0 and is sorted forward by score

Zrevrank zseta 222ditto, except that it is sorted in reverse order of score

Zrevrange zseta 0-1 / / displays all elements in reverse order with a score

Zcard zseta / / returns the number of all elements in the collection

Zcount zseta 1 10 / / returns the number of elements with a score of 1-10

Zrem zseta 222Delete the specified element

Zremrangebyrank zseta 0 2 / / deletes the elements in the index range 0-2, sorting by score forward

Zremrangebyscore zseta 1 10 / / Delete elements with scores ranging from 1 to 10

Key-value correlation:

Keys * / / remove all key

Keys m * / / fuzzy matching

EXPIRE key1 100s / / Expiration after setting key1 100s

Del key1 / / Delete a key, return 1 successfully, otherwise return 0

Ttl key / / check how long it will take for the key to expire. The unit is smermer2, which means key does not exist, and-1 does not set survival time.

Select 0 / / means to select the current database and enter the 0 database by default

Exists name / / returns 1 with name key, otherwise returns 0

Move age 1 / / move age to database 1

Persist key1 / / cancel the expiration time of key1

Randomkey / / randomly returns a key

Type key1 / / returns the type of key

Rename oldname newname / / rename key

Info / / returns redis database status information

Dbsize / / returns the number of key in the current database

Flushdb / / clear all keys in the current database

Flushall / / clear all key in all databases

-

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report