shibo / redis
1.1.2
2018-02-27 01:43 UTC
Requires (Dev)
- mockery/mockery: ^1.0@dev
This package is not auto-updated.
Last update: 2024-09-14 19:31:04 UTC
README
PHP Redis 客户端,支持单个 Redis 服务器,或 Redis 主从集群。
安装
1.推荐使用 composer
composer require shibo/redis
或者在你的 composer.json 中
{
"require": {
"shibo/redis" : "^1.0"
}
}
2.如果你不使用 composer,你应该在代码中包含 'Autoload.php'
示例
1.单个 Redis 服务器
读写操作都在单个服务器上执行。
use \Redis\SingleClient; use \Redis\Drivers\RedisFactory; include 'Autoload.php'; $config = ['host' => '127.0.0.1', 'port' => 6379, 'weight' => 1]; // if need auth // $config = ['host' => '127.0.0.1', 'port' => 6379, 'weight' => 1, 'auth' => 'qii']; $redis = new SingleClient( $config, RedisFactory::PHPREDIS // this is optional param, default is PHPREDIS driver ); $redis->set('name', 'qii404'); // true $redis->get('name'); // 'qii404'
2.没有从属服务的 Redis 集群
读写操作都在集群中的同一个服务器上执行。
use Redis\Drivers\RedisFactory; use Redis\WithoutSlavesClient; use Redis\Hash; use Redis\Key; include 'Autoload.php'; $config = [ ['host' => '127.0.0.1', 'port' => 6379, 'weight' => 1], ['host' => '127.0.0.1', 'port' => 6380], ]; // hash stragety, you can also define your stragety in Hash folder $hash = new Hash\Consistant(); // key hasher, such as new Md5 or Cr32, you can add it in Key folder $calculator = new Key\Cr32(); // $calculator = new Key\Md5(); $redis = new WithoutSlavesClient( $config, $hash, $calculator, RedisFactory::PHPREDIS // this is optional param, default is PHPREDIS driver ); // when using the same key, both read & write operation executed in the same server, such as port 6379 $redis->hset('profile', 'name', 'qii44'); // true $redis->hget('profile', 'name'); // 'qii404'
3.有从属服务的 Redis 集群
读写操作在不同的服务器上执行,读操作从从属服务器上读取,写操作从主服务器上写入
(你应该正确配置 'm' 和 's',例如 6381 是 6379 的从属服务器,6382 是 6380 的从属服务器).
use Redis\Drivers\RedisFactory; use Redis\WithSlavesClient; use Redis\Hash; use Redis\Key; include 'Autoload.php'; $config = [ 'm' =>[ ['host' => '127.0.0.1', 'port' => 6379, 'weight' => 1], ['host' => '127.0.0.1', 'port' => 6380], ], 's' =>[ ['host' => '127.0.0.1', 'port' => 6381], ['host' => '127.0.0.1', 'port' => 6382], ] ]; // hash stragety, you can also define your stragety in Hash folder $hash = new Hash\Consistant(); // key hasher, such as new Md5 or Cr32, you can add it in Key folder $calculator = new Key\Cr32(); // $calculator = new Key\Md5(); $redis = new WithSlavesClient( $config, $hash, $calculator, RedisFactory::PHPREDIS // this is optional param, default is PHPREDIS driver ); $redis->zadd('key', 99, 'qii404'); // true; executes in master server, such as port 6379 $redis->zscore('key', 'qii404'); // 99; executes in slave server, such as port 6381
注意事项
- 当你在配置中使用 'weight' 时,它只在集群模式下有效,在主从模式下,你应该在 'm' 数组中而不是 's' 数组中配置。
- 不同的客户端通过多态实现,因此它简单且高效,但你需要自己创建一个客户端。
- 如果你有任何问题,不要问我。