thinkphp6:访问多个redis数据源 --- 2021-06-10

一,配置多个redis库的地址:
.env

APP_DEBUG = true
#APP_DEBUG = false

[APP]
DEFAULT_TIMEZONE = Asia/Shanghai

[REDIS0]
TYPE = redis
HOST = 127.0.0.1
PORT = 6379
PASSWORD =

[REDIS1]
TYPE = redis
HOST = 127.0.0.1
PORT = 6380
PASSWORD =

[LANG]
default_lang = zh-cn

二,配置php到redis的连接
config/cache.php

<?php

// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------

return [
    // 默认缓存驱动
    'default' => env('cache.driver', 'file'),

    // 缓存连接方式配置
    'stores'  => [
        'file' => [
            // 驱动方式
            'type'       => 'File',
            // 缓存保存目录
            'path'       => '',
            // 缓存前缀
            'prefix'     => '',
            // 缓存有效期 0表示永久缓存
            'expire'     => 0,
            // 缓存标签前缀
            'tag_prefix' => 'tag:',
            // 序列化机制 例如 ['serialize', 'unserialize']
            'serialize'  => [],
        ],
        // 更多的缓存连接
        'redis0'    =>    [
            'type'     => env('redis0.type', 'redis'),
            'host'     => env('redis0.host', '127.0.0.1'),
            'port'     => env('redis0.port', '6379'),
            'password' => env('redis0.password', ''),
            'select'   => '0',
            // 全局缓存有效期(0为永久有效)
            'expire'   => 0,
            // 缓存前缀
            'prefix'   => '',
            'timeout'  => 0,
        ],
        // 更多的缓存连接
        'redis1'    =>    [
            'type'     => env('redis1.type', 'redis'),
            'host'     => env('redis1.host', '127.0.0.1'),
            'port'     => env('redis1.port', '6380'),
            'password' => env('redis1.password', ''),
            'select'   => '0',
            // 全局缓存有效期(0为永久有效)
            'expire'   => 0,
            // 缓存前缀
            'prefix'   => '',
            'timeout'  => 0,
        ],
    ],
];

三,如何访问多个redis数据源,看例子:
api/controller/UserController.php

<?php
namespace app\api\controller;

use think\facade\Cache;


class UserController
{
    public function index()
    {
        //访问redis0
        Cache::store('redis0')->set('name0','value1234',3600);
        $value0 = Cache::store('redis0')->get("name0");
        //访问redis1
        Cache::store('redis1')->set('name1','value5678',3600);
        $value1 = Cache::store('redis1')->get("name1");
        //返回
        return '您好![userindex],<br/>redis0 value0:'.$value0."<br/>redis1 value1:".$value1;
    }

    public function test() {
        return "this is usercontroller test";
    }
}

四,测试效果
1,访问:
http://127.0.0.1:81/api/user/index

2,从命令行查看redis中保存的数据:

# /usr/local/soft/redis6/bin/redis-cli -p 6380
127.0.0.1:6380> get name1
"s:9:\"value5678\";"
127.0.0.1:6380> exit
# /usr/local/soft/redis6/bin/redis-cli -p 6379
127.0.0.1:6379> get name0
"s:9:\"value1234\";"

以上为使用thinkphp6框架配置两个redis访问的数据源,再增加原理一样;

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容