Implementing horizontal caching in PHP with Redis Cluster
Connect to your server via SSH:
ssh [USERNAME]@[IP_ADDRESS]
Update packages:
sudo apt update && sudo apt upgrade
Install Redis:
sudo apt install redis-server
Start and enable Redis:
sudo systemctl start redis sudo systemctl enable redis
Check Redis status:
sudo systemctl status redis
Redis is now installed and ready to use.
Configuring Redis Cluster
To create a cluster, you need to do a little fiddling with the configuration files, especially redis.conf
.
Open the configuration file:
sudo nano /etc/redis/redis.conf
Please note the following security settings. It's important to disable
protected-mode
for the cluster to work, but be aware that this increases the risk of access from outside:protected-mode no
Specify IP addresses for connections:
bind 127.0.0.1 [SERVER_IP_ADDRESS]
Activate cluster mode:
cluster-enabled yes cluster-config-file nodes-6379.conf cluster-node-timeout 15000
Turn on
appendonly
to improve data reliability:appendonly yes
After making changes, restart Redis:
sudo systemctl restart redis
Don't forget to open the necessary ports:
sudo ufw allow 6379 sudo ufw allow 16379
Creating a Redis Cluster
Now let's create a cluster using the utility redis-cli
.
Use the following command to create a cluster:
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1
If you did everything correctly, Redis will report that all 16384 slots have been allocated, confirming that the cluster was created successfully.
Connect to the cluster and check its status:
redis-cli -c -p 7000
Now you can use commands like SET
And GET
to interact with your cluster.
Integrating Redis Cluster with PHP
Installing and configuring PhpRedis
It's time to connect Redis to your PHP application. PhpRedis
is a PHP extension that provides low-level access to Redis and supports all of its features, including working with clusters.
Install PhpRedis using PECL:
pecl install redis
Add the following line to your
php.ini
:extension=redis.so
Create a connection to the cluster:
$redisCluster = new RedisCluster('mycluster', ['127.0.0.1:7000', '127.0.0.1:7001', '127.0.0.1:7002']);
Now you can use Redis commands:
$redisCluster->set("my_key", "Hello, Redis!");
echo $redisCluster->get("my_key"); // Вывод: Hello, Redis!
It is important to handle possible exceptions:
try {
$value = $redisCluster->get("unknown_key");
echo $value ? $value : "Key does not exist!";
} catch (RedisException $e) {
echo "Redis error: " . $e->getMessage();
}
Installing and configuring Predis
Predis
is a client library for Redis in PHP that does not require installation of additional extensions.
Install Predis:
composer require predis/predis
Create a connection:
require 'vendor/autoload.php'; $client = new Predis\Client([ 'cluster' => 'redis', 'parameters' => [ 'host' => '127.0.0.1', 'port' => 7000, ], ]);
Work with data:
$client->set('test_key', 'Hello from Predis!'); $value = $client->get('test_key'); echo $value; // Вывод: Hello from Predis!
Basic commands and their uses
Working with simple keys
sudo systemctl status redis
Working with hashes
$client->hset("user:1000", "name", "John Doe");
$client->hset("user:1000", "email", "john@example.com");
$user = $client->hgetall("user:1000");
print_r($user);
Working with Lists
$client->rpush("task_queue", "Task 1");
$client->rpush("task_queue", "Task 2");
$tasks = $client->lrange("task_queue", 0, -1);
print_r($tasks);
Setting the key lifetime
$client->setex("temporary_key", 300, "This key expires in 5 minutes.");
Working with the MSET and MGET team
$client->mset(["key1" => "value1", "key2" => "value2"]);
$values = $client->mget(["key1", "key2"]);
print_r($values);
Implementing horizontal caching in PHP
Write-Through and Write-Behind caching
Write-Through caching assumes that data is written simultaneously to both the cache and the database. This ensures that the cache is always up to date, but may increase response time:
function writeThrough($key, $value) {
global $redis;
$redis->set($key, $value);
saveToDatabase($key, $value);
}
Write-Behind caching first writes data to the cache and then to the database, which improves response time:
function writeBehind($key, $value) {
global $redis;
$redis->set($key, $value);
queueForDatabaseInsert($key, $value);
}
With TTL you can manage memory by automatically deleting keys after time has elapsed:
function cacheWithTTL($key, $value, $ttl) {
global $redis;
$redis->setex($key, $ttl, $value);
}
Example of using caching for API requests
Set up a connection to Redis:
require 'vendor/autoload.php';
$redis = new Predis\Client([
'cluster' => 'redis',
'parameters' => [
'host' => '127.0.0.1',
'port' => 7000,
],
]);
Create a function to retrieve data from cache or database:
function getCachedData($key) {
global $redis;
if ($redis->exists($key)) {
return $redis->get($key);
} else {
$data = getDataFromDatabase($key);
$redis->setex($key, 3600, $data); // Кешируем данные на 1 час
return $data;
}
}
function getDataFromDatabase($key) {
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$result = $mysqli->query("SELECT value FROM table WHERE key='$key'");
return $result->fetch_assoc()['value'];
}
Example of using the function
$key
= "user:123";
$data = getCachedData($key);
echo "Данные: " . $data;
Well, that's all – we set up the cluster, connected it to PHP, figured out caching – what else is needed to be happy? Most importantly, do not forget about security, otherwise Redis is a responsive, but trusting friend.
OTUS experts consider more practical cases within the framework of courses, a full list of which can be found here. check out the catalog. I also remind you that in the events calendar you can sign up to any webinar you are interested in.