Home> System Tutorial> LINUX> body text

Redis high availability practice

WBOY
Release: 2024-08-20 16:51:04
Original
919 people have browsed it
0×01 Foreword

Redis is an open source log-type Key-Value database written in ANSI C language, supports network, can be memory-based and persistent, and provides APIs in multiple languages.

Nowadays, Internet business data is growing at a faster rate, and data types are becoming more and more abundant, which puts forward higher requirements for data processing speed and capabilities. Redis is an open source in-memory non-relational database that brings a disruptive experience to developers. Designed from start to finish with high performance in mind, Redis is the fastest NoSQL database available today.

While considering high performance, high availability is also an important consideration. The Internet provides 7×24 uninterrupted service and Failover at the fastest speed during a failure, which can bring minimal losses to the enterprise.

So, what are the high-availability architectures in practical applications? What are the pros and cons between the architectures? How should we choose? What are some best practices?

0×02 Sentinel Principle

Before explaining the Redis high availability solution, let’s first take a look at theRedis Sentinel principle.

  1. The Sentinel cluster discovers the master through the given configuration file and monitors the master when it starts. Obtain all slave servers under this server by sending info information to the master.
  2. The Sentinel cluster sends hello information (once per second) to the monitored master and slave servers through command connections. This information includes the Sentinel's own IP, port, id, etc., in order to announce its existence to other Sentinels.
  3. The Sentinel cluster receives hello information sent by other Sentinels through subscription connections to discover other Sentinels monitoring the same master server; clusters will create command connections with each other for communication, because there are already master-slave servers that send and receive hello No subscription connection is created between Sentinel and Sentinel.
  4. The Sentinel cluster uses the ping command to detect the status of the instance. If there is no reply within the specified time (down-after-milliseconds) or an incorrect reply is returned, the instance is judged to be offline.
  5. When the failover active/standby switchover is triggered, the failover will not proceed immediately. It will also require the authorization of the majority of Sentinels in the Sentinel before the failover can be carried out. That is, the Sentinel that performs the failover will obtain the authorization of the designated quorum Sentinels. After success, Enter ODOWN state. For example, if 2 quorums are configured among 5 Sentinels, failover will be executed when the 2 Sentinels think that the master is dead.
  6. Sentinel sends the SLAVEOF NO ONE command to the slave selected as the master. The condition for selecting the slave is that Sentinel will first sort the slaves according to their priorities. The smaller the priority, the higher the ranking. If the priorities are the same, check the replication subscript, whichever one receives more replication data from the master will be ranked first. If the priority and index are the same, the one with the smaller process ID is selected.
  7. After Sentinel is authorized, it will obtain the latest configuration version number (config-epoch) of the failed master. When the failover execution is completed, this version number will be used for the latest configuration and notify others through broadcast Sentinel, other Sentinels update the configuration of the corresponding master.

1 to 3 are automatic discovery mechanisms:

  • Send the info command to the monitored master every 10 seconds and obtain the current master information based on the reply.
  • Send PING commands to all redis servers, including Sentinel, at a frequency of 1 second, and determine whether the server is online through the reply.
  • Send current Sentinel master information messages to all monitored master and slave servers at a frequency of 2 seconds.

4 is the detection mechanism, 5 and 6 are failover mechanisms, and 7 is the update configuration mechanism. [1]

0×03 Redis high availability architecture

After explaining the principle of Redis Sentinel, let’s explain the commonly usedRedis high-availability architecture.

  • Redis Sentinel cluster + intranet DNS + custom script
  • Redis Sentinel Cluster + VIP + Custom Script
  • Encapsulate the client to directly connect to the Redis Sentinel port
    • JedisSentinelPool, suitable for Java
    • PHP is self-packaged based on phpredis
  • Redis Sentinel Cluster + Keepalived/Haproxy
  • Redis M/S + Keepalived
  • Redis Cluster
  • Twemproxy
  • Codis

The following will be explained one by one with pictures and text.

3.1 Redis Sentinel Cluster + Intranet DNS + Custom Script

Redis high availability practice

