Home Backend Development PHP Tutorial How Laravel framework uses Redis

How Laravel framework uses Redis

May 31, 2018 pm 03:50 PM
laravel redis method

This article mainly introduces the method of using Redis in the Laravel framework. It analyzes the configuration, usage and related operation precautions of the Redis database in the Laravel framework in detail in the form of examples. Friends in need can refer to it

The example in this article describes how the Laravel framework uses Redis. Share it with everyone for your reference, the details are as follows:

Installation

Using redis in laravel first requires you to install the predis/predis package through Composer:

composer require predis/predis
Copy after login

Configuration

The configuration file of redis is: config/database.php

 'redis' => [
    'client' => 'predis',
    'default' => [
      'host' => env('REDIS_HOST', '127.0.0.1'),
      'password' => env('REDIS_PASSWORD',null),
      'port' => env('REDIS_PORT', 6379),
      'database' => 0,
    ],
  ],
Copy after login

You don’t need to change this when you test it. The other place is the .env file

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Copy after login

These are relevant information. In fact, you don’t need to change it. Let's not talk about the problem of redis cluster here, but let's talk about the use of single redis first.

Test

First you need a route:

//redis测试
Route::get('testRedis','RedisController@testRedis')->name('testRedis');
Copy after login

Utilize The artisan command creates a controller

php artisan make:controller RedisController
Copy after login

Then we introduce the corresponding class and create a method in the controller.

Because after we installed it through composer, the laravel framework has helped us register and support redis in the app.php configuration file, so we can use it directly. (Member class is the data table model I tested myself, so don’t bother with it)

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Member;
use Illuminate\Support\Facades\Redis;
class RedisController extends Controller
{
  public function testRedis()
  {
    Redis::set(&#39;name&#39;, &#39;guwenjie&#39;);
    $values = Redis::get(&#39;name&#39;);
    dd($values);
    //输出:"guwenjie"
    //加一个小例子比如网站首页某个人员或者某条新闻日访问量特别高,可以存储进redis,减轻内存压力
    $userinfo = Member::find(1200);
    Redis::set(&#39;user_key&#39;,$userinfo);
    if(Redis::exists(&#39;user_key&#39;)){
      $values = Redis::get(&#39;user_key&#39;);
    }else{
      $values = Member::find(1200);//此处为了测试你可以将id=1200改为另一个id
     }
    dump($values);
  }
}
Copy after login

Error question

When you complete the above operation and run it, you may get this error:

(1/1) ConnectionException
����Ŀ����������ܾ����޷����ӡ� [tcp://127.0.0.1:6379]
in AbstractConnection.php (line 155)
at AbstractConnection->onConnectionError(&#39;����Ŀ����������ܾ����޷����ӡ�&#39;, 10061)
in StreamConnection.php (line 128)
....
Copy after login

In fact, this problem is not a problem, but many people may get into trouble when they first use it.

This is because the redis service is not installed and started on your server, just like mysql. The prerequisite for use is that it is installed and started successfully.

I tested it under windows, so I will talk about windows. I will write related redis articles in the future, and the installation, startup and use of Linux will be introduced.

First download the windows version: https://redis.io/download

Or use the one I downloaded, the version is: 4.0.8

In fact, the following is also This is a tutorial on how to install Redis in Windows

Extract the compressed package you just downloaded, change the name to Redis (optional) and place it on the C drive

Open the cmd window under this path and enter directly redis.exe

The following content is displayed to indicate that the installation and startup were successful. (Note: If you want to operate from the command line, you should open another cmd window. This cannot be closed)

If you don’t want to go to this directory to start every time, please configure the environment variables.

Now you can rerun the request in Laravel and it will run normally.

Related recommendations:

Detailed explanation of pjax use cases in laravel framework

laravel framework implementation of search function code analysis

The above is the detailed content of How Laravel framework uses Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to use redis cluster zset How to use redis cluster zset Apr 10, 2025 pm 10:09 PM

Use of zset in Redis cluster: zset is an ordered collection that associates elements with scores. Sharding strategy: a. Hash sharding: Distribute the hash value according to the zset key. b. Range sharding: divide into ranges according to element scores, and assign each range to different nodes. Read and write operations: a. Read operations: If the zset key belongs to the shard of the current node, it will be processed locally; otherwise, it will be routed to the corresponding shard. b. Write operation: Always routed to shards holding the zset key.

PostgreSQL performance optimization under Debian PostgreSQL performance optimization under Debian Apr 12, 2025 pm 08:18 PM

To improve the performance of PostgreSQL database in Debian systems, it is necessary to comprehensively consider hardware, configuration, indexing, query and other aspects. The following strategies can effectively optimize database performance: 1. Hardware resource optimization memory expansion: Adequate memory is crucial to cache data and indexes. High-speed storage: Using SSD SSD drives can significantly improve I/O performance. Multi-core processor: Make full use of multi-core processors to implement parallel query processing. 2. Database parameter tuning shared_buffers: According to the system memory size setting, it is recommended to set it to 25%-40% of system memory. work_mem: Controls the memory of sorting and hashing operations, usually set to 64MB to 256M

See all articles