Start with NoSQL

NoSQL is an acronym for Not Only SQL, meaning that the technology complements, rather than replaces, traditional relational databases. In the whole NoSQL technology stack, MemCache, Redis, MongoDB are called the three swordsmen of NoSQL. So why does the era need NoSQL databases? Here’s a comparison:

  Relational database No database
Data storage location The hard disk memory
The data structure Highly organized structured data There are no predefined patterns
Data manipulation mode SQL All data is key-value pairs and there is no declarative query language
Transaction control Strict base transaction ACID principle The CAP theorem

So the biggest advantages of NoSQL databases are: high performance, high availability, and scalability.

Ii. Introduction to Redis

Redis English website introduction:

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.
Copy the code

Redis Chinese website introduction:

Redis is an open source (BSD-licensed), in-memory data structure storage system that can be used as a database, cache, and messaging middleware. It supports many types of data structures, such as strings (hashes), lists (Lists), sets (sets), sorted sets (sorted sets) and range queries, bitmaps, Hyperloglogs and Geospatial index radius query. Redis is built with replication, LUA scripting, LRU eviction, transactions and different levels of disk persistence, And provides high availability through Redis Sentinel and Automated partitioning (Cluster).Copy the code

Redis command reference document: redisdoc.com

Three, Redis installation

1. Upload redis-4.0.2.tar.gz and decompress it

The tar – ZXVF redis – 4.0.2. Tar. Gz

2. Install the C compilation environment

[It is recommended to take snapshots first.]

yum install -y gcc-c++

3. Change the installation position

Vim redis unzip/SRC /Makefile

PREFIX? =/usr/local/redisCopy the code

As far as Redis itself is concerned, it does not need to be modified. The purpose of modification here is to make Redis running program not mixed with other files.

4. Compile and install

Compile: Go to the decompressed Redis directory and run the make command

[It is recommended to take snapshots first.]

Install: make install

5. Start the Redis server

① Default startup

/ root @ rich ~ # / usr/local/redis/bin/redis – server 7239: C 7 Oct 18:59:12. 144 # oO0OoO0OoO0Oo redis is starting OO0OoO0OoO0Oo 7239:C 07 Oct 18:59:12.144 # Redis version=4.0.2, bits=64, commit=00000000, modified=0, PID =7239, Just started 7239:C 07 Oct 18:59:12.144 # Warning: no config file specified, using the default config. In order to specify a config file use /usr/local/redis/bin/redis-server /path/to/redis.conf 7239:M 07 Oct 18:59:12.145 * Increased maximum number of open files to 10032 (it was originally set to 1024)._ _. – ` ` __ ‘- _ _. – ` ` `. ` _.’ ‘- _ Redis 4.0.2 (00000000/0), 64 – bit. – ` `. – ` ` `. ` ` ` \ / _, _’ -. _ (‘. – ` | `, ) Running in standalone mode |`-._`-… – ` _… -.“-._|’` _.-‘| Port: 6379 | `-._ `._ / _.-‘ | PID: 7239 `-._ `-._ `-./ _.-‘ _.-‘ |`-._`-._ `-._.-‘ _.-‘_.-‘| | `-._`-._ _.-‘_.-‘ | redis.io `-._ `-._`-._.-‘_.-‘ _.-‘ | ` -) _ ` -) _ ` – _. – ‘_. -‘ _. – ‘| | ` – _ ` – _ _. -‘ _. – ‘| ` – _ ` – _ ` – _. -‘ _. – ‘_. -‘ ` – _ ` – _. – ‘_. -‘ ` – _ _. – ‘` -. __. -‘

7239:M 07 Oct 18:59:12.148 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128. 7239:M 07 Oct 18:59:12.148 # Server Initialized 7239:M 07 Oct 18:59:12.148 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add ‘vm.overcommit_memory = 1’ to /etc/sysctl.conf and then reboot or run the command ‘sysctl vm.overcommit_memory=1’ for this to take effect. 7239:M 07 Oct 18:59:12.148 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will be created latency and memory usage issues with Redis. To fix this issue run the command ‘echo never > /sys/kernel/mm/transparent_hugepage/enabled’ as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is Disabled. 7239:M 07 Oct 18:59:12.148 * Ready to Accept connections