The picture above is a solution that has been applied in an online environment. The bottom layer is the Redis Sentinel cluster, which acts as an agent for the Redis master and slave. The Web side connects to the intranet DNS to provide services. Intranet DNS is allocated according to certain rules, such asxxxx.redis.cache/queue.port.xxx.xxx. The first segment indicates the business abbreviation, the second segment indicates that this is the Redis intranet domain name, and the third segment Represents the Redis type, cache represents the cache, queue represents the queue, the fourth segment represents the Redis port, and the fifth and sixth segments represent the main domain name of the intranet.

When the master node fails, such as machine failure, Redis node failure, or network unreachability, the Sentinel cluster will call theclient-reconfig-scriptconfigured script to modify the intranet domain name of the corresponding port. The intranet domain name of the corresponding port points to the new Redis master node.

Advantages:

  • Second-level switching, complete the entire switching operation within 10s
  • Script customization and controllable architecture
  • Transparent to the application, the front end does not have to worry about changes in the back end

Disadvantages:

  • The maintenance cost is slightly high. It is recommended to invest in more than 3 machines for the Redis Sentinel cluster
  • Depends on DNS, there is resolution delay
  • Sentinel mode service will be unavailable for a short period of time
  • This solution cannot be used if the service is accessed through the external network
3.2 Redis Sentinel Cluster + VIP + Custom Script

Redis high availability practice

This plan is slightly different from the previous one. The first solution uses the intranet DNS, and the second solution replaces the intranet DNS with a virtual IP. The bottom layer is the Redis Sentinel cluster, which acts as an agent for Redis master and slave, and the Web side provides services through VIP. When deploying Redis master-slave, you need to bind the virtual IP to the current Redis master node. When the master node fails, such as machine failure, Redis node failure, or network unreachability, the Sentinel cluster will call the script configured byclient-reconfig-scriptto float the VIP to the new master node.

Advantages:

  • Second-level switching, complete the entire switching operation within 5s
  • Script customization and controllable architecture
  • Transparent to the application, the front end does not have to worry about changes in the back end

Disadvantages:

  • The maintenance cost is slightly high. It is recommended to invest in more than 3 machines for the Redis Sentinel cluster
  • Using VIP increases maintenance costs and risks IP chaos
  • Sentinel mode service will be unavailable for a short period of time
3.3 Encapsulate the client to directly connect to the Redis Sentinel port

Redis high availability practice

일부 기업에서는 외부 네트워크를 통해서만 Redis에 액세스할 수 있습니다. 위의 두 가지 솔루션 중 어느 것도 사용할 수 없으므로 이 솔루션이 파생되었습니다. 웹은 클라이언트를 사용하여 Redis Sentinel 클러스터 중 하나에 있는 시스템의 특정 포트에 연결한 후 이 포트를 통해 현재 마스터 노드를 얻은 다음 실제 Redis 마스터 노드에 연결하여 해당 세일즈맨 작업을 수행합니다. Redis Sentinel 포트와 Redis 마스터 노드 모두 개방형 액세스가 필요하다는 점에 유의하는 것이 중요합니다. 프론트엔드 업무가 Java를 사용한다면 JedisSentinelPool을 재사용할 수 있고, 프론트엔드 업무가 PHP를 사용한다면 phpredis를 기반으로 2차 캡슐화가 가능합니다.

장점:

  • 서비스는 즉시 결함을 감지합니다
  • DBA 유지관리 비용이 저렴합니다

단점:

  • 클라이언트 지원에 따라 다름 Sentinel
  • Sentinel 서버 및 Redis 노드에는 공개 액세스가 필요합니다
  • 애플리케이션에 방해가 됨
3.4 Redis Sentinel 클러스터 + Keepalived/Haproxy

Redis high availability practice

하위 레이어는 Redis 마스터와 슬레이브의 에이전트 역할을 하는 Redis Sentinel 클러스터이며, 웹 측은 VIP를 통해 서비스를 제공합니다. 머신 장애, Redis 노드 장애, 네트워크 연결 불가 등 마스터 노드 장애 시 Redis Sentinel의 내부 메커니즘에 의해 Redis 간 전환이 보장되고, Keepalived에 의해 VIP 전환이 보장됩니다.

