hyperf会话session操作到redis

发布时间:2021-12-30 10:22:21 阅读:1246次

如何用hyperf来操作session

安装
composer require hyperf/session
php bin/hyperf.php vendor:publish hyperf/session
配置 Session 中间件

修改config/autoload/middlewares.php

<?php
return [
    // 这里的 http 对应默认的 server name,如您需要在其它 server 上使用 Session,需要对应的配置全局中间件
    'http' => [
        \Hyperf\Session\Middleware\SessionMiddleware::class,
    ],
];
配置储存驱动

修改config/autoload/session.php

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\Session\Handler;

return [
    'handler' => Handler\RedisHandler::class, //改为文件则为FileHandler
    'options' => [
        'connection' => 'default',
        'path' => BASE_PATH . '/runtime/session',
        'gc_maxlifetime' => 1200,
        'session_name' => 'HYPERF_SESSION_ID',
        'domain' => null,
        'cookie_lifetime' => 5 * 60 * 60,
    ],
];

创建controller文件

<?php

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;

class TestController
{
    /**
     * @Inject()
     * @var \Hyperf\Contract\SessionInterface
     */
    private $session;

    public function index()
    {
        // 直接通过 $this->session 来使用
        $sessionId = $this->session->getId();
        //return $sessionId;
        //$this->session->set('foo', 'bar');
        //$data = $this->session->all();
        return $this->session->get('foo');
    }

}

然后打开redis

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询
下一篇:hyperf响应处理

转载请注明:hyperf会话session操作到redis 出自老鄢博客 | 欢迎分享