Search code examples
phpredismemcachedttlphpredis

phpredis function mSet with ttl


I'm currently using memcached, but i'm trying move this mechanism to redis.

My goal is to save the entire array (key => value) every 1000 iterations.

Old solution:

<?php
$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$memcached->setMulti($data, time()+864000);

New solution:

<?php
$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$redis->mSet($data);

The operation of these scripts is almost identical.

As you can see, the redis can not set the expire date when I'm using multi (mSet function).

Any solution?


Solution

  • MSET doesn't support the EX and PX options available with SET. You have 2 options depending on your needs:

    • If you need this to be atomic, use either transactions or Lua scripting. An example with transactions (from redis-cli) would look like this:

      > MULTI

      OK

      > SET key1 value1 EX 10

      QUEUED

      > SET key2 value2 EX 10

      QUEUED

      > EXEC

    I'm not familiar with phpredis, but it probably has an abstraction that handles this for you.

    • If you don't need atomicity, you can just use pipelining with multiple SET commands.