장점:

  • 단 몇 초 만에 전환
  • 애플리케이션에 투명함

단점:

  • 높은 유지비용
  • 분할뇌
  • 센티넬 모드 서비스가 잠시 중단됩니다
3.5 Redis M/S + Keepalived

Redis high availability practice

이 솔루션은 Redis Sentinel을 사용하지 않습니다. 이 솔루션은 기본 마스터-슬레이브를 사용하며 Keepalived를 통해 VIP 전환이 보장됩니다. Redis 마스터-슬레이브 간 전환에는 사용자 지정 스크립트가 필요합니다.

장점:

  • 단 몇 초 만에 전환
  • 애플리케이션에 투명함
  • 간단한 배포 및 낮은 유지 관리 비용

단점:

  • 전환 기능을 구현하려면 스크립트가 필요합니다
  • 분할뇌
3.6 Redis 클러스터

Redis high availability practice

출처: http://intro2libsys.com/focused-redis-topics/day-one/intro-redis-cluster

Redis 3.0.0은 2년여 전인 2015년 4월 2일에 공식 출시되었습니다. Redis 클러스터는 P2P 모드를 채택하고 중앙 집중화되지 않습니다. 키를 16384개의 슬롯으로 나누고 각 인스턴스가 슬롯의 일부를 담당합니다. 클라이언트는 해당 데이터를 요청하며, 인스턴스 슬롯에 해당 데이터가 없으면 해당 인스턴스로 인스턴스를 전달합니다. 또한 Redis 클러스터는 Gossip 프로토콜을 통해 노드 정보를 동기화합니다.

장점:

  • 구성 요소가 일체형으로 구성되어 배포가 쉽고 기계 리소스가 절약됩니다
  • 프록시 모드보다 성능이 더 좋습니다
  • 슬롯 마이그레이션 중에 자동 장애 조치 및 데이터 사용 가능
  • 공식 기본 클러스터 솔루션, 보장된 업데이트 및 지원

단점:

  • 아키텍처는 비교적 새롭고 모범 사례가 거의 없습니다
  • 다중키 조작 지원은 제한적입니다(운전자는 곡선을 통해 나라를 구할 수 있습니다)
  • 성능 향상을 위해 클라이언트는 라우팅 테이블 정보를 캐시해야 합니다
  • 노드 검색 및 리샤딩 작업이 충분히 자동화되지 않았습니다
3.7 트웸프록시

Redis high availability practice

출처: http://engineering.bloomreach.com/the-evolution-of-fault-tolerant-redis-cluster

다중 동형 Twemproxy(동일 구성)는 동시에 작동하며 클라이언트 요청을 수락하고 해시 알고리즘에 따라 해당 Redis로 전달합니다.

Twemproxy 솔루션은 비교적 성숙한 솔루션입니다. 우리 팀은 오래전부터 이 솔루션을 사용해왔지만 효과는 그다지 만족스럽지 않습니다. 한편으로는 위치 지정 문제가 더 어렵고, 다른 한편으로는 노드 자동 제거에 대한 지원이 그리 우호적이지 않습니다.

장점:

  • 개발하기 쉽고 애플리케이션에 거의 투명함
  • 오랜 역사, 성숙한 솔루션

단점:

  • 프록시가 성능에 영향을 미침
  • LVS와 Twemproxy는 노드 성능 병목 현상을 겪게 됩니다
  • Redis 확장이 너무 귀찮다
  • Twitter는 내부적으로 이 솔루션의 사용을 포기했으며 새로운 아키텍처는 오픈 소스가 아닙니다
3.8코디스

Redis high availability practice

출처: https://github.com/CodisLabs/codis

