There are two main redis extensions of php that we use at present:
phpredis, which uses c An efficient extension of PHP; predis, which is written in PHP code and is used quite a lot.
phpredis (PHP extension) method (Recommended learning: PHP video tutorial)
1. phpredis stand-alone method
<?php $client = new Redis(); $client->connect('10.30.5.163', '7000'); echo $client->get('new_item_key:d89b561fb759fd533a8c2781ef15dd5f');
phpredis cluster usage
<?php $redis_list = ['10.30.5.162:7000','10.30.5.163:7000','10.30.5.163:7001']; $client = new RedisCluster(NUll,$redis_list); echo $client->get('new_item_key:d89b561fb759fd533a8c2781ef15dd5f');
Code description
Pass NULL for the first parameter. Don’t ask me, I don’t know why. Anyway, I couldn’t find the document, and I didn’t understand this article.
The second parameter is the list of master servers of the redis cluster we need to connect to. We have 3 masters, so just fill in 3. You can also fill in a master node, or even a slave node, but the performance is different. See Part 4
3. Cluster Principle
Why can redisCluster be operated by filling in any node address?
In cluster mode, when Redis receives any key-related command, it first calculates the slot corresponding to the key,
If the slave node is initialized, the redis command will be sent to the slave node first.
The slave node finds the corresponding node according to the slot. If the node is itself, the key command is processed;
If not itself, MOVED redirects an error, notifying the client to request the correct node. This process is called MOVED redirection
The redirection information contains the slot corresponding to the key and the node address responsible for the slot. According to this information
The client can initiate a request to the correct node
The phpredis client can directly initiate a request to the node where the key is located based on the redirection information to obtain the data
Use predis cluster mode
<?php use Predis\Client; require __DIR__ . '/../vendor/autoload.php'; $redis_list = [ 'tcp://10.30.5.163:7000', 'tcp://10.30.5.163:7001', 'tcp://10.30.5.162:7000' ]; $redis = new Client($redis_list, ['cluster'=>'redis']); echo $redis->get('new_item_key:d89b561fb759fd533a8c2781ef15dd5f')
The above is the detailed content of How to call redis cluster in php. For more information, please follow other related articles on the PHP Chinese website!