Stop the Redis server

/ usr/local/redis/bin/redis – cli shutdown… 7239:M 07 Oct 19:00:53.98 # User requested shutdown… 7239:M 07 Oct 19:00:53.208 * Saving the final RDB snapshot before Withdraw. 7239:M 07 Oct 19:00:53.214 * DB saved on disk 7239:M 07 Oct 19:00:53.214 # Redis is now ready to exit, bye bye…

 

② Start customizing configuration items

[1] Prepare the configuration file

Cp/opt/redis – 4.0.2 / redis. Conf/usr/local/redis /

Vim [2] modify configuration items/usr/local/redis/redis. Conf

Note: mkdir -p /var/logs/redis.log is required to create the /var/logs/redis.log directory

Configuration Item Name role The values
daemonize Controls whether the Redis server is run as a daemon no
logfile Specifies the log file location “/var/logs/redis.log”
dir Redis working directory /usr/local/redis

Bind IP address port number 192.168.0.100 192.168.0.100

[3] Make Redis start according to the specified configuration file

Format Redis-server File path Path of the redis

, for example, / usr/local/redis/bin/redis server/usr/local/redis/redis. Conf

 

 

DENIED redis is running in protected mode: You do not need to set a password

6. Log in to the client

/usr/local/redis/bin/redis-cli

127.0.0.1:6379 >

ping

PONG

127.0.0.1:6379 > exit

Another:

cd /usr/local/redis/bin

/redis-cli -h 192.168.0.100 -p 6379

192.168.0.100:6379 > ping PONG

Four, Redis five common data structures

1. Overall structure

KEY VALUE
string
list
set
hash
zset

Data in Redis is, in general, key-value pairs. Different data types refer to the types of the median key-value pairs.

2. Type string

The most basic type in Redis, which is a single value for key. Binary security, do not worry about binary data changes due to coding and other problems. So the Redis string can contain any data, such as JPG images or serialized objects. The maximum capacity of a string value in Redis is 512 megabytes.

3. The type of the list

A Redis list is a simple list of strings, sorted by insertion order. You can add an element to either the head (left) or the tail (right) of the list. It shows that its bottom layer is based on linked lists, so it operates with high efficiency at the head and tail, and low efficiency in the middle.

2. The set type

Redis’ set is an unordered collection of type string. It is implemented based on hash tables.

3. The hash type

Is itself a set of key-value pairs. It can be treated like a Map<String,Object> in Java.

4. Zset type

Redis zset, like set, is a collection of string elements and does not allow duplicate members. The difference is that each element is associated with a double score. Redis uses scores to sort the members of a collection from smallest to largest. Members of a Zset are unique, but scores can be repeated.

Redis command line operation

1. Basic operations

① Switching database

HTML Redis has 16 databases by default. 115 # Set the number of databases. The default database is DB 0, you can select 116 # a different one on a per-connection basis using SELECT

where 117 # dbid is a number between 0 and ‘databases’-1 110 databases 127.0.0.1:6379> SELECT 2 OK 127.0.0.1:6379[2]> SELECT 0 OK 127.0.0.1:6379> ‘

② Check the database length

HTML 127.0.0.1:6379> dbsize (integer) 3

2. The KEY operation

HTML ●KEYS PATTERN ●TYPE KEY ●MOVE KEY DB moves a set of key-value pairs to another database ●DEL KEY [KEY…] At least one KEY must be specified. ●EXISTS KEY Checks whether the specified KEY EXISTS. Returns 1 if a KEY is specified, and 0 if no KEY is specified. Multiple keys can be specified, returning the number of existing keys. ●RANDOMKEY returns a RANDOMKEY from an existing KEY ●RENAME KEY NEWKEY renames a KEY, regardless of whether the NEWKEY already exists, or overwrites it if it already exists. ●RENAMENX KEY NEWKEY The command can be executed successfully only when the NEWKEY does not exist. ●TTL KEY Checks how long the KEY lasts in SECONDS. ●PTTL KEY checks how long the KEY lasts in milliseconds. ●EXPIRE KEY SECONDS Set a KEY to expire in SECONDS, which Redis will remove. ●EXPIREAT KEY TIMESTAMP sets a KEY to EXPIREAT the specified time in TIMESTAMP ●PEXPIRE KEY MILLISECONDS specifies the expiration time in MILLISECONDS ●PEXPIREAT KEY MILLISECONDS-TIMESTAMP Specifies the elapsed time in MILLISECONDS ●PERSIST KEY removes the elapsed time and becomes a permanent KEY

