3月 042020
 

安装EPEL仓库

[root@ip-172-31-43-75 ~]# yum -y install epel-release
[root@ip-172-31-43-75 ~]# yum makecache

查看当前Redis服务版本信息

[root@ip-172-31-43-75 ~]# yum info redis
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: d36uatko69830t.cloudfront.net
 * epel: mirrors.aliyun.com
 * extras: d36uatko69830t.cloudfront.net
 * updates: d36uatko69830t.cloudfront.net
Available Packages
Name        : redis
Arch        : x86_64
Version     : 3.2.12
Release     : 2.el7
Size        : 544 k
Repo        : epel/x86_64
Summary     : A persistent key-value database
URL         : http://redis.io
License     : BSD
Description : Redis is an advanced key-value store. It is often referred to as a data
            : structure server since keys can contain strings, hashes, lists, sets and
            : sorted sets.
            : 
            : You can run atomic operations on these types, like appending to a string;
            : incrementing the value in a hash; pushing to a list; computing set
            : intersection, union and difference; or getting the member with highest
            : ranking in a sorted set.
            : 
            : In order to achieve its outstanding performance, Redis works with an
            : in-memory dataset. Depending on your use case, you can persist it either
            : by dumping the dataset to disk every once in a while, or by appending
            : each command to a log.
            : 
            : Redis also supports trivial-to-setup master-slave replication, with very
            : fast non-blocking first synchronization, auto-reconnection on net split
            : and so forth.
            : 
            : Other features include Transactions, Pub/Sub, Lua scripting, Keys with a
            : limited time-to-live, and configuration settings to make Redis behave like
            : a cache.
            : 
            : You can use Redis from most programming languages also.

[root@ip-172-31-43-75 ~]#

在主服务器上安装Redis服务

[root@ip-172-31-43-75 ~]# yum -y install redis

在主服务器上注册并启动服务

[root@ip-172-31-43-75 ~]# systemctl enable redis
Created symlink from /etc/systemd/system/multi-user.target.wants/redis.service to /usr/lib/systemd/system/redis.service.
[root@ip-172-31-43-75 ~]# systemctl start redis
[root@ip-172-31-43-75 ~]# redis-cli ping
PONG
[root@ip-172-31-43-75 ~]#

在主服务器上执行性能测试

[root@ip-172-31-43-75 ~]# redis-benchmark -q -n 1000 -c 10 -P 5
PING_INLINE: 333333.34 requests per second
PING_BULK: 499999.97 requests per second
SET: 499999.97 requests per second
GET: 333333.34 requests per second
INCR: 333333.34 requests per second
LPUSH: 333333.34 requests per second
RPUSH: 499999.97 requests per second
LPOP: 333333.34 requests per second
RPOP: 333333.34 requests per second
SADD: 333333.34 requests per second
HSET: 249999.98 requests per second
SPOP: 499999.97 requests per second
LPUSH (needed to benchmark LRANGE): 200000.00 requests per second
LRANGE_100 (first 100 elements): 45454.55 requests per second
LRANGE_300 (first 300 elements): 14084.51 requests per second
LRANGE_500 (first 450 elements): 6849.31 requests per second
LRANGE_600 (first 600 elements): 5102.04 requests per second
MSET (10 keys): 166666.67 requests per second

[root@ip-172-31-43-75 ~]#

在主服务器上查看端口监听

[root@ip-172-31-43-75 ~]# netstat -lnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN     
tcp6       0      0 :::111                  :::*                    LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN     
tcp6       0      0 ::1:25                  :::*                    LISTEN     
[root@ip-172-31-43-75 ~]#

在从服务器上安装并启动Redis服务

[root@ip-172-31-43-112 ~]# yum -y install epel-release
[root@ip-172-31-43-112 ~]# yum -y install redis

[root@ip-172-31-43-112 ~]# systemctl enable redis
Created symlink from /etc/systemd/system/multi-user.target.wants/redis.service to /usr/lib/systemd/system/redis.service.
[root@ip-172-31-43-112 ~]# systemctl start redis
[root@ip-172-31-43-112 ~]# redis-cli ping
PONG
[root@ip-172-31-43-112 ~]#

配置主服务器

[root@ip-172-31-43-75 ~]# vi /etc/redis.conf


# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Take the connection alive from the point of view of network
#    equipment in the middle.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.
#
# A reasonable value for this option is 300 seconds, which is the new
# Redis default starting with Redis 3.2.1.
#tcp-keepalive 300
tcp-keepalive 60


################################## NETWORK #####################################

# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 lookback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#bind 127.0.0.1
bind 172.31.43.75


# Require clients to issue AUTH <PASSWORD> before processing any other
# commands.  This might be useful in environments in which you do not trust
# others with access to the host running redis-server.
#
# This should stay commented out for backward compatibility and because most
# people do not need auth (e.g. they run their own servers).
#
# Warning: since Redis is pretty fast an outside user can try up to
# 150k passwords per second against a good box. This means that you should
# use a very strong password otherwise it will be very easy to break.
#
# requirepass foobared
requirepass 43l4890fji24897usdkj4eyud834ksdhwl9


# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
# is reached. You can select among five behaviors:
#
# volatile-lru -> remove the key with an expire set using an LRU algorithm
# allkeys-lru -> remove any key according to the LRU algorithm
# volatile-random -> remove a random key with an expire set
# allkeys-random -> remove a random key, any key
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
# noeviction -> don't expire at all, just return an error on write operations
#
# Note: with any of the above policies, Redis will return an error on write
#       operations, when there are no suitable keys for eviction.
#
#       At the date of writing these commands are: set setnx setex append
#       incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
#       sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
#       zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
#       getset mset msetnx exec sort
#
# The default is:
#
# maxmemory-policy noeviction
maxmemory-policy noeviction


# By default Redis asynchronously dumps the dataset on disk. This mode is
# good enough in many applications, but an issue with the Redis process or
# a power outage may result into a few minutes of writes lost (depending on
# the configured save points).
#
# The Append Only File is an alternative persistence mode that provides
# much better durability. For instance using the default data fsync policy
# (see later in the config file) Redis can lose just one second of writes in a
# dramatic event like a server power outage, or a single write if something
# wrong with the Redis process itself happens, but the operating system is
# still running correctly.
#
# AOF and RDB persistence can be enabled at the same time without problems.
# If the AOF is enabled on startup Redis will load the AOF, that is the file
# with the better durability guarantees.
#
# Please check http://redis.io/topics/persistence for more information.

#appendonly no
appendonly yes

# The name of the append only file (default: "appendonly.aof")

appendfilename "appendonly.aof"

在主服务器上重新启动Redis服务并查看端口监听

[root@ip-172-31-43-75 ~]# systemctl restart redis
[root@ip-172-31-43-75 ~]# netstat -lnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 172.31.43.75:6379       0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN     
tcp6       0      0 :::111                  :::*                    LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN     
tcp6       0      0 ::1:25                  :::*                    LISTEN     
[root@ip-172-31-43-75 ~]#

配置从服务器

[root@ip-172-31-43-112 ~]# vi /etc/redis.conf

#bind 127.0.0.1
bind 172.31.43.112

#tcp-keepalive 300
tcp-keepalive 60

requirepass 934jskls034ks73shdjd6

# Master-Slave replication. Use slaveof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# 1) Redis replication is asynchronous, but you can configure a master to
#    stop accepting writes if it appears to be not connected with at least
#    a given number of slaves.
# 2) Redis slaves are able to perform a partial resynchronization with the
#    master if the replication link is lost for a relatively small amount of
#    time. You may want to configure the replication backlog size (see the next
#    sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
#    network partition slaves automatically try to reconnect to masters
#    and resynchronize with them.
#
# slaveof <masterip> <masterport>
slaveof 172.31.43.75 6379

# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the slave to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the slave request.
#
# masterauth <master-password>
masterauth 43l4890fji24897usdkj4eyud834ksdhwl9

重新启动从服务器Redis服务

[root@ip-172-31-43-112 ~]# systemctl restart redis

登录测试

[root@ip-172-31-43-112 ~]# redis-cli -h 172.31.43.112 -p 6379
172.31.43.112:6379> AUTH 934jskls034ks73shdjd6
OK
172.31.43.112:6379> exit
[root@ip-172-31-43-112 ~]#

在主服务器上检查主从复制状态

[root@ip-172-31-43-75 ~]# redis-cli -h 172.31.43.75 -p 6379
172.31.43.75:6379> AUTH 43l4890fji24897usdkj4eyud834ksdhwl9
OK
172.31.43.75:6379> INFO
# Server
redis_version:3.2.12
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:7897e7d0e13773f
redis_mode:standalone
os:Linux 3.10.0-957.1.3.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:4.8.5
process_id:19963
run_id:d9d36c6ad3afb25b4ea2ab1c9acfdbb1818c9e9a
tcp_port:6379
uptime_in_seconds:772
uptime_in_days:0
hz:10
lru_clock:6234889
executable:/usr/bin/redis-server
config_file:/etc/redis.conf

# Clients
connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

# Memory
used_memory:1881968
used_memory_human:1.79M
used_memory_rss:8114176
used_memory_rss_human:7.74M
used_memory_peak:1917896
used_memory_peak_human:1.83M
total_system_memory:8094560256
total_system_memory_human:7.54G
used_memory_lua:37888
used_memory_lua_human:37.00K
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
mem_fragmentation_ratio:4.31
mem_allocator:jemalloc-3.6.0

# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1583292981
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:0
rdb_current_bgsave_time_sec:-1
aof_enabled:1
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_current_size:0
aof_base_size:0
aof_pending_rewrite:0
aof_buffer_length:0
aof_rewrite_buffer_length:0
aof_pending_bio_fsync:0
aof_delayed_fsync:0

