An Introduction to Redis in PHP using Predis
Core points
- Redis is a popular open source data structure server that features far more than simple key-value storage thanks to its built-in data types. It is widely used by large companies and can be used as a session handler or to create online chat or live booking systems.
- Redis and Memcache perform similarly in terms of basic operations, but Redis provides more features such as memory and disk persistence, atomic commands and transactions, and server-side data structures.
- Predis is a flexible and fully functional PHP Redis client library that allows PHP developers to interact with Redis using PHP code. It supports a variety of Redis features, including transactions, pipelines, and clusters.
- Redis commands include SET, GET, EXISTS (for storing and checking temporary information), INCR and DECR (for maintaining counters), HSET, HGET, HINCRBY and HDEL (for processing hash data types), and EXPIRE, EXPIREAT, TTL, and PERSIST (for processing data persistence).
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:
- String - The basic data type used in Redis, from which you can store a small number of characters to the contents of the entire file.
- List - A simple list of strings arranged in the order in which their elements are inserted. You can add and remove elements from the head and tail of a list, so you can use this data type to implement a queue.
- Hash - Map of string keys and string values. This way you can represent an object (that can be considered as a level one-level depth JSON object).
- Collection - An unordered collection of strings where you can add, delete and test the presence of members. The only constraint is that you do not allow duplicate members.
- Sorting sets—Special case of collection data types. The difference is that each member has an associated score that is used to sort the set from the smallest score to the maximum score.
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:
- HSET—Set the value of the key on the hash object.
- HGET - Get the value of the key on the hash object.
- HINCRBY—Increment the value of the hash object's key using the specified value.
- HDEL - Remove key from object.
- HGETALL - Get all keys and data of the object.
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
- What is the main purpose of using Predis and Redis 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.
- How to install Predis in PHP project?
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.
- How to use Predis to connect to a Redis server?
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.
- How to use Predis to execute Redis commands?
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
- How to handle errors in Predis?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Alipay PHP...

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.