2. String operations

` ` ` HTML low SET KEY VALUE [EX SECONDS] [PX MILLISECONDS] [NX | XX] give the KEY to SET a VALUE of type string. The EX parameter is used to set the number of seconds of survival. The PX parameter is used to set the number of milliseconds to survive. The NX parameter indicates that the KEY specified in the current command does not exist. The XX parameter indicates that the KEY specified in the current command exists. ●GET KEY Obtains the value based on the KEY. The value can only be string. ●APPEND KEY VALUE Appends the specified VALUE to the original VALUE of the KEY. The returned value is string length after addition ●STRLEN KEY Directly Returns string length ●INCR KEY increases by 1 ●DECR KEY decreases by 1 ●INCRBY KEY INCREMENT Original value +INCREMENT ●DECRBY KEY DECREMENT Original VALUE -DECREMENT ●GETRANGE KEY START END Selects a specified segment from a string ●SETRANGE KEY OFFSET VALUE Specifies that values are replaced from OFFSET ●SETEX KEY SECONDS ●SETNX KEY VALUE Create a string KEY VALUE pair ●MSET KEY VALUE [KEY VALUE…] Set a set of multiple KEY pairs at one time ●MGET KEY [KEY…] MSETNX KEY VALUE [KEY VALUE…] ●GETSET KEY VALUE Sets the new VALUE and returns the old VALUE

` ` `

3. The list action

