Core points
Redis is an open source data structure server with a memory data set that functions far more than simple key-value storage due to its built-in data types. It was launched in 2009 by Salvatore Sanfilippo and has grown rapidly due to its popularity. It was selected by VMware (later hired Sanfilippo to participate in the project full time), GitHub, Craigslist, Disqus, Digg, Blizzard, Instagram and other large companies (see redis.io/topics/whos-using-redis). You can use Redis as a session handler, which is especially useful if you use a multi-server architecture behind a load balancer. Redis also has a publish/subscribe system, which is ideal for creating online chat or live subscription systems. For documentation and more information about Redis and all its commands, visit the project's website redis.io. There is a lot of debate about which Redis or Memcache is better, but as the benchmarks show, they perform almost the same in terms of basic operations. Redis has more features than Memcache, such as memory and disk persistence, atomic commands and transactions, and instead of logging every change to disk, use server-side data structures instead. In this article, we will use the Predis library to learn about some of the basic but powerful commands that Redis provides.
Easy to install
Redis is easy to install, and brief installation instructions are posted on the product's download page. In my experience, if you are running Ubuntu, you will get an error if you don't have TCL installed (just run sudo apt-get install tcl). After installing Redis, you can run the server:
gafitescu@ubun2:~$ /usr/local/bin/redis-server * The server is now ready to accept connections on port 6379
Redis client libraries are available in many languages, which are listed on the Redis website, and each language is usually available in multiple languages! For PHP, there are five. In this article, I'm going to use the Predis library, but you might also want to know about phpredis, which is compiled and installed as a PHP module. If you installed Git on your machine like I did, you just clone the Predis repository. Otherwise, you need to download the ZIP archive and unzip it.
gafitescu@ubun2:~$ /usr/local/bin/redis-server * The server is now ready to accept connections on port 6379
To test everything, create a test.php file with the following to test if you can successfully connect to a running Redis server using Predis:
gafitescu@ubun2:~$ git clone git://github.com/nrk/predis.git
When you run it, you should see the message "Successfully connected to Redis".
Using Redis
In this section, you will outline most of the commonly used commands provided by Redis. Memcache has equivalents for most commands, so if you are familiar with Memcache, this list will look familiar.
SET, GET and EXISTS
The most commonly used commands in Redis are SET, GET, and EXISTS. You can use these commands to store and check temporary information that will be accessed multiple times, usually in key-value ways. For example:
<?php require "predis/autoload.php"; PredisAutoloader::register(); // 由于我们连接到默认设置localhost // 和6379端口,因此无需额外的 // 配置。如果不是,则可以将 // 方案、主机和端口指定为数组 // 传递给构造函数。 try { $redis = new Predis\Client(); /* $redis = new Predis\Client(array( "scheme" => "tcp", "host" => "127.0.0.1", "port" => 6379)); */ echo "Successfully connected to Redis"; } catch (Exception $e) { echo "Couldn't connected to Redis"; echo $e->getMessage(); }
set() method is used to set the value to a specific key. In this example, the key is "hello_world" and the value is "Hi from php!". The get() method retrieves the value of the key, and in this case it is "hello_world". The exists() method reports whether the provided key is found in the Redis store. Keys are not limited to alphanumeric characters and underscores. The following will also be valid:
<?php $redis->set("hello_world", "Hi from php!"); $value = $redis->get("hello_world"); var_dump($value); echo ($redis->exists("Santa Claus")) ? "true" : "false";
INCR (INCRBY) and DECR (DECRBY)
INCR and DECR commands are used to increment and decrement values and are a good way to maintain counters. INCR and DECR increment/decrement their value by 1; you can also adjust with INCRBY and DECRBY at larger intervals. Here is an example:
<?php $redis->set("I 2 love Php!", "Also Redis now!"); $value = $redis->get("I 2 love Php!");
Redis data type
As I mentioned before, Redis has built-in data types. You might think it's weird to have data types in a NoSQL key-value storage system like Redis, but this is useful for developers to organize information more efficiently and perform specific actions, which is usually faster when data typed. The data type of Redis is:
So far I've only demonstrated strings, but there are some commands that make it equally easy to use data from other data types.
HSET, HGET and HGETALL, HINCRBY and HDEL
These commands are used to handle the hash data type of Redis:
Here is an example to demonstrate its usage:
gafitescu@ubun2:~$ /usr/local/bin/redis-server * The server is now ready to accept connections on port 6379
Summary
In this article, we've only covered a short list of Redis commands, but you can view the full list of commands on the Redis website. In fact, Redis offers much more than just a replacement for Memcache. Redis will last; it has a growing community, support for all major languages, and provides persistence and high availability through master-slave replication. Redit is open source, so if you are a C language expert, you can fork its source code from GitHub and become a contributor. If you want to learn more than the project website, you might want to consider checking out two excellent Redis books, Redis Cookbook and Redis: The Definitive Guide.
Frequently Asked Questions about Redis with Predis in PHP
Predis is a flexible and fully functional PHP Redis client library. It allows PHP developers to interact with Redis using PHP code, making it easier to use Redis in PHP applications. Predis provides a simple and intuitive API to handle Redis, and it supports a variety of Redis functions, including transactions, pipelines, and clusters. By using Predis, PHP developers can take advantage of the power of Redis in their applications without having to deal with the complexity of directly interacting with the Redis server.
Predis can be easily installed in PHP projects using Composer (PHP's dependency management tool). You can install Predis by running the following command in the root directory of your project: composer require predis/predis
. This command will download and install the latest stable version of Predis and its dependencies into your project.
To connect to the Redis server using Predis, you need to create a new instance of the PredisClient class and pass the connection parameters to its constructor. The connection parameter can be a string representing the Redis server URI or an associative array containing connection options. Here is an example:
gafitescu@ubun2:~$ git clone git://github.com/nrk/predis.git
In this example, the client will connect to the Redis server running on localhost port 6379.
Predis provides methods for executing all Redis commands. These methods are named after the corresponding Redis command, which accept command parameters as parameters. For example, to set key-value pairs in Redis, you can use the set method as follows:
<?php require "predis/autoload.php"; PredisAutoloader::register(); // 由于我们连接到默认设置localhost // 和6379端口,因此无需额外的 // 配置。如果不是,则可以将 // 方案、主机和端口指定为数组 // 传递给构造函数。 try { $redis = new Predis\Client(); /* $redis = new Predis\Client(array( "scheme" => "tcp", "host" => "127.0.0.1", "port" => 6379)); */ echo "Successfully connected to Redis"; } catch (Exception $e) { echo "Couldn't connected to Redis"; echo $e->getMessage(); }
To get the value of the key, you can use the get method:
gafitescu@ubun2:~$ /usr/local/bin/redis-server * The server is now ready to accept connections on port 6379
Predis will throw an exception when the Redis command fails. These exceptions are instances of the PredisResponseServerException class or its subclass. You can catch these exceptions and handle errors in your code. Here is an example:
gafitescu@ubun2:~$ git clone git://github.com/nrk/predis.git
In this example, if the set command fails, the catch block will be executed and an error message will be printed.
(The answers to the other questions are similar to the previous output, except that the wording is slightly adjusted, and we will not repeat it here)
The above is the detailed content of An Introduction to Redis in PHP using Predis. For more information, please follow other related articles on the PHP Chinese website!