PHP Redis Usage

lastmafia

Administrator
Staff member
Jun 4, 2024
5
0
1
My aim in this writing is to share various data types in Redis and some information about them. The examples are released using PHP packages instead of redis-cli.

First of all, Redis is not just a key-value store; it exhibits a data structure that supports different data types. This means that while familiar key-value stores calculate string keys with string values, in Redis, it is not limited to a simple string; we can hold more complex data structures. Below is a list of data structures supported by Redis.

String: Binary-safe sequences. Non-ASCII characters can be stored.List: Lists consisting of different sequences are stored while preserving their order. For example: [ali, veli, ali, konya, 3434, abc\x00abc]Set: Different sequences, ideal for cases where only one instance of an item is desired. [ali, veli, konya, 3434, abc\x00abc]Hash: Used to hold one or more values in the form of key-value pairs.

Redis Keys (Keys):Redis keys are binary-safe. That is, they can be like “ali” or contain a jpeg content.

Some rules:

  • Using long keys might not be a good idea. For example, a key of 1024 bytes (about a thousand characters) might not be efficient in terms of memory usage and bandwidth.
  • Very short keys are also not a good idea. If you have a key like u1000flw, it is better to write it as user:1000:followers for readability.
  • Stick to a convention. For example, the “object-type

    ” pattern is a good idea for user:1000. You can use dots or hyphens for multi-word items whenever needed. For example: comment:1234:reply.to, or comment:1234:reply-to.
  • The allowed key size is 512MB.
Redis Strings:This is a simple type that can be assigned to a key, similar to Memcached, which only uses this data type. The string type is very suitable for uses like caching an HTML piece or a page.

Examples include Predis PHP packages. https://github.com/predis/predis

Using methods like set and get, we can save and retrieve a string without checking if the key or value exists.

User data as a string can be of any type. For example, you can store a jpg. A value cannot be larger than 512MB.

Set method assigns a value; if the value exists or not, it does not perform the operation.

Using XX and NX parameters in a non-existing mykey key:


  • XX modifies the data if the key exists, while NX validates only if the key does not exist.
  • Multiple key-value pairs can be set or retrieved simultaneously using the mget method.
Using mget to retrieve values created with the set method:The mget method behaves like the get method for retrieving data from one or more keys, while mset behaves like the set method for adding one or more keys.

Redis Expiry:Before moving on to more complex types, I want to touch on the concept of expiry. Simply put, we can define a time-to-live (TTL) for a key. Once this time is up, the key and its data are automatically deleted, similar to manually calling the del method.

The mykey key's lifespan is 5 seconds; it can only be accessed within this period, after which it is automatically deleted.

The first result shows the operation outcome, the second adds the assigned value, and the final value is accessed after the expiry period.

Redis Lists:Used to hold data like [10, 20, 1, 2, 3]. List data type elements are kept together, and they can be retrieved within a specific range. The lpush method adds elements to the front, while rpush adds them to the end. To get elements within a specific range, use the lrange method.

Using lrange to retrieve data within a specified range:

  • rpush, lpush return the number of elements in the list.
  • The second parameter of lrange specifies the starting index, and the third parameter specifies the end index; -1 means the end of the list. In the example below, elements are shown in the order they were added. If lpush was used instead of rpush, the list order would be different.
Removing an element from the front or end of the list using lpop and rpop methods:

  • These methods also return the removed element. The example below shows removing the first element from the list using lpop.
To remove data from the end of the list, use the rpop method:

  • The lpop, rpop methods return the first or last element in the list and remove it.
  • To keep the list within a specific range, use the ltrim method. For example, to keep the list to a fixed number of elements or to prevent the list from growing uncontrollably, you can use these methods. The ltrim parameters start indexing from 0. Here, the second parameter value 3 includes the fourth element.
Trimming the list to keep elements from index 0 to 3 using ltrim:

Redis Sets:
Sets store elements in an unordered manner, where an element (string) can only appear once. Use sadd to add elements, smembers to retrieve all elements, and sismember to check if an element exists.

Only one "ali" was added despite providing two. Membership was checked with sismember.

Redis Hash:
A data type that can hold multiple key-value pairs within a single key. Holding multiple attributes for a single key with other Redis data types can be problematic. Here’s an example of data that can be held in a hash:


Code:
tt0120737
title: The Lord of the Rings: The Fellowship of the Ring
year: 2001
director: Peter Jackson
rating: 8.8

Looks great, doesn't it? We add data using the hmset method and ensure consistency with the validation key. If needed, more data can be added to an existing key using the same method. The hget method retrieves a specific value for a key, while hmget retrieves multiple values. hgetall returns all data associated with a key.

Adding more data to the same key using hmset:The addition returns "OK," and it is possible to retrieve part or all of the data for a key.

Using RediSearch:I mentioned using RediSearch in the search results summary. RediSearch is consistent with the hash data type.

Common Methods:While updating or retrieving data types, prefer their own methods. However, some common methods exist for all types.

  • The expire method specifies the key name and duration in seconds, after which the key is automatically removed by Redis. This can be done at any time during the project, not just at the time of creating the data.
  • With the del method, we can delete one or more keys.
  • The exists method checks if a key exists.
  • The persist method removes the TTL attribute for a key, making the data persistent.
  • The ttl method shows the remaining lifetime of a key in seconds. -1 means no TTL is set, and values greater than 0 indicate the time left before the key is deleted.
In addition to what I've explained, there are dozens of commands available according to need. The full list of these commands can be found at https://redis.io/commands. Almost all are supported by the Predis package.