HTML ●LPUSH key value [value…] ●RPUSH key value [value… ●LRANGE key start stop prints element data based on the index of the list set: 0,1,2,3… Number of reversals: -1,-2,-3… ●LLEN key ●LPOP Key pops an element from the left. Eject = return + delete. ●RPOP Key pops an element from the right. ●RPOPLPUSH source destination RPOP an element from the source, LPUSH to the destination in low LINDEX key index according to the index from the collection value low LINSERT key BEFORE | AFTER the pivot value specified in the pivot value BEFORE or AFTER inserting value low LPUSHX key Value LPUSH ●LREM key count value Removes the key from the list based on the number specified by count. Value ●LSET Key index Value Replaces the element at the specified index position with another value ●LTRIM Key start stop Only the data in the specified range is retained and the data on both sides is deleted

` ` `

4. Set operation

HTML ●SADD key [member…] ●SREM key member ●SCARD key returns the number of elements in the set ●SISMEMBER key member Checks whether the specified member is an element in the set ●SREM key member [member…] ●SINTER key [key…] Set A: A, B, C Set B: B, C, D Intersection: B, C ●SINTERSTORE destination key [key…] SDIFF key [key…] Set A: A, B, C set B: b, C, D A diff: A on B equivalent to: A- Intersection part ●SDIFFSTORE destination key [key…] Low SUNION key [key]… Set A: A, B, C Set B: B, C, D Union: A, B, C, D ●SUNIONSTORE destination key [key…] SMOVE source destination member SMOVE source destination member SMOVE source destination member ●SRANDMEMBER key [count] returns a random number of elements from the set. Return 1 ●SSCAN key cursor [MATCH pattern] [count count] Cursor based traversal

` ` `

5. The hash operation

HTML ●HSET Key Field Value ●HGETALL key ●HGET key field ●HLEN key ●HKEYS key ●HEXISTS key field ●HDEL key field [field …] ●HINCRBY Key Field increment ●HMGET Key field [field… ●HMSET key field value [field value… ●HSETNX key field value ●HSCAN key cursor [MATCH pattern] [COUNT COUNT] ‘

6. Zset operation

` ` ` HTML low ZADD key [NX | XX] [CH] [INCR] score member [score member… ●ZRANGE key start stop [WITHSCORES] ●ZCARD key ●ZSCORE key member ●ZINCRBY key increment member ●ZLEXCOUNT key min Max ●ZRANGEBYLEX key min Max [LIMIT offset Count] returns member min and Max in alphabetical order ●ZRANGEBYSCORE key min Max [WITHSCORES] [LIMIT offset count First sort the scores in ascending order, ●ZREM key member [member…] ●ZREMRANGEBYLEX key min Max ●ZREMRANGEBYRANK key start stop ●ZREMRANGEBYSCORE Max (WITHSCORES) Max (WITHSCORES) Max (WITHSCORES) Max (WITHSCORES) ●ZREVRANK key member ●ZINTERSTORE destination numkeys key [WEIGHTS…] [WEIGHTS…]] [AGGREGATE The SUM | MIN | MAX] low ZUNIONSTORE destination numkeys key [key]… [WEIGHTS weight] [AGGREGATE SUM | MIN | MAX] take intersection, member of the specified collection ZSCAN key cursor [MATCH pattern] [COUNT COUNT] ‘

6. Redis persistence mechanism

Website description

When Redis works, all data is stored in memory, and in case the server fails, all data is lost. In response to this situation, Redis uses persistence mechanisms to enhance data security.

1.RDB

① Mechanism Description

Data in memory is saved as a snapshot to a file on the hard disk at regular intervals. Redis enables the RDB mechanism by default.

② Trigger time

[1] Based on the default configuration

“` properties

save 900 1

save 300 10

save 60 10000

“`

meaning

configuration meaning
save 900 1 At least one change within 900 seconds triggers the save operation
save 300 10 At least 10 changes within 300 seconds trigger the save operation
save 60 10000 At least 10,000 changes within 60 seconds trigger the save operation

[2] Use the save command

Save or bgsave

[3] Run the flushall command

This command also produces the dump. RDB file, but it is empty and meaningless

[4] The server shuts down

If the SHUTDOWN command is used to exit Redis normally, a persistent save is executed.

③ Related Configuration

Configuration items The values role
save “” The RDB mechanism is disabled
dbfilename File name, for example, dump.rdb Set the name of the data store file in RDB mode
dir Redis working directory path Specify the path to the directory where the persistence file is stored. Note: this must be a directory and not a file name

(4) thinking

Does the RDB guarantee absolute data security?

2.AOF

① Mechanism Description

According to the policies specified in the configuration file, the commands for generating data are saved to a file on the hard disk. The contents of an AOF file can be seen in the following example:

“` properties

*2

$6

SELECT

$1

0

*3

$3

set

$3

num

$2

10

*2

$4

incr

$3

num

*2

$4

incr

$3

num

*2

$4

incr

$3

num

“`

The Redis command to generate the contents of the above file is:

“` html

set num 10

incr num

incr num

incr num

“`

② Basic AOF configuration

Configuration items The values role
appendonly yes Enable AOF persistence
  no Disable AOF persistence [default]
appendfilename “File name” AOF persistence file name
dir Redis working directory path Specify the path to the directory where the persistence file is stored. Note: this must be a directory and not a file name
appendfsync always The file is written after each data modification, which is slow but safest.
  everysec Write operations are performed once per second. Compromise.
  no The fastest write operation is performed by the operating system at the appropriate time.

(3) AOF rewrite

Compare the following two sets of commands:

AOF rewrite before AOF rewritten
set count 1 incr count incr count incr count set count 4

The final value of the two sets of commands is the same for count, but the AOF rewriting eliminates the intermediate process, which can make the AOF file smaller. Redis decides whether to rewrite AOF based on the size of the AOF file. The configuration items are as follows:

Configuration items meaning
auto-aof-rewrite-percentage 100 AOF rewrite is performed when the file size increases by 100%
auto-aof-rewrite-min-size 64mb AOF rewrite is performed when the file size grows to 64MB

Do not do frequent AOF rewrites in practice, because CPU resources are more valuable than hard disk resources, so you should not consume CPU performance to save hard disk space.

3. Repair persistent file damage

If a damaged persistent file is read during the startup of the Redis server, the startup fails. In this case, you need to repair the damaged persistent file for the normal startup of the Redis server. The AOF file is used as an example to describe how to repair the fault.

  • Step 1: Back up the appendone.aof file to be repaired

  • Step 2: Execute the fix

    /usr/local/redis/bin/redis-check-aof –fix /usr/local/redis/appendonly.aof

  • Step 3: Restart Redis

Note: Repairing persistent files simply removes the corrupted parts, not retrieves the corrupted data.

4. Extended reading: A trade-off between two persistence mechanisms

1) RDB

[1]

Suitable for large-scale data recovery with high speed

[2]

All changes made after the last snapshot are lost. Therefore, data consistency and integrity cannot be guaranteed. At Fork, the data in memory is cloned. Roughly twice the expansibility needs to be considered, but there are conditions for this to be true, and Linux has optimization methods

(2) AOF

[1]

When you run appendfSync always, data consistency is theoretically achieved, but performance is poor. The content of the file is readable and can be used to analyze Redis working conditions.

[2]

Persist the same data, file size is larger than RDB, recovery speed is slower than RDB. The efficiency of synchronous write is lower than that of RDB, and the efficiency of asynchronous write is the same as that of RDB.

③RDB and AOF coexist

When Redis restarts, AOF files will be loaded first to recover the original data, because AOF files usually hold more complete data sets than RDB files

RDB data is not real-time, and server restart will only look for AOF files when both are used. Should we just use AOF? The authors advise against it, as RDB is better for backing up databases (AOF is constantly changing), quick restarts, and no potential AOF bugs, as a fallback measure.

④ Usage Suggestions

If Redis is only used as a cache, no persistence can be used.

For other applications, performance, integrity, and consistency are considered.

RDB files are only used for backup purposes. It is recommended that RDB files be persisted only on the Slave and backed up only once every 15 minutes. Only save 9001 is retained. If you Enalbe AOF, the benefit is that you lose less than two seconds of data in the worst case. The startup script is simpler and you just load your own AOF files. The cost is constant IO and the inevitable blocking of writing new data to new files in the rewrite process. The frequency of AOF rewrite should be minimized as long as hard drives are permitted; the default base size of AOF rewrite, 64M, is too small and can be set to more than 5G. The default size exceeds 100% of the original size and overrides can be changed to an appropriate value. If AOF is not enabled, high availability performance can be achieved by master-slave Replication alone. It saves a lot of IO and reduces the system volatility that comes with rewriting. The trade-off is that if the Master/Slave is dropped at the same time, the data will be lost for more than ten minutes. The startup script will also compare the RDB files in the two Master/Slave files and load the newer one. Sina Weibo has chosen this structure.

Redis transaction control

1. Commands related to Redis transaction control

The command name role
MULTI The command collection starts. All subsequent commands are not executed immediately, but are added to a queue.
EXEC Execute all commands in the command queue behind MULTI.
DISCARD Abort the command in the queue.
WATCH “Observe” and “monitor” a KEY. When the KEY is operated by other commands outside the current queue, the command of the queue is abandoned
UNWATCH Give up monitoring a KEY

2. Two cases of command queue execution failure

① Failed to join the queue

HTML 127.0.0.1:6379> multi OK 127.0.0.1:6379> set age 20 QUEUED 127.0.0.1:6379> INCr age QUEUED 127.0.0.1:6379> INCr Age WWW (error) ERR wrong number of arguments for ‘incr’ command 127.0.0.1:6379> exec (error) EXECABORT Transaction discarded because of previous errors. “`

An error detected at enqueue time is encountered and the entire queue is not executed.

② Queue execution failed

HTML 127.0.0.1:6379> multi OK 127.0.0.1:6379> set age 30 QUEUED 127.0.0.1:6379> incrby age 5 QUEUED 127.0.0.1:6379> Incrby age 5 QUEUED 127.0.0.1:6379> incrby age ww QUEUED 127.0.0.1:6379> incrby age 5 QUEUED 127.0.0.1:6379> EXEC 1) OK 2) (INTEGER) 35 3) (integer) 40 4) (Error) ERR value is not an integer or out of range 5) (integer) 45 127.0.0.1:6379> get age “45” “`

Errors are not detected at enqueue time, the entire queue is executed with incorrect commands failing to execute, but other commands are not rolled back.

Why does Redis not support rollback

Here’s the official explanation:

If you have experience with relational databases, the idea that Redis does not roll back when a transaction fails, but continues to execute the remaining commands may strike you as a little strange. The advantages of this approach are as follows: 1. The Redis command will only fail due to incorrect syntax (and these problems cannot be detected at queue entry), or the command will be used on the wrong type of key: That is, from a practical point of view, failed commands are caused by programming errors that should be discovered during development, not in production. 2. Because rollback support is not required, Redis can be kept simple and fast internally. There is an argument that Redis is buggy in the way it handles transactions, but it is important to note that in general, rolling back does not solve the problem caused by programming errors. For example, if you intend to add 1 to the value of a key by INCR, but accidentally add 2 to it, or if you perform INCR on the wrong type of key, rollback does not handle these situations.

3. Pessimistic locks and optimistic locks

After the WATCH command is used to monitor a KEY, the commands in the current queue are abandoned due to the execution of external commands, which is an example of optimistic locking.

  • Pessimistic locking

    It is considered that the current environment is prone to collisions. Therefore, data must be locked before performing an operation and released after the operation is complete. Other operations can continue.

  • Optimistic locking

    Consider that the current environment is not prone to collisions, so do not lock data before performing an operation, and in case a collision does occur, abandon your operation.

Redis master/slave replication mechanism

1. Benefits of read-write separation:

  • Performance optimization: The primary server focuses on write operations and can work in a mode more suitable for writing data; Similarly, the slave server focuses on reads and can work in a mode better suited to reading data.
  • Enhance data security to avoid single point of failure: Because of the data synchronization mechanism, data on all servers is consistent. Therefore, the failure of one server does not cause data loss or access failure. From this perspective, the Redis servers participating in master/slave replication constitute a cluster.

2. Setup procedure

1) thinking

The Redis cluster uses the same executable at run time, but the corresponding configuration file is different.

The same parameters in each configuration file are:

“` html

