Deleted Cache when the data is changed.

This commit is contained in:
李铭昕 2019-01-25 16:18:06 +08:00
parent a068f3909a
commit 5a37cc6c66
4 changed files with 77 additions and 1 deletions

View File

@ -31,4 +31,12 @@ trait Cacheable
return $manager->findManyFromCache($ids, static::class);
}
public function deleteCache()
{
$container = ApplicationContext::getContainer();
$manager = $container->get(Manager::class);
return $manager->destroy([$this->getKey()], get_called_class());
}
}

View File

@ -135,7 +135,7 @@ class RedisHandler implements HandlerInterface
public function deleteMultiple($keys)
{
$this->redis->delete(...$keys);
return $this->redis->delete(...$keys);
}
public function has($key)

View File

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://hyperf.org
* @document https://wiki.hyperf.org
* @contact group@hyperf.org
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
namespace Hyperf\DbConnection\Cache\Listener;
use Hyperf\Database\Model\Events\Created;
use Hyperf\Database\Model\Events\Deleted;
use Hyperf\Database\Model\Events\Event;
use Hyperf\Database\Model\Events\Saved;
use Hyperf\Database\Model\Events\Updated;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
/**
* @Listener
*/
class DeleteCacheListener implements ListenerInterface
{
public function listen(): array
{
return [
Deleted::class,
Updated::class,
Created::class,
Saved::class,
];
}
public function process(object $event)
{
if ($event instanceof Event) {
$model = $event->getModel();
if (method_exists($model, 'deleteCache')) {
$model->deleteCache();
}
}
}
}

View File

@ -139,6 +139,27 @@ class Manager
return $instance->newQuery()->whereIn($primaryKey, $ids)->get();
}
/**
* Destroy the models for the given IDs from cache.
*/
public function destroy($ids, string $class)
{
/** @var Model $instance */
$instance = new $class();
$name = $instance->getConnectionName();
if ($handler = $this->handlers[$name] ?? null) {
$keys = [];
foreach ($ids as $id) {
$keys[] = $this->getCacheKey($id, $instance, $handler->getConfig());
}
return $handler->deleteMultiple($keys);
}
return 0;
}
protected function getCacheKey($id, Model $model, Config $config)
{
// mc:$prefix:m:$model:$pk:$id