lumen使用predis访问redis集群

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daily886/article/details/84346068

目录

介绍

编辑 bootstrap\app.php

修改环境变量 .env

配置项 修改 vendor\laravel\lumen-framework\config\database.php

配置路由 routes\web.php

配置控制器 创建目录和文件  app\Http\Controllers\Cache\CacheController.php

创建自定义打印方法 app\helpers.php

最后访问 路由地址  http://localhost/cache


介绍

Predis是一个开源的高级密钥值存储。它通常被称为数据结构服务器,因为键可以包含字符串、散列、列表、集和排序集。

在将Redis与Laravel一起使用之前,您将需要通过Composer安装predis/predis包:

扫描二维码关注公众号,回复: 5019262 查看本文章

predis适用于 redis集群架构

composer require predis/predis

 或者,您可以通过PECL安装redisphp扩展。该扩展安装起来更复杂,但对于大量使用Redis的应用程序可能产生更好的性能。

编辑 bootstrap\app.php

<?php

require_once __DIR__.'/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);
// 开启门面
 $app->withFacades();  
// 抽象对象
 $app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

// $app->middleware([
//    App\Http\Middleware\ExampleMiddleware::class
// ]);

// $app->routeMiddleware([
//     'auth' => App\Http\Middleware\Authenticate::class,
// ]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
// 注册redis类
 $app->register(\Illuminate\Redis\RedisServiceProvider::class);
// $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->router->group([
    'namespace' => 'App\Http\Controllers',
], function ($router) {
    require __DIR__.'/../routes/web.php';
});

return $app;

修改环境变量 .env

APP_ENV=local                                                 #开发: local ,测试: testing ,预上线: staging ,正式环境: production
APP_DEBUG=true                                                #开启debug模式
APP_KEY=base64:yl2XKMVlbjke4e/y1kWanFG9ecaCrteWFBTg4QV4je8=   #随机字符串
APP_TIMEZONE=PRC                                              #时区
APP_LOCALE=en                                                 #语言英文

LOG_CHANNEL=daily                                             #日志记录-按天记录 , vendor /laravel/lumen-framework/config/logging.php 可以配置记录多少天内的日志
LOG_SLACK_WEBHOOK_URL=                                        #暂未使用

DB_CONNECTION=mysql                                           #数据库类型
DB_HOST=127.0.0.1                                             #数据库地址
DB_PORT=3306                                                  #数据库端口
DB_DATABASE=laravel                                           #数据库名称
DB_USERNAME=root                                              #用户名
DB_PASSWORD=root                                              #密码
DB_PREFIX=lumen_                                              #表前缀

CACHE_DRIVER=redis                                            #缓存类型
REDIS_HOST_FIRST=10.10.87.241                                 #缓存集群ip
REDIS_HOST_SECOND=10.10.87.242                                #缓存集群ip
REDIS_TIMEOUT=5                                               #缓存集群超时时间
QUEUE_DRIVER=sync                                             #队列驱动 sync 是同步

 

配置项 修改 vendor\laravel\lumen-framework\config\database.php

以下是示例;
default是默认的Redis连接对象名,值是连接对象的参数;app('redis.connection')返回的就是该默认连接对象;

mydefine是笔者定义的Redis连接对象名;通过执行app('redis')->connection('myredis')可以获取该连接对象;

mycluster1是笔者定义的Redis集群对象名;通过执行app('redis')->connection('mycluster1')可以获取该集群对象;