dir /usr/local/cluster-redis

“`

The different parameters are:

Configuration Item Name role The values
port Port number that the Redis server listens for after startup 6000 7000 8000
dbfilename RDB file storage location dump6000.rdb dump7000.rdb dump8000.rdb
logfile Log file location /var/logs/redis6000.log /var/logs/redis7000.log /var/logs/redis8000.log
pidfile Pid file location /var/run/redis6000.pid /var/run/redis7000.pid /var/run/redis8000.pid

(2) step

  • Create the /usr/local/cluster-redis directory

  • Step 2: Copy the original unmodified redis.conf file to /usr/local/cluster-redis

  • Conf file in /usr/local/cluster-redis to redis6000.conf

  • Step 4: Modify the configuration items in redis6000.conf as planned

    • dir
    • port
    • dbfilename
    • logfile
    • pidfile
  • Step 5: Copy redis6000.conf to redis7000.conf

  • Step 6: Modify the configuration items in redis7000.conf

    • port
    • dbfilename
    • logfile
    • pidfile
  • Step 7: Copy redis6000.conf to redis8000.conf

  • Step 8: Modify the configuration items in redis8000.conf

    • port
    • dbfilename
    • logfile
    • pidfile

③ Start the Redis primary and secondary replication clusters

“`html

/usr/local/redis/bin/redis-server /usr/local/cluster-redis/redis6000.conf

