Redis dan High Availability dengan Redis Sentinel

Redis dan High Availability dengan Redis Sentinel

Redis adalah kependekan dari kata Remote Dictionary Server, sebagai penyimpanan data didalam memori. Karena proses Read/Write ke memori sangat cepat, biasanya redis digunakan sebagai cache dan message broker.

Gambar 1. Redis Sebagai Cache, sumber.

Gambar 2. Redis Pub/Sub, sebagai message queue

Instalasi Redis

Ada beberapa cara untuk meng-install redis, tapi disini kita akan menjalankan redis di dalam container menggunakan docker-compose.

Buatlah struktur folder seperti ini

redis
   ├── config
   │   └── master.conf
   ├── data
   │   └── master
   ├── docker-compose.yml

File redis configuration (master.conf) bisa diambil dari sini https://redis.io/docs/management/config-file/

Beberapa hal yang perlu diperhatikan pada file konfigurasi redis

  • requirepass : ini bisa diisi jika ingin menambahkan password saat menggunakan redis

  • bind : IP yang akan di-bind ke redis server, disini saya isi 0.0.0.0 agar dapat connect oleh siapapun

  • port : port yang akan digunakan

  • appendonly : untuk mengatur fitur data persistence, jika data persistence diaktifkan, redis akan melakukan write data ke harddisk (meng-copy data dari memori ke harddisk), misal jika redis mati dan hidup kembali, maka redis dapat mengambil data yang ada di harddisk untuk disimpan kembali didalam memori

Lanjut pada file docker-compose.yml isi sebagai berikut

version: "3.7"

services:
  redis_master:
    container_name: redis_master
    image: redis:6
    command: redis-server /usr/local/etc/redis/redis.conf
    ports:
      - 6379:6379
    volumes:
      - ./data/master:/data/
      - ./config/master.conf:/usr/local/etc/redis/redis.conf
    networks:
      static-network:
        ipv4_address: 172.20.128.2

networks:
  static-network:
    ipam:
      config:
        - subnet: 172.20.0.0/16
  • Volumes: bind data file config yang ada di local dengan file yang ada di dalam container

  • Port: 6379*<Port Docker Host>:6379<Port Didalam Container>*

  • Command: mengeksekusi perintah redis-server dengan konfigurasi yang telah dibuat

  • Network: dibuat hanya untuk mengambil static IP, agar lebih mudah untuk men-demokan clustering redis.

Selanjutnya, jalankan perintah docker-compose up -d --build pada root directory project redis, jika redis berhasil berjalan akan menampilkan pesan kurang lebih seperti ini

kita bisa masuk ke dalam container redis yang sudah berjalan, dengan menjalankan perintah docker exec -it redis_master sh , lalu buat koneksi ke redis-server via redis-cli dengan perintah redis-cli redis-cli -h 127.0.0.1 -p 6379

Di redis kita bisa membuat database dan menggunakan databasenya, namun sedikit berbeda, jika di relational database kita bisa membuat database dengan menggunakan nama database, di redis kita hanya bisa menggunakan angka sebagai database, secara default database di redis adalah 0 (nol).

select 0 berarti kita memilih database index ke-0

Konsep penyimpanan pada redis cukup simple, terdiri dari key dan value. Redis sebenarnya mendukung struktur data yang banyak, seperti String, List, Set, dan lain-lain, namun yang paling sering digunakan adalah struktur data String.

127.0.0.1:6379> setex firstName 120 Nauval   ==> menambahkan key baru (firstName), masa berlaku 2 menit (120s), dengan nilai "Nauval"
OK
127.0.0.1:6379> keys *                       ==> menampilkan semua keys
1) "firstName"
127.0.0.1:6379> get firstName                ==> melihat isi data key firstName
"Nauval"

Pub/Sub

Pola Pub/Sub alias Publish-Subscribe adalah pola yang didalamnya terdapat tiga komponen utama yaitu sender, receiver & broker.

Komunikasi diproses oleh broker, membantu sender atau publisher untuk mempublikasikan informasi dan menyampaikan informasi tersebut kepada receiver atau subcriber.

Pada tab kiri saya subscribe ke channel_nauval, sedangkan di tab kanan saya publish message ke channel_nauval. Respon di-tab kanan (integer) 1 ini berarti message berhasil dikirim ke 1 subscriber dan subscriber menerima pesan yang dikirim oleh publisher (tab kiri).

Repository: https://bitbucket.org/nauvalsh/redis-sentinel


Berikut beberapa fitur / command pada redis cli yang bisa kalian pelajari

