Redis入门日志

发布时间:2024年01月04日

安装命令

sudo apt-get install redis

查看版本

redis-cli -v

redis-cli 连接服务

redis-cli -h 127.0.0.1 -p 端口 -a 密码

查看工作路径

连接客户端cli后,输入config get dir得到工作路径,默认时/var/lib/redis/

查看服务

systemctl status redis-server.service

iml6yu@iml6yu-machine:~$ systemctl status redis-server.service
● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2024-01-02 08:35:15 CST; 3min 50s ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
   Main PID: 500 (redis-server)
     Status: "Ready to accept connections"
      Tasks: 5 (limit: 4599)
     Memory: 6.3M
        CPU: 414ms
     CGroup: /system.slice/redis-server.service
             └─500 "/usr/bin/redis-server *:6379" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

1月 02 08:35:12 iml6yu-machine systemd[1]: Starting Advanced key-value store...
1月 02 08:35:15 iml6yu-machine systemd[1]: Started Advanced key-value store.

常用路径(默认)

通过上面的命令可以看到,默认安装的redis服务的路径是在

/lib/systemd/system/redis-server.service

打开redis-server.service能看到更多内容

[Unit]
Description=Advanced key-value store
After=network.target
Documentation=http://redis.io/documentation, man:redis-server(1)

[Service]
Type=notify
ExecStart=/usr/bin/redis-server /etc/redis/redis.conf --supervised systemd --daemonize no
PIDFile=/run/redis/redis-server.pid
TimeoutStopSec=0
Restart=always
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=2755

UMask=007
PrivateTmp=yes
LimitNOFILE=65535
PrivateDevices=yes
ProtectHome=yes
ReadOnlyDirectories=/
ReadWritePaths=-/var/lib/redis
ReadWritePaths=-/var/log/redis
ReadWritePaths=-/var/run/redis

NoNewPrivileges=true
CapabilityBoundingSet=CAP_SETGID CAP_SETUID CAP_SYS_RESOURCE
MemoryDenyWriteExecute=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictRealtime=true
RestrictNamespaces=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

默认启动文件所在位置 /usr/bin

iml6yu@iml6yu-machine:/usr/bin$ ls | grep redis
redis-benchmark
redis-check-aof
redis-check-rdb
redis-cli
redis-server

可以看到关于redis的常用工具都在这里了

默认配置文件位置

/etc/redis/redis.conf

配置多个自启动的redis服务

增加多个配置文件

  • 使用任意一款顺手的工具将redis.conf拷贝到本地(因为我习惯了在windows上操作文件,如果更喜欢在linux上操作文件那就更简单了)

  • 将原来的文件复制一份,修改配置文件内容port 6379 为 6380 和6381 分别另存为 redis_6380.conf 和redis_6381.conf

  • 使用任意一款顺手的工具将文件上传到linux中(我的是ubuntu)

  • 修改文件所属用户和组 sudo chown redis:redis /etc/redis/redis_6380.conf /etc/redis/redis_6381.conf

服务模板

/lib/systemd/system/redis-server@service文件

添加多个服务文件

  • 将原来的service文件拷贝一份
  • 修改内容
ExecStart=/usr/bin/redis-server /etc/redis/redis_6380.conf --supervised systemd --daemonize no
PIDFile=/run/redis/redis-6380.pid
  • 将文件另存为redis-6380.service 到目录 /lib/systemd/system/

执行启动指令

systemctl start redis-6380.service

设置系统服务

systemctl enable redis-6380.service

查看运行状态

systemctl status redis-6380.service

出现以下结果表示运行成功,如果运行失败根据信息解决,一般就是配置文件搞错了

redis-6380.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-6380.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2024-01-02 13:07:45 CST; 3min 12s ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
   Main PID: 487 (redis-server)
     Status: "Ready to accept connections"
      Tasks: 5 (limit: 4599)
     Memory: 2.9M
        CPU: 400ms
     CGroup: /system.slice/redis-6380.service
             └─487 "/usr/bin/redis-server *:6380" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

1月 02 13:07:42 iml6yu-machine systemd[1]: Starting Advanced key-value store...
1月 02 13:07:45 iml6yu-machine systemd[1]: Started Advanced key-value store.