# Stats
total_connections_received:2
total_commands_processed:217
instantaneous_ops_per_sec:1
total_net_input_bytes:7756
total_net_output_bytes:478
instantaneous_input_kbps:0.04
instantaneous_output_kbps:0.01
rejected_connections:0
sync_full:1
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:772
migrate_cached_sockets:0

# Replication
role:master
connected_slaves:1
slave0:ip=172.31.43.112,port=6379,state=online,offset=309,lag=0
master_repl_offset:309
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:2
repl_backlog_histlen:308

# CPU
used_cpu_sys:0.40
used_cpu_user:0.24
used_cpu_sys_children:0.00
used_cpu_user_children:0.00

# Cluster
cluster_enabled:0

# Keyspace
172.31.43.75:6379>

主服务器故障或维护时将从服务器临时切换为主服务器角色

[root@ip-172-31-43-112 ~]# redis-cli -h 172.31.43.112 -p 6379 
172.31.43.112:6379> AUTH 934jskls034ks73shdjd6
OK
172.31.43.112:6379> SLAVEOF NO ONE
OK
172.31.43.112:6379> INFO
# Server
redis_version:3.2.12
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:7897e7d0e13773f
redis_mode:standalone
os:Linux 3.10.0-957.1.3.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:4.8.5
process_id:19834
run_id:094e98c730ce1571ba38ca222d4762d332e25e86
tcp_port:6379
uptime_in_seconds:561
uptime_in_days:0
hz:10
lru_clock:6235238
executable:/usr/bin/redis-server
config_file:/etc/redis.conf

# Clients
connected_clients:1
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

# Memory
used_memory:812536
used_memory_human:793.49K
used_memory_rss:6008832
used_memory_rss_human:5.73M
used_memory_peak:833488
used_memory_peak_human:813.95K
total_system_memory:8094560256
total_system_memory_human:7.54G
used_memory_lua:37888
used_memory_lua_human:37.00K
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
mem_fragmentation_ratio:7.40
mem_allocator:jemalloc-3.6.0

# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1583292981
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-1
rdb_current_bgsave_time_sec:-1
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok

# Stats
total_connections_received:2
total_commands_processed:59
instantaneous_ops_per_sec:0
total_net_input_bytes:1027
total_net_output_bytes:19991
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
migrate_cached_sockets:0

# Replication
role:master
connected_slaves:0
master_repl_offset:785
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# CPU
used_cpu_sys:0.27
used_cpu_user:0.22
used_cpu_sys_children:0.00
used_cpu_user_children:0.00

# Cluster
cluster_enabled:0

# Keyspace
172.31.43.112:6379>

对于有多个从服务器集群的处理(在所有其他从节点执行)

SLAVEOF hostname port

主服务器恢复后再次切换回从服务器角色

172.31.43.112:6379> SLAVEOF 172.31.43.75 6379
OK
172.31.43.112:6379> INFO
# Server
redis_version:3.2.12
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:7897e7d0e13773f
redis_mode:standalone
os:Linux 3.10.0-957.1.3.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:4.8.5
process_id:19834
run_id:094e98c730ce1571ba38ca222d4762d332e25e86
tcp_port:6379
uptime_in_seconds:795
uptime_in_days:0
hz:10
lru_clock:6235472
executable:/usr/bin/redis-server
config_file:/etc/redis.conf

# Clients
connected_clients:2
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

# Memory
used_memory:833416
used_memory_human:813.88K
used_memory_rss:6012928
used_memory_rss_human:5.73M
used_memory_peak:833488
used_memory_peak_human:813.95K
total_system_memory:8094560256
total_system_memory_human:7.54G
used_memory_lua:37888
used_memory_lua_human:37.00K
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
mem_fragmentation_ratio:7.21
mem_allocator:jemalloc-3.6.0

# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1583292981
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-1
rdb_current_bgsave_time_sec:-1
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok

# Stats
total_connections_received:2
total_commands_processed:62
instantaneous_ops_per_sec:0
total_net_input_bytes:1178
total_net_output_bytes:22251
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.02
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
migrate_cached_sockets:0

# Replication
role:slave
master_host:172.31.43.75
master_port:6379
master_link_status:up
master_last_io_seconds_ago:2
master_sync_in_progress:0
slave_repl_offset:1121
slave_priority:100
slave_read_only:1
connected_slaves:0
master_repl_offset:0
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# CPU
used_cpu_sys:0.37
used_cpu_user:0.31
used_cpu_sys_children:0.00
used_cpu_user_children:0.00

# Cluster
cluster_enabled:0

# Keyspace
172.31.43.112:6379>

操作示例(复制)

172.31.43.75:6379> SET ABC 123465
OK
172.31.43.75:6379>

172.31.43.112:6379> GET ABC
"123465"
172.31.43.112:6379>