我们知道数据库操作一直是应用的瓶颈所在,所以我们经常要用到`缓存`
通过是先查缓存,缓存没有再查数据库,然后将查询到的结果保存到缓存
在hyperf中有比较优雅的方式,就是`模型缓存`
```
安装模型缓存组件
composer require hyperf/model-cache
控制器 app/Controller/IndexController.php
input('id',1);
//User::query(true)->where('id',1)->update(['username'=>'倚天屠龙记张无忌']);//执行更新或删除操作会自动更新删除缓存
$user = User::findFromCache($id);
return $user->toArray();
}
}
User模型 app/Model/User.php
[
'driver' => env('DB_DRIVER', 'mysql'),
'host' => env('DB_HOST', 'mysql'),
'database' => env('DB_DATABASE', 'hyperf'),
'port' => env('DB_PORT', 3306),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', '123456'),
'charset' => env('DB_CHARSET', 'utf8'),
'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
'prefix' => env('DB_PREFIX', ''),
'pool' => [
'min_connections' => 1,
'max_connections' => 10,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => (float) env('DB_MAX_IDLE_TIME', 60),
],
'commands' => [
'gen:model' => [
'path' => 'app/Model',
'force_casts' => true,
'inheritance' => 'Model',
],
],
//模型缓存配置
'cache' => [
'handler' => \Hyperf\ModelCache\Handler\RedisHandler::class,
'cache_key' => 'mc:%s:m:%s:%s:%s',
'prefix' => 'default',
'ttl' => 3600 * 24,
'empty_model_ttl' => 3600,
'load_script' => true,
'use_default_value' => false,
]
],
];
测试
curl 118.195.173.53:9501/index/index?id=1
返回结果
{
"id": 1,
"name": "xiaohong",
"age": 24,
"role_id": 1,
"status": 1
}
mysql命令修改id=1的记录age=30
mysql> update user set age=30 where id=1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql命令查看user表记录
mysql> select * from user;
+----+------------------+------+---------+--------+
| id | name | age | role_id | status |
+----+------------------+------+---------+--------+
| 1 | xiaohong | 30 | 1 | 1 |
| 2 | huyongjian2 | 24 | 2 | 0 |
| 4 | xiaoming | 28 | 2 | 1 |
| 5 | xiaoming5 | 30 | 2 | 1 |
| 6 | huyongjian1 | 30 | 2 | 1 |
| 7 | huyongjian2 | 31 | 2 | 1 |
| 8 | xiaohong | 24 | 1 | 1 |
| 11 | model_event_test | 20 | 1 | 1 |
+----+------------------+------+---------+--------+
8 rows in set (0.00 sec)
重新访问
curl 118.195.173.53:9501/index/index?id=1
返回结果
{
"id": 1,
"name": "xiaohong",
"age": 24,
"role_id": 1,
"status": 1
}
进入redis 查看是否存在类似:mc:default:m:user:id:1 的key
root@e78217bbda35:/data# redis-cli
127.0.0.1:6379> keys *
1) "mc:default:m:user:id:1"
注:说明已经成功使用了缓存功能
访问update控制器
curl 118.195.173.53:9501/index/update
结果返回
1
重新访问
curl 118.195.173.53:9501/index/index?id=1
结果返回
{
"id": 1,
"name": "xiaohong",
"age": 30,
"role_id": 2,
"status": 1
}
注:age,role_id已变成最新数据
缓存获取方法
// 查询单个缓存
/** @var int|string $id */
$model = User::findFromCache($id);
// 批量查询缓存,返回 Hyperf\Database\Model\Collection
/** @var array $ids */
$models = User::findManyFromCache($ids);
转https://www.cnblogs.com/hu308830232/p/15350917.html
```