备注

移除服务:

systemctl disable redis-6381

Redis 主从模式配置

参与复制的Redis实例划分为主节点(master)和从节点(slave)。默认 情况下,Redis都是主节点。每个从节点只能有一个主节点,而主节点可以 同时具有多个从节点。复制的数据流是单向的,只能由主节点复制到从节 点。

配置从节点

配置复制的方式有以下三种:

  1. 在配置文件中加入slaveof{masterHost}{masterPort}随Redis启动生 效。
  2. 在redis-server启动命令后加入–slaveof{masterHost}{masterPort}生 效。
  3. 直接使用命令:slaveof{masterHost}{masterPort}生效。

在终端中输入redis-cli -h 127.0.0.1 -p 6380 -a 123456

连接127.0.0.1 端口6380 密码123456的redis客户端

连接成功后入输入

> slaveof 127.0.0.1 6379
OK
#配置密码
> config set masterauth 123456
OK

查看主节点信息

info replication 命令

127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:1
slave0:ip=127.0.0.1,port=6380,state=online,offset=798,lag=1
master_replid:753a7b57dee695aa8c687db61dbe978d9192c7ec
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:798
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:798

查看一下从节点的info信息

可以看到 role:slave

127.0.0.1:6380> info replication
# Replication
role:slave
master_host:127.0.0.1
master_port:6379
master_link_status:up
master_last_io_seconds_ago:2
master_sync_in_progress:0
slave_repl_offset:1092
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:753a7b57dee695aa8c687db61dbe978d9192c7ec
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:1092
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:1092

断开从节点

slaveof no one

再次查看信息, == role:master ==

127.0.0.1:6380> info replication
# Replication
role:master
connected_slaves:0
master_replid:c56653c49d3ef28e4bdb33adae2d41d8c350822a
master_replid2:753a7b57dee695aa8c687db61dbe978d9192c7ec
master_repl_offset:1540
second_repl_offset:1541
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:1540

配置一致性

? 主从配置不一致是一个容易忽视的问题。对于有些配置主从之间是可以 不一致,

比如:主节点关闭AOF在从节点开启。但对于内存相关的配置必须 要一致,

比如maxmemory,hash-max-ziplist-entries等参数。当配置的 maxmemory从节点小于主节点,如果复制的数据量超过从节点maxmemory 时,它会根据maxmemory-policy策略进行内存溢出控制,此时从节点数据已 经丢失,但主从复制流程依然正常进行,复制偏移量也正常。

修复这类问题 也只能手动进行全量复制。

当压缩列表相关参数不一致时,虽然主从节点存 储的数据一致但实际内存占用情况差异会比较大。

常见堵塞问题

发现堵塞

一般是通过程序的日志报警,出现大量的连接超时或者命令超时

也可以在redis-cli中使用slowlog get {n}命令查看慢日志

内部原因

  • API或者数据结构不合理,出现一次性读取大量数据或者keys
    • slowlog get n 查看慢日志
    • redis-cli -h 主机 -p 端口 -a 密码 --bigkeys 查看大对象
  • CPU饱和,reids是单线程的,有可能出现cpu跑到100%
    • redis-cli -h 主机 -p 端口 -a 密码 --stat 查看redis使用情况
  • 持久化导致的堵塞
    • for阻塞,一般发生在持久化的时候
    • AOF刷盘阻塞
    • HugePage写操作阻塞

外部原因

  • CPU竞争
    • 多个程序装在一台机器上,出现cpu竞争
    • Redis绑定CPU,如果在出现save命令时可能会出现单个cpu100%
  • 内存交换 linux级别,可以通过linux命令查看
  • 网络问题
    • 连接拒绝网络波动导致的,查看机器的网络日志
    • 连接拒绝Redis的maxclients参数配置导致,连接数已经达到了上线

哨兵

