1
votes

We run a Laravel 5.1 API, which in some cases queues commands to provision server instances with various packages and settings. Each instance has a specific id, which is included in the queue item data. That instance id is in turn used as a prefix for Redis cache keys. For example: "instance-0:clients:list" for a list of clients running on instance id 0. The "cache.prefix" config setting is updated through a middleware with the current instance id.

Various create/update/delete endpoints "forget" cache keys, which are then rebuilt when list/show endpoints are called. Everything is fine and dandy up to this point when those actions occur through the API endpoints directly. It also works if I run the queue manually with "artisan queue:work".

BUT...

The regular queue is run as a daemon through supervisord. When the queue runs as a daemon, the cache prefix is never changed because (I'm guessing) it doesn't go through the middleware when it runs a given queue item. This also happens if I run the queue as a daemon manually (not through supervisord).

I've tried force-setting the value through \Config::set('cache.prefix', 'instance-X') as well as putenv('CACHE_PREFIX=instance-X') but they have no effect on the actual prefix used by the cache store itself. The only way I was able to set it successfully was to set CACHE_PREFIX in the ".env" file but it does not work with out architecture. We run API and worker instances in Docker containers and workers are not specific to any given API instance, hence the inclusion of the instance id in the queue item data for later use.

So, I'm kind of stuck as to how I can set the cache prefix on a per-queue item basis. Is that even possible? Any help would be greatly appreciated!

1

1 Answers

1
votes

Try the method Cache::setPrefix('instance-X').

It will force a the cache prefix to change for the given request. It should work for you since I had a similar use case but was I needed it to manage my Cache. It may or may not work. I've not tested this with queues but since the cache prefix is shared by both session and queue drivers in Laravel it should work.

Just to be clear the method does not affect the config values. If you use config('cache.prefix') to get the cache prefix immediately after running the method, the value will still be that in your config file.