Getting Began With Redis and PHP for Fast Knowledge Storage

The popular Redis storage engine is an excellent and must-have tool in any software developer's arsenal. The in-memory storage engine enables data to be saved and retrieved at lightning speed with up to an impressive 32 million queries per second, making it an excellent addition to any major database engine.

Let's dive in and learn how to speed up our online operations.

Redis: pros and cons

The biggest advantage of Redis is that it is a purely in-memory data store. This means that it is lightning fast as the database is stored in RAM and therefore does not require any file I / O on disk.

RAM guide

Other additional benefits include simplicity, cluster support via Redis clusters, and support for eight different data types, giving you the flexibility to store and manage your data as needed.

The main disadvantage, however, is also the fact that it is only an in-memory data store and therefore has size restrictions. This depends on your server infrastructure. However, for the sake of this article and for simplicity, your typical Redis database will only contain a maximum of 2 to 4 GB of data.

This means that Redis is used as a complement to the commonly used database engines like mySQL, PostgreSQL and MongoDB and is not intended as a replacement. Redis main uses include a cache, temporary / current data that expires in a short time, or small data that is accessed frequently.

How to install Redis

Assuming you're running Ubuntu or a Linux distribution that includes the apt-get command, simply run the following command in the terminal to install Redis:

sudo apt-get install redis-server

Then check that Redis has been installed successfully. In the terminal run the following command:

redis-cli –version

This should print the version of Redis you are running and, assuming it does, run the following command to connect to Redis:

redis-cli

This will give you a non-standard Redis prompt in Terminal that looks something like this:

127.0.0.1:6379>

String commands

Each entry in Redis is identified by a key, which can be any non-space character string. Strings contain only a single value. For example, run the following commands at the Redis command prompt to set a value on some keys.

127.0.0.1:6379> set full_name "John Doe"
127.0.0.1:6379> set units 5

You can now list all the keys in the Redis database using the keys command.

127.0.0.1:6379> key *

This results in the two previously set buttons being displayed. Full name and units. You can see the value of these keys with the get command.

127.0.0.1:6379> get full_name
"John Doe"
127.0.0.1:6379> Get units
5

Deleting keys can easily be done with the del command.

127.0.0.1:6379> del full_name

It is also possible to increase an integer quickly using the hincrby Command. In the following, the "Units" key is increased from 5 to 7.

127.0.0.1:6379> Inkrby units 2

List commands

Lists in Redis are one-dimensional arrays with a specific order and allow duplicate items in different positions in the list. Items can be added to the left or right of a list with the lpush and rpush Commands.

127.0.0.1:6379> lpush colors blue
127.0.0.1:6379> rpush colors red yellow green

As you can see in the example above, you can move multiple items into a list within a single command. We can now view all of the items in the list by editing the Area Command.

127.0.0.1:6379> color shades 0 -1

At the end of the command there are two integers, the first defines the position within the list to start at, and the second specifies the number of items to be returned, where -1 means all items. The result of the above command is: blue, red, yellow, green.

You can also remove items from either end of a list with the option lpop and rpop Commands.

127.0.0.1:6379> lpop colors
blue
127.0.0.1:6379> rpop colors
green

You can also get the number of items in a list using the ll Command.

127.0.0.1:6379> all colors
(Integer) 2

Finally, you can remove an element from a list using the lrem Command.

127.0.0.1:6379> lrem colors 1 green
(Integer) 1

The lrem The command begins with the list name, followed by the number of occurrences to remove and the name of the item to be removed. The number of occurrences found and removed from the list is returned.

Hash commands

One of the most popular data types in Redis is hashes, which allow you to store multiple key-value pairs in a single entry. The key does not have to exist yet, and you can use the to define key-value pairs at any time hset Command.

127.0.0.1:6379> hset user: 581 full_name "Jane Doe"
127.0.0.1:6379> hset user: 581 points 500

You can also define multiple key-value pairs of a hash in a single command with the command hmset Command.

127.0.0.1:6379> hmset user: 581 Email jane@domain.com Gender F.