先配置复制模式

  • 启动一个redis服务作为master

  • 再启动两个redis作为slave

    • 通过redis-cli客户端命令,输入slaveof host port 作为slave
  • 在master上通过redis-cli输入info replication 可以看到如下信息表示模式成功,一个master两个slave

    192.168.137.144:6381> info replication
    # Replication
    role:master
    connected_slaves:2
    slave0:ip=192.168.137.144,port=6380,state=online,offset=464929,lag=1
    slave1:ip=192.168.137.144,port=6379,state=online,offset=464929,lag=0
    master_replid:37f740a0ac68ac3b36e44256d3c056e54995b1e3
    master_replid2:379ad0a8dd0b7a57560c0b0f640fee58c7da57b0
    master_repl_offset:464929
    second_repl_offset:344363
    repl_backlog_active:1
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:333074
    repl_backlog_histlen:131856
    

配置中的注意事项

conf文件中一定要配置bind 的地址,并且是一个客户端能够访问的地址,不可以使用127.0.0.1,这会导致客户端如果不在同一台物理机上无法连接

配置哨兵

模板地址

https://github.com/redis/redis/blob/unstable/sentinel.conf

重点配置内容

  • sentinel monitor m6379 192.168.137.144 6379 2
    • master名称,监控地址,端口,2代表判断主节点失败至少需要2个Sentinel节 点同意
  • sentinel down-after-milliseconds mymaster 30000
  • sentinel parallel-syncs mymaster 1
  • sentinel failover-timeout mymaster 180000

测试的时候在同一台电脑上开启多个哨兵(最少3个),所以要注意修改配置文件的port,按照官方文档给的建议是不应该放到同一个物理机上,连接见下

https://redis.io/docs/management/sentinel/

完整配置的demo

# Example sentinel.conf

# By default protected mode is disabled in sentinel mode. Sentinel is reachable
# from interfaces different than localhost. Make sure the sentinel instance is
# protected from the outside world via firewalling or other means.
protected-mode no

# port <sentinel-port>
# The port that this sentinel instance will run on
port 26379

# By default Redis Sentinel does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis-sentinel.pid when
# daemonized.
daemonize no

# When running daemonized, Redis Sentinel writes a pid file in
# /var/run/redis-sentinel.pid by default. You can specify a custom pid file
# location here.
pidfile /var/run/redis-sentinel.pid

# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
# nothing (nothing is logged)
loglevel notice

# Specify the log file name. Also the empty string can be used to force
# Sentinel to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile ""

# To enable logging to the system logger, just set 'syslog-enabled' to yes,
# and optionally update the other syslog parameters to suit your needs.
# syslog-enabled no

# Specify the syslog identity.
# syslog-ident sentinel

# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7.
# syslog-facility local0

# sentinel announce-ip <ip>
# sentinel announce-port <port>
#
# The above two configuration directives are useful in environments where,
# because of NAT, Sentinel is reachable from outside via a non-local address.
#
# When announce-ip is provided, the Sentinel will claim the specified IP address
# in HELLO messages used to gossip its presence, instead of auto-detecting the
# local address as it usually does.
#
# Similarly when announce-port is provided and is valid and non-zero, Sentinel
# will announce the specified TCP port.
#
# The two options don't need to be used together, if only announce-ip is
# provided, the Sentinel will announce the specified IP and the server port
# as specified by the "port" option. If only announce-port is provided, the
# Sentinel will announce the auto-detected local IP and the specified port.
#
# Example:
#
# sentinel announce-ip 1.2.3.4

# dir <working-directory>
# Every long running process should have a well-defined working directory.
# For Redis Sentinel to chdir to /tmp at startup is the simplest thing
# for the process to don't interfere with administrative tasks such as
# unmounting filesystems.
dir /tmp

# sentinel monitor <master-name> <ip> <redis-port> <quorum>
#
# Tells Sentinel to monitor this master, and to consider it in O_DOWN
# (Objectively Down) state only if at least <quorum> sentinels agree.
#
# Note that whatever is the ODOWN quorum, a Sentinel will require to
# be elected by the majority of the known Sentinels in order to
# start a failover, so no failover can be performed in minority.
#
# Replicas are auto-discovered, so you don't need to specify replicas in
# any way. Sentinel itself will rewrite this configuration file adding
# the replicas using additional configuration options.
# Also note that the configuration file is rewritten when a
# replica is promoted to master.
#
# Note: master name should not include special characters or spaces.
# The valid charset is A-z 0-9 and the three characters ".-_".
sentinel monitor m6379 192.168.137.144 6379 2

