4.4.11 模型缓存
安装composer包
composer require hyperf/model-cache
配置文件
在config/autoload/databases.php下
<?php
return [
'default' => [
'driver' => env('DB_DRIVER', 'mysql'),
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'hyperf'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'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),
],
'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,
]
],
];
ORM类中引入缓存机制
- 实现 \Hyperf\ModelCache\CacheableInterface 接口
- 引入 \Hyperf\ModelCache\Cacheable 缓存文件
<?php
namespace App\Model;
use Hyperf\Database\Model\Events\Created;
use Hyperf\Database\Model\Events\Creating;
use Hyperf\Database\Model\SoftDeletes;
use Hyperf\DbConnection\Model\Model;
/**
* @property int $id
* @property string $merchant_no
* @property string $title
* @property string $desc
* @property int $status
* @property string $meta
* @property string $cdn_addr
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
* @property string $deleted_at
*/
class UserActivity extends Model implements \Hyperf\ModelCache\CacheableInterface
{
use \Hyperf\ModelCache\Cacheable;
/**
* 表名
* @var string
*/
protected $table = 'user_activity';
...
}
findFromCache():查询单个缓存
<?php
namespace App\Controller;
class IndexController extends AbstractController
{
public function index()
{
return \App\Model\UserActivity::findFromCache(10028);
}
}
输出
{
"id": 10028,
"merchant_no": "11211",
"title": "TEST",
"desc": "desc",
"status": 1,
"meta": "{\"cover_pic\":\"https:\\/\\/timgsa.baidu.com\\/timg?image&quality=80&size=b9999_10000&sec=1591770047788&di=8efc808496c85415054dae40e1a7f06a&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F56%2F12%2F01300000164151121576126282411.jpg\",\"share_pic\":\"https:\\/\\/timgsa.baidu.com\\/timg?image&quality=80&size=b9999_10000&sec=1591770047788&di=8efc808496c85415054dae40e1a7f06a&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F56%2F12%2F01300000164151121576126282411.jpg\",\"rule\":\"rule\"}",
"cdn_addr": "",
"created_at": "2020-07-14 01:50:18",
"updated_at": "2020-07-14 02:36:00",
"deleted_at": "2020-07-14 02:36:00"
}
query(true):批量删除缓存
- 避免批量更新数据时,缓存与数据库的数据不同步
<?php
namespace App\Controller;
class IndexController extends AbstractController
{
public function index()
{
// 批量更新数据,并会批量将缓存数据删除
\App\Model\UserActivity::query(true)->where('id', 10028)->update([
'title' => sprintf('title-%d', mt_rand(0, 9999))
]);
// 重新刷新缓存
return \App\Model\UserActivity::findFromCache(10028);
}
}文档更新时间: 2021-09-24 17:57 作者:赵豪