1
$redisClient -> setex('key', 3600, 'value' );

and

$redisClient -> psetex('key', 3600, 'value' );
ROOT
  • 11,363
  • 5
  • 30
  • 45

3 Answers3

1

https://redis.io/commands/set vs https://redis.io/commands/setex

and yes, serialize the data with serialize or jasn_encode.

Alex Barker
  • 4,316
  • 4
  • 28
  • 47
1

psetex is precise setex, meaning the units for the TTL are in milliseconds, not in seconds. See https://redis.io/commands/psetex

As value, you can set any binary-safe string. You can store an array serialized in your preferred format, like JSON or CSV, but every operation you do on the array you have to read in full and write back in full.

Consider the other data types in Redis: lists, sets, sorted sets, hash (maps). Chances are another data type is a better fit for your requirement. See https://redis.io/topics/data-types

You can always set an expiration on any type of key using EXPIRE or PEXPIRE.

LeoMurillo
  • 6,048
  • 1
  • 19
  • 34
0

As others have described SETEX takes the TTL in seconds and PSETEX takes it in milliseconds.

You can have PhpRedis handle the serialization for you though:

$obj_r = new Redis();
$obj_r->connect('localhost', 6379);

$obj_r->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
$obj_r->set('serialized', ['this', 'is', 'an', ['array', 'of', 'values']]);

var_dump($obj_r->get('serialized'));

setOption examples in the docs