首先須要構造數據的基本格式,如命令 php
hmset news105 news_title title105 news_content content105 news_views 28
拆分紅如下格式:mysql
*8 // 按空格拆分有幾段 $5 // 表明 hmset 的字符長度 hmset $7 // 表明 news105 的字符長度,以此類推· news105 $10 news_title $8 title105 $12 news_content $10 content105 $10 news_views $2 28
數據表(news)結構:redis
利用 sql 拼接數據(news.sql):sql
select concat('*8','\r\n','$5','\r\n','hmset','\r\n','$',LENGTH(news_id)+4,'\r\n','news',news_id,'\r\n' ,'$10','\r\n','news_title','\r\n','$',LENGTH(news_title),'\r\n',news_title,'\r\n','$12','\r\n','news_content','\r\n' ,'$',LENGTH(news_content),'\r\n',news_content,'\r\n','$10','\r\n','news_views','\r\n','$',LENGTH(news_views),'\r\n',news_views ,'\r') from news order by news_views desc limit 0,5
導出 sql 執行結果(news):數據庫
mysql -uroot -p123456 -D 數據庫名 --skip-column-names --raw < news
至此,數據構造完畢。批量插入 redis:fetch
cat news | redis-cli --pipe
查看結果:spa
preheat.php:3d
<?php $redis = new Redis(); $redis->connect('Redis服務端IP',6379); $redis->multi(Redis::PIPELINE); $newsPreData = getDataBySQL("select news_id,news_title,news_views from news order by news_views desc limit 0,5"); foreach($newsPreData as $row) { $key="news".$row["news_id"]; // 拼接key // 批量插入 $redis->hMset($key, [ "news_id"=>$row["news_id"], "news_title"=>$row["news_title"], "news_views"=>$row["news_views"] ]); $redis->expire($key, 200); } $redis->exec(); echo "done...".PHP_EOL; // 從數據庫讀取 function getDataBySQL(String $sql) { $dsn = 'mysql:host=MySQL服務端IP;dbname=redis'; $pdo=new PDO($dsn, "root", "123456"); $sth = $pdo->prepare($sql); $sth->execute(); $sth->setFetchMode(PDO::FETCH_ASSOC); return $sth->fetchAll(); }
執行該腳本:code
查看結果:blog