/usr/local/redis/bin/redis-server /usr/local/cluster-redis/redis7000.conf

/usr/local/redis/bin/redis-server /usr/local/cluster-redis/redis8000.conf

“`

The redis-cli command is in the following format: /usr/local/bin/redis-cli -h IP address -p port number shutdown

3. Master-slave relationship

① Check the master/slave relationship

HTML 127.0.0.1:6000> info Replication # Replication role: Master Connected_Slaves :0

Each node server in the newly started cluster server considers itself to be the primary server. A master-slave relationship needs to be established.

② Set the master-slave relationship

Specify the host location on the slave machine

HTML SLAVEOF 127.0.0.1 6000

③ Abolish the master-slave relationship

Execute commands on the slave machine

“` html

SLAVEOF NO ONE

“`

4. Preliminary test

  • Test 1: Write data on the host and view data on the slave
  • Test 2: Failed to write data to the slave machine. The basis in the configuration file is: slave-read-only yes
  • Test 3: The host runs SHUTDOWN to check the slave state
  • Test 4: The host recovers and starts. Check the slave state
  • Test 5: when the slave machine is SHUTDOWN, the host writes data to the slave machine and starts to check the status. Reset the master/slave relationship to check whether the new data is synchronized.

5. Sentinel mode

1) role

The sentinel server monitors the master and slave to automatically manage the master and slave replication clusters.

② Related concepts

[1] Subjective referral

One sentry detects that a node server is offline.

[2] [J]

Indicates that the specified number of sentinel servers are offline for a node server. This amount is specified later in the Sentry’s startup profile.

3 Configuration Mode

For simplicity we will only have one sentry. All we need to do is create a configuration file for the Sentinel server to run.

vim /usr/local/cluster-redis/sentinel.conf

format Sentinel Monitor Names hosts host IP address Host port Number The number of hosts to be identified as offline by Sentinel
example Sentinel Monitor MyMaster 127.0.0.1 6000 1

④ Start the sentry

/usr/local/redis/bin/redis-server /usr/local/cluster-redis/sentinel.conf –sentinel

HTML +sdown master mymaster 127.0.0.1 6379 +odown master mymaster 127.0.0.1 6379 #quorum 1/1…… + vote – for – 17818 eb9240c8a625d2c8a13ae9d99ae3a70f9d2 leader 1 [election leader]… + fail-state-send-slaveof -noone slave 127.0.0.1:6381 127.0.0.1 6381 @mymaster 127.0.0.1 6379

— — — — — — — — — — — — — hang up them again host — — — — — — — — — — — — — — — — — — — — — — sdown slave 127.0.0.1:6379 127.0.0.1 6379 @ mymaster 127.0.0.1 6381 +convert-to-slave slave 127.0.0.1:6379 127.0.0.1 6379 @myMaster 127.0.0.1 6381 +convert-to-slave slave 127.0.1:6379 127.0.0.1 6379 @myMaster 127.0.0.1 6381

 

Ix. Publish and subscribe

Subscribe to a channel

HTML 127.0.0.1:6379> SUBSCRIBE CCTV Reading Messages… (press Ctrl-C to quit) 1) “subscribe” 2) “cctv” 3) (integer) 1

` ` `

