hyperf session会话管理

安装session组件

composer require hyperf/session

生成session配置文件 config/autoload/session.php

php bin/hyperf.php vendor:publish hyperf/session
<?php

declare(strict_types=1);

use Hyperf\Session\Handler;

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

添加session中间件

<?php

declare(strict_types=1);

return [
        'http' => [
                \Hyperf\Session\Middleware\SessionMiddleware::class
        ],
];

控制器 app/Controller/IndexController.php

<?php
namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;

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

        public function index(){
                $this->session->set('name', 'huyongjian');
                $name = $this->session->get('name');
                return $name;
        }
}

测试访问

curl 118.195.173.53:9501/index/index

返回结果

huyongjian

session文件路径: runtime/session/

使用Redis驱动

修改session配置文件

<?php

declare(strict_types=1);

use Hyperf\Session\Handler;

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

安装redis组件

composer require hyperf/redis

redis配置文件 config/autoload/redis.php

<?php

declare(strict_types=1);

return [
    'default' => [
        'host' => env('REDIS_HOST', 'redis'),
        'auth' => env('REDIS_AUTH', null),
        'port' => (int) env('REDIS_PORT', 6379),
        'db' => (int) env('REDIS_DB', 0),
        'pool' => [
            'min_connections' => 1,
            'max_connections' => 10,
            'connect_timeout' => 10.0,
            'wait_timeout' => 3.0,
            'heartbeat' => -1,
            'max_idle_time' => (float) env('REDIS_MAX_IDLE_TIME', 60),
        ],
    ],
];

生成session文件

sudo rm -rf runtime/session

访问测试

curl 118.195.173.53:9501/index/index

返回结果

huyongjian

redis-cli进入Redis可以看到有新key,runtime/session 没有文件生成

session使用

储存数据

$this->session->set('name', 'huyongjian);

获取数据

$this->session->get('name', $default = null);

获取所有数据

$this->session->all();

判断是否存在key

$this->session->has('name')

删除数据

$this->session->forget('name');
$this->session->forget(['name', 'name2']);

清空数据

$this->session->clear();

获取sessionID

$this->session->getId();
posted @ 2021-09-23 17:37  胡勇健  阅读(395)  评论(0)    收藏  举报