首先我们需要知道redis 是什么?
Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Hash), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。

整合redis 进yii2框架,并将缓存的内容存储在redis中

'components'	=>	[
	'redis' => [
       'class'     =>  'yii\redis\Connection',
        'hostname'  =>  '',//redis 服务地址
        'password'  =>  '',//如果redis 连接需要密码,请在这里填写redis的连接密码
        'port'      =>  6379,//连接redis的端口号
        'database'  =>  '0',//选择数据库
    ],

	//将缓存写进redis中缓存
    'cache' => [
		'class'	=>	'yii\redis\Cache'
	],

	//将session 写进redis中缓存
	'session'	=>	[
		'class'	=>	'yii\redis\Session',
		'redis'	=>	'redis'
	]
]


//在yii2中使用redis
<?php
namespace app\controllers;

use yii\web\Controller;
use Yii;

class IndexController extends Controller
{
   /**
	* 使用redis 服务
	*/
	public function actionIndex()
	{
		Yii::$app->response->format = \yii\web\Response::FORMAT_HTML;

		$_redis = Yii::$app->redis;
	
		$key = "test_key";		

		$value = $_redis->get(key);

		if($value)
		{
			return "从缓存中获取的数据:{value }";
		}else{
			//向redis中存储数据
			$_redis->set($key,"name:谭勇  age:24");
			//设置生命周期
			$_redis->expire($key,20);
			$value = $_redis->get(key);
			return "存储数据成功 : {value }";
		}
	}
	
	/**
     * 缓存使用和session 使用  和原来不变,只是将内容从原来的地方换到了redis当中存储
     */
}


?>

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