# sentinel auth-pass <master-name> <password>
#
# Set the password to use to authenticate with the master and replicas.
# Useful if there is a password set in the Redis instances to monitor.
#
# Note that the master password is also used for replicas, so it is not
# possible to set a different password in masters and replicas instances
# if you want to be able to monitor these instances with Sentinel.
#
# However you can have Redis instances without the authentication enabled
# mixed with Redis instances requiring the authentication (as long as the
# password set is the same for all the instances requiring the password) as
# the AUTH command will have no effect in Redis instances with authentication
# switched off.
#
# Example:
#
sentinel auth-pass m6379 123456

# sentinel auth-user <master-name> <username>
#
# This is useful in order to authenticate to instances having ACL capabilities,
# that is, running Redis 6.0 or greater. When just auth-pass is provided the
# Sentinel instance will authenticate to Redis using the old "AUTH <pass>"
# method. When also an username is provided, it will use "AUTH <user> <pass>".
# In the Redis servers side, the ACL to provide just minimal access to
# Sentinel instances, should be configured along the following lines:
#
#     user sentinel-user >somepassword +client +subscribe +publish \
#                        +ping +info +multi +slaveof +config +client +exec on

# sentinel down-after-milliseconds <master-name> <milliseconds>
#
# Number of milliseconds the master (or any attached replica or sentinel) should
# be unreachable (as in, not acceptable reply to PING, continuously, for the
# specified period) in order to consider it in S_DOWN state (Subjectively
# Down).
#
# Default is 30 seconds.
sentinel down-after-milliseconds m6379 30000

# IMPORTANT NOTE: starting with Redis 6.2 ACL capability is supported for
# Sentinel mode, please refer to the Redis website https://redis.io/topics/acl
# for more details.

# Sentinel's ACL users are defined in the following format:
#
#   user <username> ... acl rules ...
#
# For example:
#
#   user worker +@admin +@connection ~* on >ffa9203c493aa99
#
# For more information about ACL configuration please refer to the Redis
# website at https://redis.io/topics/acl and redis server configuration 
# template redis.conf.

# ACL LOG
#
# The ACL Log tracks failed commands and authentication events associated
# with ACLs. The ACL Log is useful to troubleshoot failed commands blocked 
# by ACLs. The ACL Log is stored in memory. You can reclaim memory with 
# ACL LOG RESET. Define the maximum entry length of the ACL Log below.
acllog-max-len 128

# Using an external ACL file
#
# Instead of configuring users here in this file, it is possible to use
# a stand-alone file just listing users. The two methods cannot be mixed:
# if you configure users here and at the same time you activate the external
# ACL file, the server will refuse to start.
#
# The format of the external ACL user file is exactly the same as the
# format that is used inside redis.conf to describe users.
#
# aclfile /etc/redis/sentinel-users.acl

requirepass 123456
#
# You can configure Sentinel itself to require a password, however when doing
# so Sentinel will try to authenticate with the same password to all the
# other Sentinels. So you need to configure all your Sentinels in a given
# group with the same "requirepass" password. Check the following documentation
# for more info: https://redis.io/topics/sentinel
#
# IMPORTANT NOTE: starting with Redis 6.2 "requirepass" is a compatibility
# layer on top of the ACL system. The option effect will be just setting
# the password for the default user. Clients will still authenticate using
# AUTH <password> as usually, or more explicitly with AUTH default <password>
# if they follow the new protocol: both will work.
#
# New config files are advised to use separate authentication control for
# incoming connections (via ACL), and for outgoing connections (via
# sentinel-user and sentinel-pass) 
#
# The requirepass is not compatible with aclfile option and the ACL LOAD
# command, these will cause requirepass to be ignored.

# sentinel sentinel-user <username>
#
# You can configure Sentinel to authenticate with other Sentinels with specific
# user name. 

# sentinel sentinel-pass <password>
#
# The password for Sentinel to authenticate with other Sentinels. If sentinel-user
# is not configured, Sentinel will use 'default' user with sentinel-pass to authenticate.

