目录
[TOC]
WorkerA 的 Redis 功能基于 [predis](https://github.com/nrk/predis "predis"),使用方式也和 predis 相似。
## 配置
redis 的配置在 config/database/php 中:
```php
'redis' => [
'cluster' => FALSE, // 是否使用 redis 集群
'options' => NULL, //
'rd_con' => [ // redis 连接
'default' => [
'host' => '127.0.0.1', // 主机名
'password' => NULL, // 密码
'port' => 6379, // 端口
'database' => 0, // 数据库索引
// 'read_write_timeout' => 0, // 超时时间,0 或 -1 禁用超时
],
'other' => [
'host' => 'xx.xx.xx.xx',
'password' => NULL,
'port' => 6379,
'database' => 0,
// 'read_write_timeout' => 0,
],
]
]
```
**关于配置的一些说明:**
cluster 为 FALSE 时,框架初始化后 rd_con 中的每条配置都会创建一个 redis 连接。cluster 为 TRUE 时,框架初始化后只会创建一个连接,rd_con 中的每条配置会被当做 cluster 模式中的一个节点。
因为 WorkerA 在常驻内存模式下运行,需要对 redis 的超时问题做处理。设置 read_write_timeout 参数为 0 或 -1 时即可禁止超时。详见:[predis - issue#33](https://github.com/nrk/predis/issues/33#issuecomment-1395652)
## 使用
WorkerA 对 predis 的封装参考了 Laravel,所以你可以像在 Laravel 中一样对 redis 进行操作。
### 获取连接
默认连接 default 是不用获取的,不指定则默认使用 default 连接。如果你要访问其它连接,请使用 WorkerF\DB\Redis 类的 connection 方法:
```php
use WorkerF\DB\Redis;
...
$con = Redis::connection('other');
```
### 基本操作
WorkerF\DB\Redis 类支持所有 redis 方法,你可以直接调用方法名称:
```php
namespace App\Controller;
use App\Controller\Controller;
use App\Models\Test;
use WorkerF\DB\Redis;
class TestController extends Controller
{
public function test(Test $test)
{
// 从 redis 获取数据
$value = Redis::get('rst');
if( ! $value) {
$rst = $test->getData();
// 设置 redis 数据
Redis::set('rst', json_encode($rst));
} else {
$rst = json_decode($value);
}
return $rst;
}
}
```
WorkerF\DB\Redis 类还提供了一个 command 方法,用来发送 redis 命令:
```php
$values = Redis::command('get', 'rst');
$values = Redis::command('set', ['rst', json_encode($rst)]);
```
### pipeline
predis 提供了 pipeline 流水线模式,可以减少向 redis 发送大量命令时的网络请求延迟问题。WorkerF\DB\Redis 类直接调用了 predis 的 pipeline 方法:
```php
Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i++) {
$pipe->set("key:$i", $i);
}
});
```
### 发布与订阅
同样,Redis 类提供了发布和订阅 (publish / subscribe) 功能:
```php
// subscribe
Redis::subscribe('test-channel', function($msg) {
echo $msg;
});
// publish
Redis::publish('test-channel', json_encode(['foo' => 'bar']));
```
> 注:subscribe 方法会阻塞进程,所以不要在框架加载后使用。你可以在 WorkerStart.php 中的 onWorkerStart 回调中选取一个进程来单独执行 subscribe。
> 当然,基于 workerman 的环境,你可以使用更多 socket 相关方法来处理发布、订阅的业务,没必要非用 redis 的 publish / subscribe 不可。
