laravel的cache如何设置一个值有生命周期,然后这期间我会更新这个值,如何使得生命周期不变的?

情况是这样的,我想对一个值设置一个生命周期
cache()->set(‘test’,’value’,30); //30秒后就消失
但是在30秒内我会更新这个值,如果我用
cache()->set(‘test’,’value1’);//那么生命周期就永久了
我想的是能既更新缓存值又不改变生命周期?

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 9

把时间存进去,计算剩余时间重新设置就行

6个月前 评论

试试put()

Cache::put('test', 'value', 30);
Cache::put('test', 'new value', 30);
6个月前 评论
donggan (楼主) 6个月前
Dash007 (作者) 6个月前

可以先读取剩余的过期时间 然后设置值的时候 过期时间 设置这个剩余的过期时间就可以了

6个月前 评论
donggan (楼主) 6个月前
cccdz (作者) 6个月前

目前,没有好办法,因为 Cache 是标准包装,没有提供获取 key 的 ttl 的方法,所以你不能知道它还有多久过期。

但是有另外一个方法,就是你可以传一个实现了 \DateTimeInterface 接口的对象进去,比如,传一个 Carbon,那 Laravel 就会自动计算到期的时间。

当然, 你也可以获取到底层的 Redis, 封装后手动控制查询,以下代码加入到 AppServiceProvider 的 boot 里面。

use Illuminate\Cache\RedisStore;
use Illuminate\Cache\Repository;


Cache::macro('putKeepTtl', function ($key, $value, $seconds = null) {
    /** @var Repository $this */
    $seconds = $this->getSeconds($seconds);
    $store = $this->store;
    if ($seconds > 0 || is_null($store) || !$store instanceof RedisStore) {
        return $this->put($key, $value, $seconds);
    }

    /** @var RedisStore $store */
    $connection = $store->connection();
    $prefix = $store->getPrefix();
    // 原始的 Redis 连接,需要使用前缀拼接
    $ttl = $connection->ttl($prefix . $key);
    if ($ttl > 0) {
        return $this->put($key, $value, $ttl);
    }

    return $this->put($key, $value);
});

使用示例

Cache::putKeepTtl('foo', 'bar', 100);
Cache::putKeepTtl('foo', 'foo');

这只是一个简单的封装,可能还有其他一些未处理的问题,比如使用 tags 时

6个月前 评论
running8

获取缓存过期剩余时间秒的方法

采用 radis 缓存:

return \Illuminate\Support\Facades\Redis::connection('cache')->ttl(config('cache.prefix') . ':' . $key); 

采用文件存储缓存:

在 AppServiceProvider.php 的 boot 方法中 添加:

        Cache::macro('getTTL', function (string $key): ?int {
            $fs = new class extends FileStore {
                public function __construct()
                {
                    parent::__construct(App::get('files'), config('cache.stores.file.path'));
                }

                public function getTTL(string $key): ?int
                {
                    return $this->getPayload($key)['time'] ?? null;
                }
            };

            return $fs->getTTL($key);
        });

使用:

return \Illuminate\Support\Facades\Cache::getTTL($key);
6个月前 评论

把时间存进去,计算剩余时间重新设置就行

6个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!