// 修改redis 配置 使用predis
'redis' => [
        'client' => 'predis',
        'default' => [
            'host' => env('REDIS_HOST_FIRST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6301),
            'database' => 1,
            'read_timeout' => env('REDIS_TIMEOUT',5),
        ],
        'myredis' => [
            'host' => env('REDIS_HOST_FIRST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6301),
            'database' => 2,
            'read_timeout' => env('REDIS_TIMEOUT',5),
        ],
        'options' => [
            'cluster' => 'redis',
        ],
        'clusters' => [
            'mycluster1' => [
                [
                    'host' => env('REDIS_HOST_FIRST', '127.0.0.1'),
                    'password' => env('REDIS_PASSWORD', null),
                    'port' => env('REDIS_PORT', 6301),
                    'database' => 0,
                    'read_timeout' => env('REDIS_TIMEOUT',5),
                ],
                [
                    'host' => env('REDIS_HOST_FIRST', '127.0.0.1'),
                    'password' => env('REDIS_PASSWORD', null),
                    'port' => env('REDIS_PORT', 6302),
                    'database' => 0,
                    'read_timeout' => env('REDIS_TIMEOUT',5),
                ],
                [
                    'host' => env('REDIS_HOST_FIRST', '127.0.0.1'),
                    'password' => env('REDIS_PASSWORD', null),
                    'port' => env('REDIS_PORT', 6303),
                    'database' => 0,
                    'read_timeout' => env('REDIS_TIMEOUT',5),
                ],
                [
                    'host' => env('REDIS_HOST_SECOND', '127.0.0.1'),
                    'password' => env('REDIS_PASSWORD', null),
                    'port' => env('REDIS_PORT', 6304),
                    'database' => 0,
                    'read_timeout' => env('REDIS_TIMEOUT',5),
                ],
                [
                    'host' => env('REDIS_HOST_SECOND', '127.0.0.1'),
                    'password' => env('REDIS_PASSWORD', null),
                    'port' => env('REDIS_PORT', 6305),
                    'database' => 0,
                    'read_timeout' => env('REDIS_TIMEOUT',5),
                ],
                [
                    'host' => env('REDIS_HOST_SECOND', '127.0.0.1'),
                    'password' => env('REDIS_PASSWORD', null),
                    'port' => env('REDIS_PORT', 6306),
                    'database' => 0,
                    'read_timeout' => env('REDIS_TIMEOUT',5),
                ],
            ],
        ],

    ],

配置路由 routes\web.php
 

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$router->get('/', function () use ($router) {
    return $router->app->version();
});

$router->get('/cache', 'Cache\CacheController@cache');

配置控制器 创建目录和文件  app\Http\Controllers\Cache\CacheController.php

<?php

namespace App\Http\Controllers\Cache;

use App\Http\Controllers\Controller;

class CacheController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //
    public function cache(){
        echo 123;
        $redis = app('redis')->connection('mycluster1');
        $str = 'awefawe';
        $redis->set('libc',$str);
        $time_start = microtime(true);
        $result = $redis->get('libc');
        $time_end = microtime(true);
        $time = $time_end - $time_start;
        p($result);
        p($time);
        $redis->set('libc1',1231);
        $time_start = microtime(true);
        $result = $redis->get('libc1');
        $time_end = microtime(true);
        $time = $time_end - $time_start;
        p($result);
        p($time);
        $redis->set('libc2',1232);
        $time_start = microtime(true);
        $result = $redis->get('libc2');
        $time_end = microtime(true);
        $time = $time_end - $time_start;
        p($result);
        p($time);
    }
}

创建自定义打印方法 app\helpers.php

<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2018/11/22
 * Time: 16:07
 */

if(!function_exists('p')){
    function p($a){
        echo '<pre>';
        var_dump($a);
        echo '</pre>';
    }
}

修改 composer.json

{
    "name": "laravel/lumen",
    "description": "The Laravel Lumen Framework.",
    "keywords": ["framework", "laravel", "lumen"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/lumen-framework": "5.5.*",
        "vlucas/phpdotenv": "~2.2",
        "illuminate/redis": "^5.5"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "phpunit/phpunit": "~6.0",
        "mockery/mockery": "~0.9"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "app/helpers.php"
        ]
    },
    "autoload-dev": {
        "classmap": [
            "tests/",
            "database/"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ]
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "optimize-autoloader": true
}

# 更新自动加载
composer dump-autoload

最后访问 路由地址  http://localhost/cache

猜你喜欢

转载自blog.csdn.net/daily886/article/details/84346068