Настройки серверов Redis для отказоустойчивой работы

Внимание!
Redis.Cluster для кэша в ELMA не используется!

Требуется настроить Redis мастер и несколько Redis слейв-серверов согласно статье "Использование кэша Redis в ELMA".

Также нужно настроить Redis sentinel architectother согласно документации https://redis.io/topics/sentinel.

Настройка Redis.sentinel

При настроенном Redis.sentinel в случае, если мастер сервер окажется нерабочим, то один из слейв-серверов будет переконфигурирован как мастер. Решение об этом принимает все запущенные Redis.sentinel сервера, набрав кворум (параметр sentinel monitor в конфигурации). После возврата мастер сервера он будет переконфигурирован как слейв.

Для настройки необходимо создать файл /etc/redis/redis.sentinel.conf на каждом из серверов:

# *** IMPORTANT ***
#

# By default Sentinel will not be reachable from interfaces different than

# localhost, either use the ’bind’ directive to bind to a list of network

# interfaces, or disable protected mode with "protected-mode no" by

# adding it to this configuration file.

#

# Before doing that MAKE SURE the instance is protected from the outside

# world via firewalling or other means.

#

# For example you may use one of the following:

#

bind 0.0.0.0

protected-mode no

 

# port <sentinel-port>

# The port that this sentinel instance will run on

port 16379

 

# By default Redis does not run as a daemon. Use ’yes’ if you need it.

# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.

daemonize yes

 

# Specify the log file name. Also the empty string can be used to force

# Redis 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 /var/log/redis/redis-sentinel.log

 

# 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.

#

# Slaves are auto-discovered, so you don’t need to specify slaves in

# any way. Sentinel itself will rewrite this configuration file adding

# the slaves using additional configuration options.

# Also note that the configuration file is rewritten when a

# slave 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 elma-redis your_redis_master_ip  6379 2

 

# sentinel auth-pass <master-name> <password>

#

# Set the password to use to authenticate with the master and slaves.

# Useful if there is a password set in the Redis instances to monitor.

#

# Note that the master password is also used for slaves, so it is not

# possible to set a different password in masters and slaves 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.

sentinel auth-pass elma-redis your_redis_password

 

# sentinel down-after-milliseconds <master-name> <milliseconds>

#

# Number of milliseconds the master (or any attached slave 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 elma-redis 30000

 

# 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 slave 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 slave).

#

# - The maximum time a failover in progress waits for all the slaves to be

#   reconfigured as slaves of the new master. However even after this time

#   the slaves will be reconfigured by the Sentinels anyway, but not with

#   the exact parallel-syncs progression as specified.

#

# Default is 3 minutes.

sentinel failover-timeout elma-redis 180000

bind 0.0.0.0 делает доступным сервис Redis.sentinel со всех внешних адресов.

  • Указать адрес и порт Мастера, а также значение для достижения кворума:

sentinel monitor elma-redis your_redis_master_ip 6379 2

  • Указать пароль для доступа к Мастеру:

sentinel auth-pass elma-redis your_redis_password

  • Создать папку /var/log/redis/ и настроить ей доступ;
  • Настроить привязки к сетевым интерфейсам. В общем случае используется protected-mode no;

    Внимание!
    При работе сервера sentinel файл конфигурации самого сервера и каждого из серверов Redis меняются, поэтому необходимо выдать права доступа на их перезапись.

Для настройки сервера sentinel как служба нужно создать фал /etc/init.d/redis-sentinel на каждом из серверов и настроить права доступа:

#!/bin/bash

# Start/Stop/restart script for Redis Sentinel

 

NAME=`basename ${0}`

EXEC=/usr/bin/redis-server

PIDFILE="/var/run/redis/${NAME}.pid"

CONF="/etc/redis/redis.sentinel.conf"

 

PID=`cat $PIDFILE 2> /dev/null`

case "$1" in

     start)

         echo "Starting $NAME ..."

         touch $PIDFILE

         exec $EXEC $CONF --sentinel --pidfile $PIDFILE

         ;;

     stop)

         echo "Stopping $NAME ..."

         kill -9 $PID

         ;;

     restart)

         echo "Restarting $NAME ..."

         $0 stop

         sleep 2

         $0 start

         ;;

     *)

         echo "Usage $0 {start|stop|restart}"

         ;;

esac
  •  EXEC=/usr/bin/redis-server или  /usr/local/bin/redis-server (исполняемое приложение redis-server, можно взять из файла /etc/init.d/redis-server)

Cоздать папку /var/run/redis, настроить ей доступ.

Зарегистрировать сервис: sudo systemctl unmask  redis-sentinel.service.

После этого запускается сервер sentinel на каждом из серверов:

sudo service redis-sentinel start

или

sudo redis-sentinel /etc/redis/redis.sentinel.conf

где /etc/redis/redis.sentinel.conf – путь к нужной конфигурации sentinel.

Примечание
Работа системы проверена на версии Redis 4.0.1.