# sentinel parallel-syncs <master-name> <numreplicas>
#
# How many replicas we can reconfigure to point to the new replica simultaneously
# during the failover. Use a low number if you use the replicas to serve query
# to avoid that all the replicas will be unreachable at about the same
# time while performing the synchronization with the master.
sentinel parallel-syncs m6379 1

# sentinel failover-timeout <master-name> <milliseconds>
#
# Specifies the failover timeout in milliseconds. It is used in many ways:
#
# - The time needed to re-start a failover after a previous failover was
#   already tried against the same master by a given Sentinel, is two
#   times the failover timeout.
#
# - The time needed for a replica replicating to a wrong master according
#   to a Sentinel current configuration, to be forced to replicate
#   with the right master, is exactly the failover timeout (counting since
#   the moment a Sentinel detected the misconfiguration).
#
# - The time needed to cancel a failover that is already in progress but
#   did not produced any configuration change (SLAVEOF NO ONE yet not
#   acknowledged by the promoted replica).
#
# - The maximum time a failover in progress waits for all the replicas to be
#   reconfigured as replicas of the new master. However even after this time
#   the replicas will be reconfigured by the Sentinels anyway, but not with
#   the exact parallel-syncs progression as specified.
#
# Default is 3 minutes.
sentinel failover-timeout m6379 180000

# SCRIPTS EXECUTION
#
# sentinel notification-script and sentinel reconfig-script are used in order
# to configure scripts that are called to notify the system administrator
# or to reconfigure clients after a failover. The scripts are executed
# with the following rules for error handling:
#
# If script exits with "1" the execution is retried later (up to a maximum
# number of times currently set to 10).
#
# If script exits with "2" (or an higher value) the script execution is
# not retried.
#
# If script terminates because it receives a signal the behavior is the same
# as exit code 1.
#
# A script has a maximum running time of 60 seconds. After this limit is
# reached the script is terminated with a SIGKILL and the execution retried.

# NOTIFICATION SCRIPT
#
# sentinel notification-script <master-name> <script-path>
# 
# Call the specified notification script for any sentinel event that is
# generated in the WARNING level (for instance -sdown, -odown, and so forth).
# This script should notify the system administrator via email, SMS, or any
# other messaging system, that there is something wrong with the monitored
# Redis systems.
#
# The script is called with just two arguments: the first is the event type
# and the second the event description.
#
# The script must exist and be executable in order for sentinel to start if
# this option is provided.
#
# Example:
#
# sentinel notification-script mymaster /var/redis/notify.sh

# CLIENTS RECONFIGURATION SCRIPT
#
# sentinel client-reconfig-script <master-name> <script-path>
#
# When the master changed because of a failover a script can be called in
# order to perform application-specific tasks to notify the clients that the
# configuration has changed and the master is at a different address.
# 
# The following arguments are passed to the script:
#
# <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>
#
# <state> is currently always "start"
# <role> is either "leader" or "observer"
# 
# The arguments from-ip, from-port, to-ip, to-port are used to communicate
# the old address of the master and the new address of the elected replica
# (now a master).
#
# This script should be resistant to multiple invocations.
#
# Example:
#
# sentinel client-reconfig-script mymaster /var/redis/reconfig.sh

# SECURITY
#
# By default SENTINEL SET will not be able to change the notification-script
# and client-reconfig-script at runtime. This avoids a trivial security issue
# where clients can set the script to anything and trigger a failover in order
# to get the program executed.

sentinel deny-scripts-reconfig yes

# REDIS COMMANDS RENAMING (DEPRECATED)
#
# WARNING: avoid using this option if possible, instead use ACLs.
#
# Sometimes the Redis server has certain commands, that are needed for Sentinel
# to work correctly, renamed to unguessable strings. This is often the case
# of CONFIG and SLAVEOF in the context of providers that provide Redis as
# a service, and don't want the customers to reconfigure the instances outside
# of the administration console.
#
# In such case it is possible to tell Sentinel to use different command names
# instead of the normal ones. For example if the master "mymaster", and the
# associated replicas, have "CONFIG" all renamed to "GUESSME", I could use:
#
# SENTINEL rename-command mymaster CONFIG GUESSME
#
# After such configuration is set, every time Sentinel would use CONFIG it will
# use GUESSME instead. Note that there is no actual need to respect the command
# case, so writing "config guessme" is the same in the example above.
#
# SENTINEL SET can also be used in order to perform this configuration at runtime.
#
# In order to set a command back to its original name (undo the renaming), it
# is possible to just rename a command to itself:
#
# SENTINEL rename-command mymaster CONFIG CONFIG

