Norgul
Norgul

Reputation: 4783

Laravel Redis cache prefix missmatch

I am using Redis as my cache driver and I would like to extend the functionality to delete keys by pattern.

When I list out the cache within Redis CLI I get:

127.0.0.1:6379[1]> keys *
1) "workspace_database_workspace_cache:table_def_workspace_items"
2) "workspace_database_workspace_cache:table_def_workspaces"

However when I dump $this->prefix from Illuminate\Cache\RedisStore I get:

"workspace_cache:"

For some reason, my delete doesn't work. When I try to fetch keys using:

public function keys($pattern = '*')
{
    return $this->connection()->keys($pattern);
}

I get the keys back as expected.

But if I try to delete them, I am failing to do so (when calling Cache::forgetByPattern('*items'):

public function forgetByPattern($key)
{
    foreach ($this->keys($key) as $item) {
        $this->connection()->del($item);
    }

    return true;
}

Item dump here shows exactly workspace_database_workspace_cache:table_def_workspace_items.

If I delete by providing exact key after a prefix (like the original forget() method functions):

$this->connection()->del($this->prefix.'table_def_workspace_items');

Surely it does delete the key.

I have also tried doing a:
$this->connection()->del('*items'); 

and

$this->connection()->del($this->prefix.'*items');

EDIT: re-checking the documentation, Redis doesn't provide DEL by pattern.

But none of these work. Why is this failing, and why am I getting additional prefix added?

Upvotes: 3

Views: 5438

Answers (1)

Norgul
Norgul

Reputation: 4783

Ersoy led me to the right path with Redis monitor function. This is the final product which works:

public function forgetByPattern($key)
{
    foreach ($this->keys($key) as $item) {
        $item = explode(':', $item);
        $this->forget($item[1]);
    }

    return true;
}

Also, the prefix I was baffled with comes from database.php config file under redis.options.prefix key.

Upvotes: 4

Related Questions