The hash identified by the key User: 581 now have a total of four key-value pairs, all of which can be easily accessed using the hgetall Command.

127.0.0.1:6379> Total users: 581
1) "full_name"
2) "Jane Doe"
3 points"
4) 500
5) "Email"
6) "jane@domain.com"
7) "gender"
8) "F"

You can also use to determine the value of a single key-value pair within a hash to get Command.

127.0.0.1:6379> hget user: 581 email
"jane@domain.com"

For all integers within the hash, you can use the code to increase them by a certain amount hincrby Command.

127.0.0.1:6379> Note: 581 points 20
(whole number) 520

The value of the Points The key within the hash has now been increased by 20 to 520. A single key-value pair within a hash can be deleted with the hdel Command.

127.0.0.1:6379> HDEL users: 581 gender

Alternatively, you can completely delete a hash that contains all key-value pairs using this del Command.

127.0.0.1:6379> Delete user: 581

Redis Keys expire

Another great feature of Redis is the ability to automatically expire keys after a defined number of seconds using the button expired Command. Please note that you may only expire complete keys and not individual elements within a list or hash. For example:

127.0.0.1:6379> expire full_name 10

This sets an expiration time of 10 seconds Full name Key you created in the Strings section. After running the above command, wait 10 seconds and then try again to get the value of the key.

127.0.0.1:6379> get full_name
(Zero)

As expected, the key has now expired, so our result is null.

Connect to Redis using PHP

Now that you've learned the basics of storing and retrieving data with Redis, it's time to connect that to your software. All programming languages ​​have modules / extensions for Redis, but for this example we are using PHP.

You need to install the PHP Redis extension first as it is not installed by default. Run the command in the terminal.

sudo apt-get install php-redis

After installing, make sure to restart PHP-fpm for the extension to load properly. Here is some PHP code that connects and links to Redis.

<? php
// Connect with Redis
$ conn = new redis ();
To attempt {
$ conn-> connect (& # 39; 127.0.0.1 & # 39 ;, 6379, 5);
} catch (RedisException $ e) {
die ("Cannot connect to Redis");
}}
// set string
$ conn-> set (& # 39; Country & # 39 ;, & # 39; Canada & # 39;);
// get the string
$ value = $ conn-> get (& # 39; country & # 39;);
echo "Country is: $ value
";
// Define profile
$ profile = (
& # 39; Username & # 39; => & # 39; Microphone & # 39 ;,
& # 39; full_name & # 39; => & # 39; Mike Smith & # 39 ;,
& # 39; email & # 39; => & # 39; mike@domain.com&#39 ;,
& # 39; Country & # 39; => & # 39; Australia & # 39;
);
// create a hash
$ conn-> hmset (& # 39; user: 188 & # 39 ;, $ profile);
// Get all values ​​of the profile hash
$ values ​​= $ conn-> hgetall (& # 39; user: 188 & # 39;);
print_r ($ values);
// Get the email address only
$ email = $ conn-> hget (& # 39; User: 188 & # 39 ;, & # 39; E-Mail & # 39;);
echo "Email is: $ email
";
// Let the hash expire in 15 seconds
$ conn-> expire (& # 39; user: 188 & # 39 ;, 15);

The example code above should be pretty simple. First it connects to Redis with a 5 second timeout, then a string and hash is set and retrieved. All Redis commands can be executed via OOP by calling them directly from the Redis object as described above.

You are on your way!

Congratulations, you've learned the basics of storing and retrieving data at breakneck speed using the Redis storage engine, including building and connecting to Redis using PHP.

Please note that this article only covers the basics and the Redis Data Types page of the documentation is a great place to further explore Redis and all of its features.

dasung_fe

This e-ink monitor is a programmers and writers dream come true

The Paperlike 253 is a high-resolution 25-inch grayscale monitor from Dasung.

About the author

Matt Dizak
(2 articles published)

More from Matt Dizak

Subscribe to our newsletter

Subscribe to our newsletter for tech tips, reviews, free e-books, and exclusive deals!

One more step …!

Please confirm your email address in the email we just sent you.

Leave a Reply

Your email address will not be published. Required fields are marked *