1
votes

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?

1
The keys that return to you already have prefix(complete key name). So you don't need to add manually. - Ersoy
If you go through the post once again, you'll see that there is no prefix added in my original attempt - Norgul
I see my bad. if you trying to delete by redis's methods then it won't add prefix. If you are going to add by Cache facade's, it is going to add automatically. You may use monitor command in redis to see which commands are executed behind the scenes when you are using any of those delete methods. - Ersoy
I see that on monitor output I am getting: "DEL" "workspace_database_workspace_database_workspace_cache:table_def_workspace_items"...looks like workspace_database_ is being added somewhere down the line...do you know how to ignore it? This is not a prefix, but rather a pre-prefix, which is not the part of the same class - Norgul

1 Answers

3
votes

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.