Yii2 redis sync data to mysql

Write redis data to mysql:

This case explains how to record the number of product views in the mall through the cache and write it into mysql.
The specific redis installation process will be omitted for the time being.....

1. Install the redis plugin | configure redis

composer require yiisoft/yii2-redis

Find the common config file and add the redis configuration parameters under components

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

2. Establish redis
Create a redis record before displaying the product details page. Whenever a user accesses the page, a judgment is made on redis. If there is no redis, it will be established and assigned a value of 1. If it already exists, it will be based on the original data. +1

 //将商品访问写入到redis中
        $redisObj = Yii::$app->redis;
        $visitsData = $redisObj->get('goods_visits');

        //反序列化访问数据
        $visitsData = empty($visitsData)?[]:unserialize($visitsData);

        if (isset($visitsData[$id])) {
            $visitsData[$id] += 1;
        }else{
            $visitsData[$id] = 1;
        }

        //序列化后的数据格式为{商品id:浏览次数}
        $visitsData = serialize($visitsData);
        $redisObj->set('goods_visits',$visitsData);

3. Write redis into the database
Create a new controller, obtain the existing redis through the redistomysql method to judge, if it is empty, return true, otherwise synchronize to Mysql, and delete the redis data after the synchronization is completed

public function actionRedistomysql()
    {
        //从redis中查询所有商品信息
        $redisObj = Yii::$app->redis;
        $visits = $redisObj->get("goods_visits");

        //三元表示判断redis是否为空
        $visitsArr = empty($visits)?[]:unserialize($visits);

        if (empty($visitsArr)) {
            return true;
        }

        //将浏览数据写入数据库
        foreach ($visitsArr as $k=>$v)
        {
            $goodsModle = Goods::findOne($k);
            $goodsModle->visites += $v;
            //如果数据存储成功则删除对应的数据
            if ($goodsModle->save() !== false) {
                unset($visitsArr[$k]);
            }
            //延迟2秒防止高频率读取数据库
            sleep(2);
        }

        //删除redis中商品浏览数据
        $redisObj->del("goods_visits");

        if (empty($visitsArr)) {
            return true;
        }

        $redisObj->set('goods_visits',serialize($visitsArr));
}

4. Check whether redis is successfully established
First visit the product details page, then enter the Linux server, (after redis is installed successfully) execute redis-cli, enter the redis console, execute get goods_visits (created redis name), if the situation is as follows, refresh the goods Details page

redis1.jpg

The success page is as follows:

redis2.png

At this point, the basic steps of redis synchronizing data to Mysql have been completed, but each execution needs to be accessed manually, so here we need a method that can automatically execute it, because this project is running under linux, so use crontab Execute tasks regularly, if it is under Windows, use the task plan.....

First execute the crontab -e command to enter the linux timed task settings
Basic format:
* * * * * command (the address of the execution method, such as: http://www.xxxx.com/cront/redistomysql ) Time-
sharing day-month-week command
No. 1 Columns indicate minutes 1 to 59. Each minute is represented by * or */1
. Column 2 indicates hours 1 to 23 (0 indicates 0 o'clock)
. Column 3 indicates
date
. Week 0~6 (0 means Sunday)
The command to be run in column 6

Visit the product details page, and then wait until the set time to check whether the data exists in the database. If there is data, then your redis has been set successfully. If there is no data, you need to check your code or whether the settings are correct. This time This is the end of the introduction to the use of redis.



Author: meteorites
Link: https://www.jianshu.com/p/7b58bd6c8f97
Source: Jianshu
The copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

 
 
G
M
T
 
 
Detect languageAfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu
 
AfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu
 
 
 
 
 
 
 
 
 
Text-to-speech function is limited to 200 characters
 
 
Options : History : Feedback : Donate Close

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325256016&siteId=291194637
Recommended