# HOSTNAMES SUPPORT
#
# Normally Sentinel uses only IP addresses and requires SENTINEL MONITOR
# to specify an IP address. Also, it requires the Redis replica-announce-ip
# keyword to specify only IP addresses.
#
# You may enable hostnames support by enabling resolve-hostnames. Note
# that you must make sure your DNS is configured properly and that DNS
# resolution does not introduce very long delays.
#
# SENTINEL resolve-hostnames no

# When resolve-hostnames is enabled, Sentinel still uses IP addresses
# when exposing instances to users, configuration files, etc. If you want
# to retain the hostnames when announced, enable announce-hostnames below.
#
# SENTINEL announce-hostnames no

# When master_reboot_down_after_period is set to 0, Sentinel does not fail over
# when receiving a -LOADING response from a master. This was the only supported
# behavior before version 7.0.
#
# Otherwise, Sentinel will use this value as the time (in ms) it is willing to
# accept a -LOADING response after a master has been rebooted, before failing
# over.

# SENTINEL master-reboot-down-after-period m6379 0

启动哨兵

命令行

redis-server /etc/redis/redis_26379.conf --sentinel

root@iml6yu-machine:~# redis-server /etc/redis/redis_26379.conf --sentinel
8492:X 03 Jan 2024 15:39:49.976 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
8492:X 03 Jan 2024 15:39:49.976 # Redis version=6.0.16, bits=64, commit=00000000, modified=0, pid=8492, just started
8492:X 03 Jan 2024 15:39:49.976 # Configuration loaded
8492:X 03 Jan 2024 15:39:49.977 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 6.0.16 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in sentinel mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 26379
 |    `-._   `._    /     _.-'    |     PID: 8492
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

8492:X 03 Jan 2024 15:39:49.979 # Sentinel ID is 3517ce0738b45fb448ba9fb4c28500c248af3c59
8492:X 03 Jan 2024 15:39:49.979 # +monitor master m6379 192.168.137.144 6379 quorum 2

如果在单机上开启多个哨兵,需要修改redis-server后面的配置文件就可以了

C# 客户端使用StackExchange.Redis连接哨兵并且进行操作

连接哨兵的代码

  private ConfigurationOptions configuration;

  public ConnectionMultiplexer sentinelConnection { get; private set; }

  private void button1_Click(object sender, EventArgs e)
  {

      configuration = new ConfigurationOptions
      {
          EndPoints = {
              {"192.168.137.144",26379 },
              {"192.168.137.144",26381 },
              {"192.168.137.144", 26380}
          },
          //ServiceName = "m6379",
          Password = "123456",
          CommandMap = CommandMap.Sentinel,
          AbortOnConnectFail = false,
      };
      sentinelConnection = ConnectionMultiplexer.Connect(configuration);

      // 添加 ConnectionFailed 和 ConnectionRestored 事件处理程序
      sentinelConnection.ConnectionFailed += (sender, args) =>
      {
          // 处理连接失败的逻辑
          // 重新配置 ConnectionMultiplexer
          this.Invoke(new Action(() =>
          {
              richTextBox1.AppendText("连接失败\n");
              richTextBox1.AppendText($"sender:{JsonSerializer.Serialize(sender)}\n");
              richTextBox1.AppendText($"args:{JsonSerializer.Serialize(args)}\n");
          }));
      };

      sentinelConnection.ConnectionRestored += (sender, args) =>
      {
          // 处理连接恢复的逻辑
          // 重新配置 ConnectionMultiplexer
          this.Invoke(new Action(() =>
          {
              richTextBox1.AppendText("恢复连接\n");
              richTextBox1.AppendText($"sender:{JsonSerializer.Serialize(sender)}\n");
              richTextBox1.AppendText($"args:{JsonSerializer.Serialize(args)}\n");
          }));
      };



      // 订阅 +switch-master 频道
      var subscriber = sentinelConnection.GetSubscriber();
      subscriber.Subscribe("+switch-master", (channel, message) =>
      {
          // 处理主节点故障转移的逻辑
          // 重新配置 ConnectionMultiplexer
          this.Invoke(new Action(() =>
          {
              richTextBox1.AppendText("节点切换\n");
              richTextBox1.AppendText($"channel:{JsonSerializer.Serialize(channel)}\n");
              richTextBox1.AppendText($"message:{JsonSerializer.Serialize(message)}\n");
          }));
      });


  }

