yii2使用redis

yii的redis组件是基于socket直接连接的,不需要php-redis扩展

安装yii2-redis

在你的config文件的components节点添加

'redis' => [
    'class' => 'yii\redis\Connection',
    'hostname' => 'localhost',
    'port' => 6379,
    'database' => 0,
    'password' => 'yourpass',
],

防延迟设置

#修改php.ini,设置:
default_socket_timeout = -1
#或者在程序入口添加
ini_set('default_socket_timeout', -1);

用法

$redis = Yii::$app->redis;
//设置键值
$redis->set('name','buyue');
//获取键的值
$val = $redis->get('name');
//获取所有键的列表
$all = $redis->keys('*');
//删除键
$redis->del('name');
//清空所有db的缓存
$redis->flushall();
//清空当前db的缓存
$redis->flushdb();

//加入到列表

//从左边插入列表,后进先出
$redis->lpush('mylist1','i1');
$redis->lpush('mylist1','i2');
$redis->lpush('mylist1','i3');
//获取列表中的某一段
$list1 = $redis->lrange('mylist1',0,2);

//从右边插入列表,先进先出
$redis->rpush('mylist2','i4');
$redis->rpush('mylist2','i5');
$redis->rpush('mylist2','i6');
//获取列表中的某一段
$list2 = $redis->lrange('mylist2',0,2);

//对列表的某索引的值进行修改
$redis->lset('mylist2',0,'12345');

//哈希
$redis->hmset('info','name','buyue','job','developer');
$hash = $redis->hgetall('info');
//集合
$redis->sadd('arr','buyue','developer');
//获取集合成员
$arr = $redis->smembers('arr');
//获取集合成员数量
$arr = $redis->scard('arr');

//有序集合
$redis->zadd('info','1','buyue','2','developer');
$count = $redis->zcard('info');
//索引区间内取值
$arr = $redis->zrange('info',0,2);

//发布订阅
$redis->psubscribe('redisChat');

Session
yii2默认的session组件是yii\web\Session,这里改用yii\redis\Session

'components' => [
    'session' => [
        'class' => 'yii\redis\Session',
        //'keyPrefix' => 'yourkey',
        'redis' => [
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
            'password' => 'yourpass',
        ]
    ],
],
//或者
'components' => [
     //redis
    'redis' => [
        'class' => 'yii\redis\Connection',
        'hostname' => 'localhost',
        'port' => 6379,
        'database' => 0,
        'password' => 'yourpass',
    ],
    //session
    'session' => [
        'class' => 'yii\redis\Session',
        //'keyPrefix' => 'yourkey',
        'redis' => 'redis',
    ],
],

Cache

'components' => [
    'cache' => [
       'class' => 'yii\redis\Cache',
       'redis' => 'redis'
    ],
],
$cache = Yii::$app->cache1;
$cache->set('name','buyue');
$val = $cache->get('name');

你可能感兴趣的:(Redis,php,yii2)