light-speak / laravel_model_cache
基于Redis的laravel模型数值缓存,可以减少并发修改对数据库的压力,减少数据库事务锁的使用
v2.0.9
2023-09-05 05:58 UTC
Requires
- php: >=8.0
- ext-bcmath: *
- laravel/framework: 9.*|10.*
README
基于Laravel ORM和Redis缓存的缓存插件,依赖于队列的模型属性缓存
持有模型实例,代理字段,使用缓存修改
注意!
数据修改仅适用于数值类型,操作会执行1000次,请注意精度
安装
composer require light-speak/laravel_model_cache
说明
此插件全部使用缓存。缓存使用的Redis存储功能是代理某个模型的字段,并使用缓存维持一段时间(默认为15秒)。所有内部修改都在缓存中进行以优化性能
- 修改缓存15秒
- 读取缓存3~24小时
使用
- 已添加一个名为model-cache的队列到队列中,用于维护字段
- 嵌入到需要使用的模型类中
use useGYCache;
- 在原始模型之后调用cache()方法
$wallet = Wallet::query()->first()->cache();
- 开始正常使用
详细用法
修改数据并使用插件进行模型代理
/**
* @param bool $useTransaction Whether to use transactions, if true, you must call the saveCache() method to save
*
* @return self|CacheModel
*/
public function cache(bool $useTransaction = false): self|CacheModel
{
$this->has_cache = true;
return ModelCache::make($this, __CLASS__, $useTransaction);
}
调用模型的cache方法,返回一个CacheModel实例,同时也有Model实例本身的返回类型,不影响IDE提示
$wallet = Wallet::query()->first()->cache();
debug($wallet->balance); // Normal access to Model's field, the first access will store it in the cache
使用incrementByCache和decrementByCache修改值
此时,常规模型Wallet::query()->first()->balance也将获取最新的缓存数据
$wallet = Wallet::query()->first()->cache();
debug("Current wallet amount (check Cache): $wallet->balance"); // 100
$wallet->incrementByCache('balance', 100);
$wallet = Wallet::query()->first();
$wallet->balance = 100;
debug("Current wallet amount (check DB): $wallet->balance"); // 200
$wallet->save();
debug("Current wallet amount (check DB): $wallet->balance"); // 100
$wallet = Wallet::query()->first()->cache();
debug("Current wallet amount (check Cache): $wallet->balance"); // 100
CacheModel对象和Model尽量保持一致性
事务
$wallet = Wallet::query()->first();
$wallet->balance = 200;
$wallet->save();
$wallet1 = Wallet::query()->first()->cache(true); // This must be saved to be useful here
$wallet1->incrementByCache('balance', 100); // Originally 200 here is an invalid modification
$wallet = Wallet::query()->first();
info($wallet->balance); // 200
$wallet = Wallet::query()->first()->cache();
info($wallet->balance); // 200
$wallet1 = Wallet::query()->first()->cache(true);
$wallet1->incrementByCache('balance', 100);
$wallet1->saveCache(); // It is equal to 100 from here, and it will take effect if it is saved