0

Redis Server on CentOS 9/AlmaLinux 9 / RHEL 9

06.09.2023

Features of Redis

  • In-Memory Data structures: It is a well-known data structure with support for different data types including strings, lists, sets, hashes, streams, etc.
  • High Availability: Redis supports high availability and failover with replication. It uses asynchronous replication that uses low latency and ensures that instances of the replicas are exact copies of the master replicas. This happens as long as there is a link between the two and anytime the link breaks the replica automatically reconnects and tries to make an exact copy of the master.
  • Programmability: Redis provides a programming interface that allows you to execute custom scripts on the server. They include Running Scripts which consist of EVAL command that runs server-side scripts and Redis Functions for database elements.
  • Clustering: Redis scales horizontally with the use of the Redis Cluster that ensures data is automatically shared across multiple Redis nodes. It also provides the ability to continue running Redis in the event some subsets of nodes fail to communicate.
  • Extensibility: The use of Redis modules makes it easy to extend Redis Functionality by use of external modules. These include dynamic libraries that can be loaded into Redis at startup.
  • Persistence: As discussed above, you can use the Snapshot feature or AOF or both to make data persistent in Redis. You can also disable the functionality if you only want to use it for caching.

Common Use cases of Redis include; Real-time data storage, Caching storage, and streaming and messaging. This guide will show you how to Install and Configure Redis Server on CentOS 9|AlmaLinux 9|RHEL 9 systems.

Install Redis Server on CentOS 9 / AlmaLinux 9 / RHEL 9

Update your system packages.

sudo dnf update

Install Redis with the following command.

$ sudo dnf -y install redis

Dependencies resolved.
================================================================================
 Package        Architecture    Version                Repository          Size
================================================================================
Installing:
 redis          x86_64          6.2.7-1.el9            appstream          1.3 M

Transaction Summary
================================================================================

Start and enable the Redis server at boot.

sudo systemctl start redis
sudo systemctl enable redis

Check for the status of the service.

