• Yii缓存机制yii\caching\Cache


    一:缓存组件配置

    在Yii中常用的缓存方式有

    • yii\caching\FileCache:文件缓存

    • yii\caching\ApcCache:APC缓存,需要安装PHP的APC拓展

    • yii\caching\DbCache:数据库缓存,需要创建一个缓存表

    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->createTable('{{%cache}}', [
            'id' => $this->char(128)->defaultValue('')->comment('缓存ID'),
            'expire' => $this->integer()->defaultValue(0)->comment('到期时间'),
            'data' => $this->getDb()->getSchema()->createColumnSchemaBuilder('blob')->comment('缓存数据'),
            'PRIMARY KEY ([[id]], [[expire]])',
        ], 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB COMMENT=\'缓存表\'');
    }
    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('{{%cache}}');
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • yii\caching\MemCache:使用使用 PHP memcache 和 memcached 扩展进行缓存存储

    • yii\redis\Cache:redis缓存,需要安装yiisoft/yii2-redis拓展

    composer require yiisoft/yii2-redis
    
    • 1

    二:数据查询缓存

    参考:https://www.yiichina.com/doc/guide/2.0/caching-data

    数据查询缓存两种方式:使用yii\db\Connection实例来实现查询缓存和使用模型实现查询缓存

    1:使用yii\db\Connection实例来实现查询缓存
    $db = Yii::$app->db;
    $result = $db->cache(function ($db) {
        // SQL查询的结果将从缓存中提供
        // 如果启用查询缓存并且在缓存中找到查询结果
        return $db->createCommand('SELECT * FROM yii_user WHERE id=1')->queryOne();
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    2:使用模型实现查询缓存
    $result = User::getDb()->cache(function ($db) {
       return User::findOne(1);
    });
    
    • 1
    • 2
    • 3

    上面的cache方法一共有三个参数

    cache(callable $callable, $duration = null, $dependency = null)
    
    • 1

    自 2.0.14 以后,您可以使用以下快捷方法:

    User::find()->cache(7200)->all();
    
    • 1

    上面的cache方法一共有两个参数

    cache($duration = true, $dependency = null)
    
    • 1

    参数说明:

    • callable:匿名函数,需要缓存的sql查询数据

    • duration:缓存过期时间参数,该参数表示缓存数据可保持的有效时间(单位为秒),为非必填项

    • dependency:缓存依赖参数,如当一个缓存数据的缓存依赖信息发生了变化之后,这时候缓存数据就会被设为失效,及过期

    常用的缓存依赖有:

    • yii\caching\ChainedDependency:如果依赖链上任何一个依赖产生变化,则依赖改变。

    • yii\caching\DbDependency:如果指定 SQL 语句的查询结果发生了变化,则依赖改变。

    • yii\caching\FileDependency:如果文件的最后修改时间发生变化,则依赖改变。

    示例:

    $result = User::find()->cache(100, new \yii\caching\ChainedDependency([
        'dependencies' => [
            new \yii\caching\DbDependency([
                'sql' => 'SELECT MAX(update_time) FROM' . User::tableName()
            ]),
            new \yii\caching\FileDependency([
                'fileName' => 'text.txt'
            ]),
        ]
    ]))->count();
    
    
    $result = User::find()->cache(100, new \yii\caching\DbDependency([
        'sql' => 'SELECT MAX(update_time) FROM' . User::tableName()
    ]))->count();
    
    
    $result = User::find()->cache(100, new \yii\caching\FileDependency([
        'fileName' => 'text.txt'
    ]))->count();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    三:片段缓存

    参考:https://www.yiichina.com/doc/guide/2.0/caching-fragment

    片段缓存指的是缓存页面内容中的某个片段,如:在html中,你想要将一段html片段缓存起来,避免每次请求都重新生成此段html片段,这时候就可以使用片段缓存

    示例:

    如下就将html片段片段进行了缓存

    beginCache('key')):?>  
        html片段
    endCache();
        endif;
    ?>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    参数说明:

    beginCache($id, $properties = [])
    
    • 1
    • $id:缓存Id

    • $properties:缓存配置数组,缓存数组中常见的配置参数有:duration(缓存过期事件,单位为秒),dependency(缓存依赖),enabled(开关,默认为true,表示开启缓存,false为关闭缓存)

    四:页面缓存

    参考:https://www.yiichina.com/doc/guide/2.0/caching-page

    页面缓存指的是在服务器端缓存整个页面的内容。 随后当同一个页面被请求时,内容将从缓存中取出,而不是重新生成,页面缓存由 yii\filters\PageCache 类提供支持,这个类是一个过滤器,所以如果你需要使用页面缓存,只需要在控制器的behaviors方法中引入yii\filters\PageCache类即可

    示例:

    /**
     * 缓存过滤器
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            //内容将从缓存中取出进行渲染
            'pageCache' => [
                'class' => 'yii\filters\PageCache',
                //执行index操作时启用缓存
                'only' => ['index'],
                //缓存过期时间为60秒
                'duration' => 60,
                //当考试和公告变换时,重新进行缓存
                'dependency' => [
                    'class' => 'yii\caching\ChainedDependency',
                    'dependencies' => [
                        new \yii\caching\DbDependency([
                            'sql' => 'SELECT MAX(update_time) FROM ' . Exam::tableName() . ' WHERE status=' . Exam::STATUS_ENABLE
                        ]),
                        new \yii\caching\DbDependency([
                            'sql' => 'SELECT MAX(update_time) FROM ' . ExamNotice::tableName() . ' WHERE status=' . ExamNotice::STATUS_ENABLE
                        ]),
                        new \yii\caching\DbDependency([
                            'sql' => 'SELECT MAX(update_time) FROM ' . Content::tableName() . ' WHERE status=' . Content::STATUS_ENABLE
                        ]),
                    ]
                ],
            ],
        ]);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    五:HTTP缓存

    参考:https://www.yiichina.com/doc/guide/2.0/caching-http

    前面讲到的缓存都是服务端缓存,在Yii中还可以使用客户端缓存去节省相同页面内容的生成和传输时间,即HTTP缓存,HTTP缓存使用到了yii\filters\HttpCache类,这个类也是一个过滤器,所以你要使用HTTP缓存,及在控制器的behaviors方法中引入yii\filters\HttpCache类,。 HttpCache 过滤器仅对 GET 和 HEAD 请求生效, 它能为这些请求设置三种与缓存有关的 HTTP 头:Last-Modified,Etag,Cache-Control

    示例:

    /**
     * 缓存过滤器
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'httpCache' => [
                'class' => 'yii\filters\HttpCache',
                //执行index操作时启用缓存
                'only' => ['index'],
                //当RTag头信息发生变化时, HTTP缓存失效,重新生成缓存
                'etagSeed' => function ($action, $params) {
                    $page = Yii::$app->request->get('page');
                    return serialize([$page]);
                },
            ],
        ]);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    SolidWorks 入门笔记03:生成工程图和一键标注
    Redis Cluster 为什么不支持传统的事务模型
    常见的CSS样式
    1800_vim的宏录制功能尝试
    《OpenDRIVE1.6规格文档》5
    算法通关村第十关黄金挑战——归并排序详解
    C#学习系列之UDP同端口收发问题
    Spring Boot 版本 GA、RC、beta等含义
    PHP代码示例 - 创建、读取、增加、删除、修改 xml
    Jaya算法在电力系统最优潮流计算中的应用(创新点)【Matlab代码实现】
  • 原文地址:https://blog.csdn.net/huaweichenai/article/details/133684633