原文:基于 Redis 有序集合实现 Laravel 热门浏览文章排行榜功能 | 实战入门篇 | 高性能 Redis 实战
自己修改的部分
<?php
namespace App\Console\Commands;
use App\Models\Post;
use Illuminate\Console\Command;
// use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;
//引用
use GuzzleHttp\Client;
class MockViewPosts extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mock:view-posts';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Mock View Posts';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// 1、先清空 posts 表
Post::truncate();
// // 2、删除对应的 Redis 键
Redis::del('popular_posts');
// // 3、生成 100 篇测试文章
// Post::factory()->count(100)->create();
// dd('111');
// 4、模拟对所有文章进行 10000 次随机访问
for ($i = 0; $i < 1000; $i++) {
$postId = mt_rand(1, 12);
$client = new Client([
//跟域名
'base_uri' => 'http://**.cn',
// 超时
'timeout' => 10000000.0,
]);
$response = $client->get('/posts/' . $postId); //http://localhost/get
}
dd('11');
}
}
//Redis实现热门文章排行榜
Route::get('/posts/popular', 'PostController@popular');
Route::get('/posts/{post}', 'PostController@show');
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
class PostController extends Controller
{
//存入redis数据
public function show($post)
{
// var_dump('22');
// dd($post);
if ($post) {
// 将当前文章浏览数 +1,存储到对应 Sorted Set 的 score 字段
Redis::zincrby('popular_posts', 1, $post);
}
return 'Show Post #' . $post;
}
// 获取热门文章排行榜
public function popular()
{
// 获取浏览器最多的前十篇文章(倒序)
$postIds = Redis::zrevrange('popular_posts', 0, 9);
// dd($postIds);
// 获取浏览器最多的前十篇文章(倒序+排序字段)
$a = Redis::zrevrange ('popular_posts', 0, 9,array('withscores'=>true));
foreach ($a as $k =>$v) {
$data2 = [
'title' => $v,
'views' => $k,
];
DB::table('posts')->insert($data2);
// code...
}
//查询结果排序必须和传入时的
$cha = DB::table('posts')
->select(['id','title','views'])
->get()
->toArray();
dd($cha);
}
}