$ systemctl status redis
● redis.service - Redis persistent key-value database
     Loaded: loaded (/usr/lib/systemd/system/redis.service; enabled; vendor pre>
    Drop-In: /etc/systemd/system/redis.service.d
             └─limit.conf
     Active: active (running) since Tue 2022-06-21 00:04:58 EAT; 21s ago
   Main PID: 76716 (redis-server)
     Status: "Ready to accept connections"
      Tasks: 5 (limit: 23427)
     Memory: 7.3M
        CPU: 40ms
     CGroup: /system.slice/redis.service
             └─76716 "/usr/bin/redis-server 127.0.0.1:6379"

Verify that Redis is running with the following command. It should return PONG as a response if it is running.

$ redis-cli ping
PONG

Configure Redis Remote Access

Redis normally connects from localhost. To connect from a remote host, you would have to edit the Redis configuration file to bind your remote hs IP address. It is advisable to add a private IP address to decrease the exposure of the Redis interface to outside parties.

sudo vi /etc/redis/redis.conf

Add the following line with the private remote IP address to the file. (recommended)

bind 192.168.200.70

To allow all IP addresses use the following command.

bind 0.0.0.0

While still on the Redis file, you can secure your database with a password that will require clients to authenticate before accessing the database. Scroll to the security section to find the following line # requirepass foobared. Then uncomment the line by removing the # and changing the foobared to a stronger password.

requirepass Pass@Demo

Save and exit the file then restart Redis to apply changes.

$ sudo systemctl restart redis

If you have a firewall enabled on your system, you can configure it to allow access from remote machines to the Redis Server.

$ sudo firewall-cmd --permanent --add-port=6379/tcp
$ sudo firewall-cmd --reload

Access Redis Server using Redis-CLI

Access the Redis CLI using the following command

$ redis-cli

It will ask you for the password. Authenticate using your password

127.0.0.1:6379> auth Pass@Demo
OK

To get more information about the server uses the following command.

127.0.0.1:6379> info
# Server
redis_version:6.2.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:9664d239a7dd0d5e
redis_mode:standalone
os:Linux 5.14.0-70.13.1.el9_0.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:11.2.1
process_id:5844
process_supervised:systemd

To save data on a disk in the foreground, use the following command.

127.0.0.1:6379> save
OK

To save the data on a disk in the background, use the following command.

127.0.0.1:6379>  bgsave
Background saving started

To get the UNIX timestamp on the last save to the disk, use the following command.

127.0.0.1:6379> lastsave
(integer) 1655765038

To check clients that are connected, use the following command

127.0.0.1:6379> client list
id=224434 addr=192.168.200.70:44113 laddr=192.168.200.47:6379 fd=7 name= age=887 idle=0 flags=S db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20512 events=r cmd=replconf user=default redir=-1
id=224438 addr=127.0.0.1:39802 laddr=127.0.0.1:6379 fd=8 name= age=251 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=40928 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 events=r cmd=client user=default redir=-1

To kill a client connection, use the following command with the address of the IP address of the client.

127.0.0.1:6379> client kill 192.168.200.70 44113
OK

To save data on disk and shutdown reds, use the following command.

127.0.0.1:6379> shutdown

You can exit from the Redis-CLI with the quit command.

not connected> quit

Use Redis on Python 3

Enable EPEL Repository which will help in installing the python3 module.

If you have already enabled it, use the following command to install Python3

sudo dnf --enablerepo=epel -y install python3-redis

Create a python file and paste the following. For the Password field, change the password to the one you configured for the server machine.

$ vi use_redis.py
import redis

client = redis.StrictRedis(host='127.0.0.1', port=6379, db=0, password='Pass@Demo')

# set and get Key
client.set('key01', 'value01')
print('key01.value :', client.get('key01'))

# append and get Key
client.append('key01', ',value02')
print('key01.value :', client.get('key01'))

client.set('key02', 1)

# increment
client.incr('key02', 100)
print('key02.value :', client.get('key02'))

# decrement
client.decr("key02", 51)
print('key02.value :', client.get('key02'))

# list
client.lpush('list01', 'value01', 'value02', 'value03')
print('list01.value :', client.lrange('list01', '0', '2'))

# hash
client.hmset('hash01', {'key01': 'value01', 'key02': 'value02', 'key03': 'value03'})
print('hash01.value :', client.hmget('hash01', ['key01', 'key02', 'key03']))

# set
client.sadd('set01', 'member01', 'member02', 'member03')
print('set01.value :', client.smembers('set01'))

Run the file with the following command

$ python3 use_redis.py
key01.value : b'value01'
key01.value : b'value01,value02'
key02.value : b'101'
key02.value : b'50'
list01.value : [b'value03', b'value02', b'value01']
hash01.value : [b'value01', b'value02', b'value03']
set01.value : {b'member03', b'member01', b'member02'}

If you get a connection refused error, check the status of the Redis server and enable it to connect.

Configure Slave for replication

Install Redis using the same process above on a remote machine.

Edit the configuration file to configure the slave instance

sudo vi /etc/redis/redis.conf

Add replicaof directive with the Master IP address

replicaof 192.168.200.47 6379

As the Master has an authentication password, Find the following command and set the password

masterauth Pass@Demo

Save and exit the file then restart the Redis service to apply changes.

sudo systemctl restart redis

To verify remote access is set successfully, ping the Redis server from the remote host machine.$ redis-cli -h 192.168.200.47 ping PONG

Verify Master/Slave replication

On the Server machine login to Redis-CLI and authenticate with Password. To test replication, use the following command.

127.0.0.1:6379> set 'name' Technixleo
OK

Exit the connection.

Now go to the remote machine and login to Redis-CLI and execute the following command.

127.0.0.1:6379> get 'name'
"Technixleo"

This confirms that the master/slave replication works perfectly.

Conclusion

From this guide, we have gone through an overview of Redis Server and its capabilities. We have also seen how to install Redis on CentOS 9|AlmaLinux 9|RHEL 9 systems. We have also seen how to secure the database and enable remote access to the database. We have also seen that the Master/Slave replication works properly on Redis. Redis is the most popular caching tool and also doubles up as a database on its own for storing persistent data with Snapshot features.

Свежие комментарии

Подписка

Лучшие статьи


Fatal error: Uncaught Error: Call to a member function have_posts() on null in /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/blog.php:411 Stack trace: #0 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/widgets/latest-posts/widget.php(257): fox56_blog_grid(NULL, Array) #1 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/widgets/latest-posts/register.php(33): include('/home/host18670...') #2 /home/host1867038/the-devops.ru/htdocs/www/wp-includes/class-wp-widget.php(394): Wi_Widget_Latest_Posts->widget(Array, Array) #3 /home/host1867038/the-devops.ru/htdocs/www/wp-includes/widgets.php(845): WP_Widget->display_callback(Array, Array) #4 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/single.php(417): dynamic_sidebar('sidebar') #5 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/single.php(136): fox56_single_sidebar() #6 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/single.php(7): fox56_single_inner() #7 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/single.php(23): fox56_single() #8 /home/host1867038/the-devops.ru/htdocs/www/wp-includes/template-loader.php(106): include('/home/host18670...') #9 /home/host1867038/the-devops.ru/htdocs/www/wp-blog-header.php(19): require_once('/home/host18670...') #10 /home/host1867038/the-devops.ru/htdocs/www/index.php(17): require('/home/host18670...') #11 {main} thrown in /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/blog.php on line 411