Codis는 Wandoujia의 오픈 소스 제품이며 그 중 ZooKeeper는 라우팅 테이블과 에이전트 노드 메타데이터를 저장하고 Codis-Config 명령을 배포합니다. Codis-Config는 사용 가능한 웹 인터페이스가 있는 통합 관리 도구입니다. ; Codis -Proxy는 Redis 프로토콜과 호환되는 상태 비저장 프록시입니다. Codis-Redis는 Redis 2.8 버전을 기반으로 한 보조 개발로, 데이터 마이그레이션을 용이하게 하기 위해 슬롯 지원을 추가합니다.

장점:

  • 개발하기 쉽고 애플리케이션에 거의 투명함
  • Twemproxy보다 성능이 더 좋습니다
  • 그래픽 인터페이스, 손쉬운 확장, 편리한 운영 및 유지 관리

단점:

  • 프록시는 여전히 성능에 영향을 미칩니다
  • 부품이 너무 많고 기계 자원도 많이 필요
  • Redis 코드가 수정되어 정식 동기화가 불가능하고, 새로운 기능의 후속 조치가 느립니다
  • 개발팀에서는 Redis Transformation을 기반으로 reborndb 홍보를 준비 중입니다
0×04 모범 사례

소위 모범 사례는 특정 시나리오에 가장 적합한 사례입니다.

에서는 주로 다음 플랜을 권장합니다.

  • Redis 센티널 클러스터 + 인트라넷 DNS + 사용자 정의 스크립트
  • Redis Sentinel 클러스터 + VIP + 사용자 정의 스크립트

실제 전투 중 모범 사례를 정리하면 다음과 같습니다.

  • Redis Sentinel 클러스터는 5대 이상의 머신을 사용하는 것이 좋습니다
  • 다양한 대기업은 Redis Sentinel 클러스터를 사용하여 해당 기업의 모든 포트를 프록시할 수 있습니다
  • 업종별로 Redis 포트 범위 나누기
  • 손쉬운 확장을 위해 Python을 사용하여 사용자 정의 스크립트를 구현하는 것이 좋습니다
  • 현재 Sentinel 역할을 결정하려면 사용자 정의 스크립트에 주의를 기울여야 합니다
  • 사용자 정의 스크립트 입력 매개변수:
  • 사용자 정의 스크립트에서는 시스템을 작동하려면 원격 SSH가 필요합니다. SSH 연결을 반복적으로 설정하고 시간을 소비하지 않으려면
  • paramiko라이브러리를 사용하는 것이 좋습니다.
  • SSH 연결 속도를 높이려면 다음 두 매개 변수를 끄는 것이 좋습니다
    • DNS 사용 안함
    • GSSAPI인증번호
  • Wechat 또는 이메일 알림, 메인 프로세스를 차단하지 않도록 프로세스를 포크하는 것이 좋습니다
  • 자동 전환 및 장애 조치, 모든 작업은 15초 이내에 완료하는 것이 좋습니다
0×05 요약
이번 이벤트에서는 Redis 고가용성의 필요성, Sentinel 원칙, Redis 고가용성의 공통 아키텍처 및 실제 전투 프로세스를 요약한 모범 사례를 공유했습니다. 커뮤니케이션을 시작하려면 내 WeChat(

Wentasy)을 추가하거나 다음 주소로 이메일을 보내세요:dbarobinwen@gmail.com

첨부된 PPT 다운로드: https://github.com/dbarobin/slides

비디오 재생: Redis 고가용성 아키텍처 모범 사례

0×06 감사의 인사
꼼꼼한 준비를 해주신 팅윤님과 운영관리팀, 그리고 폭우 속에서도 행사에 참여하기 위해 와주신 모든 분들께 감사드립니다. 이 공유는 IT 전문가가 녹화했으며 기술 지원을 해주신 IT 전문가에게 감사의 말씀을 전하고 싶습니다.

0×07 참고

[1] jyzhou(2016-06-12). Redis 복제, Sentinel 구성 및 원리 설명은 http://www.cnblogs.com/zhoujinyi/p/5570024.html.

에서 가져왔습니다.

The above is the detailed content of Redis high availability practice. For more information, please follow other related articles on the PHP Chinese website!

source:linuxprobe.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!