Redis Important Comands / Strings
     - INFO: Return informations and statistics about the server in a format that is simple to parse by computers and easy to read by humans
     - KEYS: Returns all keys matching pattern
     - SET: Add/update a record
     - GET: Gets a single record
     - EXISTS: Returns if a record exists or not (0 or 1)
     - EXPIRE: Set a timeout on a key. After the timeout has expired, the key will automatically be deleted
     - TTL: Returns the remaining time to live of a key that has a timeout
     - SETEX: Equivalent to executing SET and EXPIRE
     - SETNX: Set a single record if not exists
     - INCR: Increment a number by 1
     - INCRBY: Increment by a different number
     - DECR: Decrement by 1
     - DECRBY: Decrement by a different number
     - APPEND: Appends the value at the end of a string
     - MGET: Gets multiple records
     - MSET: Sets multiple record
     - DEL: Delete one or multiple records
Redis Important Comands / Hashes
     - HSET: Sets field in the hash stored at key to value
     - HGET: Returns the value associated with field in the hash stored at key.
     - HMGET: Returns the multiple values associated with field in the hash stored at key.
     - HMSET: Sets multiple values associated with field in the hash stored at key.
     - HGETALL: Returns all fields and values of the hash stored at key
     - HINCRBY: Increment by a different number
     - HDECRBY: Decrement by a different number
Redis Important Comands / Sets
     - SADD: Add the specified members to the set stored at key. Specified members that are already a member of this set are ignored
     - SMEMBERS: Returns all the members of the set
     - SCARD: Returns the set cardinality (number of elements)
     - SISMEMBER: Returns if member is a member of the set stored at key.
     - SREM: Remove the specified members from the set stored at key
Redis Important Comands / Sorted Sets
     - ZADD: Adds specified members with the specified scores to the sorted set
     - ZRANGE: Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score
     - ZREM: Removes the specified members from the sorted set stored at key. Non existing members are ignored.
     - ZSCORE: Returns the score of member in the sorted set at key.
Redis Important Comands / Pub-Sub
     - PUBLISH: Posts a message to the given channel.
     - SUBSCRIBE: Subscribes the client to the specified channels.
Redis Important Comands / Transactions
     - MULTI: Marks the start of a transaction block. Subsequent commands will be queued for atomic execution using EXEC.
     - EXEC: Executes all previously queued commands in a transaction.
     - DISCARD: Flushes all previously queued commands in a transaction.
Redis Important Comands / Connection
     - AUTH: Request for authentication in a password-protected Redis server.
     - PING: used to test if a connection is still alive, or to measure latency. Returns PONG if no argument is provided, otherwise return a copy of the argument as a bulk.
     - SELECT: Selectable Redis databases are a form of namespacing.

Redis Sentinel

Redis Sentinel menyediakan High Availability untuk redis ketika tidak menggunakan Redis Cluster

High Availability (HA) adalah sebuah konsep pada infrastruktur yang dapat menjamin pelayanan server dengan level tinggi dan sesuai dengan ketepatan waktu.

HA banyak digunakan untuk sektor tertentu, seperti High Availability Web Server, Database, dan lain-lain.

Teknik penerapan atau implementasi HA digabungkan dengan metode Failover, yaitu ketika ada salah satu server pada node cluster yang sama sedang mengalami masalah, secepat mungkin server lainnya akan mengambil alih traffic tersebut, dan server yang sebelumnya mengalami masalah akan melakukan auto-healing atau perbaikan secara otomatis hingga siap melakukan backup seperti semula.

Selain menyediakan High Availability, Redis Sentinel juga menyediakan fitur lainnya seperti monitoring, notifications dan bertindak sebagai pengatur konfigurasi untuk client.

This is the full list of Sentinel capabilities at a macroscopic level (i.e. the big picture):

  • Monitoring. Sentinel constantly checks if your master and replica instances are working as expected.

  • Notification. Sentinel can notify the system administrator, or other computer programs, via an API, that something is wrong with one of the monitored Redis instances.

  • Automatic failover. If a master is not working as expected, Sentinel can start a failover process where a replica is promoted to master, the other additional replicas are reconfigured to use the new master, and the applications using the Redis server are informed about the new address to use when connecting.

  • Configuration provider. Sentinel acts as a source of authority for clients service discovery: clients connect to Sentinels in order to ask for the address of the current Redis master responsible for a given service. If a failover occurs, Sentinels will report the new address.

Quorum

Quorum adalah jumlah sentinel yang dibutuhkan untuk mendeteksi apakah master masih aktif. Ketika quorum terpenuhi, maka prosedur failover akan dijalankan.

Misalnya, saya punya 5 sentinel, dan quorum yang diberikan 2, maka ini yang terjadi

  • Jika 2 sentinel menyetujui pada saat yang bersamaan bahwa master unreachable , salah satu sentinel akan memulai prosedur failover.

  • Jika terdapat 3 sentinel reachable, maka prosedur failover akan diotorisasi dan dijalankan.