2. Post on a channel

HTML 127.0.0.1:6379> PUBLISH CCTV Hai (integer) 1

 

HTML 127.0.0.1:6379> SUBSCRIBE CCTV Reading Messages… (press Ctrl-C to quit) 1) “subscribe” 2) “cctv” 3) (integer) 1 1) “message” 2) “cctv” 3) “hai” “`

 

Ten, Jedis

A comparison

  MySQL Redis
The connection Connection Jedis
The connection pool C3P0 etc. JedisPool
Operation is completed Close the connection Close the connection

2. Redis preparation

Turn off the bind configuration in the Redis configuration file and set the password.

HTML #bind 127.0.0.1 requirepass your password

## 3.Jedis

XML


redis. Clients


jedis


2.9.0

“`

 

Jedis Jedis = new Jedis(“192.168.70.138”, 6379);

// Set the password jedis.auth(“123456”);

String ping = jedis.ping(); // Run the ping command.

System.out.println(ping);

jedis.close();

` ` `

## 4.JedisPool

“`java

GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

String host = “192.168.70.138”;

int port = Protocol.DEFAULT_PORT;

int timeout = Protocol.DEFAULT_TIMEOUT;

String password = “123456”;

JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout, password);

Jedis jedis = jedisPool.getResource();

String ping = jedis.ping();

System.out.println(ping);

jedisPool.close(); ` ` `