Redis
Introduction
Redis is an open source, advanced key-value pair storage database. Because it contains String, Hash, List, Set, and Ordered Set these data types , so it is often called a data structure server.
Before using Laravel's Redis, you need to install
predis/predis
extension package through Composer:composer require predis/predis
Or, you can also install PhpRedis# through PECL ## PHP extension. This extension is more complex to install, but may yield better performance for applications that make heavy use of Redis.
ConfigurationThe Redis configuration of Laravel application is in the configuration fileconfig/database.php
middle. In this file, you can see that the
redisarray contains the Redis server information used by the application:
'redis' => [ 'client' => 'predis', 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => env('REDIS_DB', 0), ], 'cache' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => env('REDIS_CACHE_DB', 1), ], ],
The default server configuration should be sufficient for development. Of course, you can also change this array at will according to the environment used. Simply specify the name, host, and port for each Redis server in the configuration file. Cluster configurationIf your application uses Redis server clusters, you should use theclusters
key in the Redis configuration file to define these clusters:
'redis' => [ 'client' => 'predis', 'clusters' => [ 'default' => [ [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ], ],
By default, the cluster can implement client-side sharding on the nodes, allowing you to implement node pools and create large amounts of available memory. Note here that client sharing does not handle failure cases; therefore, this feature is primarily suitable for cached data obtained from another master database. If you want to use the Redis native cluster, you need to specify the following in theoptions
key under the configuration file:
'redis' => [ 'client' => 'predis', 'options' => [ 'cluster' => 'redis', ], 'clusters' => [ // ... ], ],
PredisIn addition to the defaulthost
,
port,
database, and
passwordthese service configuration options, Predis also supports defining other connection parameters
connection parameters for each Redis server. If you want to use these additional configuration options, you can add the following configuration to the Redis server's configuration file config/database.php:
'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, 'read_write_timeout' => 60, ],
PhpRedis
To use the PhpRedis extension, you need to change the
client
option of the Redis configuration in the configuration fileconfig/database.php
tophpredis
:'redis' => [ 'client' => 'phpredis', // 其余的Redis配置... ],
In addition to the default
host
,port
,database
andpassword
these service configuration options, PhpRedis Several additional connection parameters are also supported:persistent
,prefix
,read_timeout
andtimeout
. You can add these configuration options to the configuration fileconfig/database.php
under the Redis service configuration item:'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, 'read_timeout' => 60, ],
Redis interaction
You can interact with Redis by calling various methods on the
Redis
facade.Redis
The facade supports dynamic methods, which means you can call various Redis commands on the facade, and the commands will be passed directly to Redis. In the example, theGET
command on Redis will be called via theget
method on theRedis
facade:<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Redis; class UserController extends Controller{ /** * 显示给定用户的配置文件。 * * @param int $id * @return Response */ public function showProfile($id) { $user = Redis::get('user:profile:'.$id); return view('user.profile', ['user' => $user]); } }
As mentioned above, you Any Redis command can be called on the
Redis
facade. Laravel uses magic methods to pass commands to the Redis server, so just pass the parameters required by the Redis command:Redis::set('name', 'Taylor'); $values = Redis::lrange('names', 5, 10);
Alternatively, you can also use the
command
method to pass the command to the server , which accepts the name of the command as its first argument and an array of values as its second argument:$values = Redis::command('lrange', ['name', 5, 10]);
Using multiple Redis connections
you A Redis instance can be obtained through the
Redis::connection
method:$redis = Redis::connection();
This will return a default Redis instance. You can pass the connection or cluster name to the
connection
method to get a specific service or cluster in the Redis configuration:$redis = Redis::connection('my-connection');
Pipeline Command
When you need to send many commands to the server in one operation, it is recommended that you use the pipeline command. The
pipeline
method accepts aClosure
of a Redis instance. You can send all commands to the Redis instance and they will be executed in one operation:Redis::pipeline(function ($pipe) { for ($i = 0; $i < 1000; $i++) { $pipe->set("key:$i", $i); } });
Publish and Subscribe
Laravel provides convenient interfaces for Redis's
publish
andsubscribe
. These Redis commands allow you to listen for messages on a specified "channel". You can publish messages from another application to another application, even using other programming languages, allowing applications and processes to communicate easily.First, we use the
subscribe
method to set up the channel listener. We place this method call in the Artisan command because calling thesubscribe
method starts a long-running process:<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Redis; class RedisSubscribe extends Command{ /** * 控制台命令的名称和签名。 * * @var string */ protected $signature = 'redis:subscribe'; /** * 控制台命令说明。 * * @var string */ protected $description = 'Subscribe to a Redis channel'; /** * 执行控制台命令。 * * @return mixed */ public function handle() { Redis::subscribe(['test-channel'], function ($message) { echo $message; }); } }
Now we can use the
publish
method to Messages are published to the channel:Route::get('publish', function () { // 路由... Redis::publish('test-channel', json_encode(['foo' => 'bar'])); });
Wildcard subscription
Use the
psubscribe
method to subscribe to the wildcard channel, which can be used to get all messages on all channels .$channel
The name will be passed as the second parameter to the provided callbackClosure
:Redis::psubscribe(['*'], function ($message, $channel) { echo $message;});Redis::psubscribe(['users.*'], function ($message, $channel) { echo $message; });