连接Master进行读写操作

 private void button2_Click(object sender, EventArgs e)
 {
     var redisConnection = sentinelConnection.GetSentinelMasterConnection(new ConfigurationOptions()
     {
         ServiceName = "m6379",
         Password = "123456",
         AbortOnConnectFail = true
     });
     var db = redisConnection.GetDatabase(0);
     db.StringSet("now_time", DateTime.Now.ToString());
     richTextBox1.AppendText(db.StringGet("hello").ToString() + "\n"); 
 }

注意事项:

  • master切换的时候读写操作会出现异常,所以在实际使用过程中要注意try catch

读写分离操作

目前没有找到比较好的办法,通过以下这个方法能够实现区分master和slave

  private void button3_Click(object sender, EventArgs e)
  {
      //master连接,可以是一个全局变量,通过哨兵的subscriber.Subscribe("+switch-master",通知进行更改
      var redisConnection = sentinelConnection.GetSentinelMasterConnection(new ConfigurationOptions()
      {
          ServiceName = "m6379",
          Password = "123456",
          AbortOnConnectFail = true, 
      });
      //获取master的所有服务,相当于包括master和slave
      //这里有一个问题就是会把内部的server也获取到,比实际的数据节点多
      var servies = redisConnection.GetServers();
      foreach(var s in servies)
      {
          richTextBox1.AppendText( s.IsReplica + "\n");
          //如果IsReplica=true表示是slave,否则是master
          //下面这段代码就是从节点读取,master节点写入
          if (s.IsReplica)
          {  
              richTextBox1.AppendText(s.Execute("GEt", "now_time").ToString() + $" by {s.EndPoint.ToString()}\n");
               
          }
          else if(s.IsConnected) 
          {
              s.Execute($"SET", "now_time",DateTime.Now.ToString()+s.EndPoint.ToString());
          }
      } 
  }

发布与订阅

发布与订阅目前都是通过master实现的,并不能基于哨兵进行发布订阅。必须得到master的连接。当master切换后,之前的发布与订阅依旧生效,不需要做多余的操作。

  private void button4_Click(object sender, EventArgs e)
  {
      var redisConnection = sentinelConnection.GetSentinelMasterConnection(new ConfigurationOptions()
      {
          ServiceName = "m6379",
          Password = "123456",
          AbortOnConnectFail = true,
      });
      var sub = redisConnection.GetSubscriber();
      sub.Subscribe(new RedisChannel("Test", RedisChannel.PatternMode.Literal), (channel, message) =>
      {
          this.Invoke(new Action(() =>
          {
              richTextBox1.AppendText("订阅Test收到消息\n");
              richTextBox1.AppendText($"channel:{JsonSerializer.Serialize(channel)}\n");
              richTextBox1.AppendText($"message:{JsonSerializer.Serialize(message)}\n");
          }));
      });
      richTextBox1.AppendText("已经订阅Test!\n");
  }

  private void button5_Click(object sender, EventArgs e)
  {
      var redisConnection = sentinelConnection.GetSentinelMasterConnection(new ConfigurationOptions()
      {
          ServiceName = "m6379",
          Password = "123456",
          AbortOnConnectFail = true,
      });
      var sub = redisConnection.GetSubscriber();
      sub.Publish(new RedisChannel("Test", RedisChannel.PatternMode.Literal), DateTime.Now.ToString() + " this message from sub publish!");
      richTextBox1.AppendText("发送消息成功!\n");
  }
文章来源:https://blog.csdn.net/iml6yu/article/details/135384261
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。