14. Yii 2.0 数据缓存

数据缓存是 将某些数据(一般是查询的结果集)进行缓存,它是最常用的一种缓存方式,一般采用memcache或apc作为缓存介质。
这里以 Yii 2.0 高级版为例,介绍如何使用 Yii 的数据缓存机制(一般用 memcache 作为缓存介质),将及时性要求不高的数据缓存起来,提高页面的响应速度。
首先,修改数据库配置文件  /advanced/common/config/main-local.php,内容如下:

    
     [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=test',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'tablePrefix' => 'basic_',    // 表前缀
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
    ],
];
再来修改组件配置文件  /advanced/common/config/main.php,设置 memcache 缓存介质,内容如下:

    
     dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class'     => 'yii\caching\MemCache',
            'keyPrefix'    => 'advanced_',    // key 的前缀
            'servers'    => [    // 可配多个memcache服务器,分布式
                [
                    'host'    => '127.0.0.1',
                    'port'    => 11211,
                    'weight'=> 100,  //权重,即访问该memcache服务器的概率
                ],
            ],
        ],
    ],    

];
然后,在前台模型层  /advanced/frontend/models 中新建一个模型文件 User.php,内容如下:

    
    select('*')
                             ->from('{{%user}}')
                             ->createCommand()
                             ->queryAll();

        return $res;
    }
}
最后,在前台控制器层  /advanced/frontend/controllers 中新建一个控制器 CacheController.php ,用于测试,内容如下:

    
    cache->delete($key);  // 如果user表有写操作,就删除缓存,以便更新缓存

        $userList = \Yii::$app->cache->get($key);  // 读取缓存
        if ($userList===false) { // 如果缓存不存在
            echo '从数据库中读取数据!'.'
'; $userList = (new User())->getList(); // 从数据库中查询数据 $end = microtime(true); \Yii::$app->cache->set($key, $userList, 10); // 写入缓存,过期时间为10秒,0表示永不过期 } else { echo '从缓存中读取数据!'.'
'; $end = microtime(true); } echo $end-$start.'
'; // 查看读取数据所有的时间 var_dump($userList); // 缓存的操作,常用的方法,除了set、get、delete外,还有mset、mget、flush。 // 缓存介质类的基类文件为 vendor/yiisoft/yii2/caching/Cache.php,如有必要,可以对其进行二次封装,如新建一个CacheHelper.php } } ?>
在浏览器中,访问  http://yii.frontend.com/?r=cache/index,查看测试的效果。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值