Redis implementation of ranking ideas

Redis implementation ranking ideas

Those who read this article must have just learned redis. This article is the ranking function implemented by the blogger after learning redis. It uses the tp6 framework. Other web frameworks can be configured by themselves!

Redis implementation ranking ideas

  • Redis implementation of ranking ideas
    • 1. tp6 configure redis cache `config\cache.php`
    • 2. Use zset ordered collection to collect popularity information
    • 3. Breakthrough: Binding heat and time in the controller

1. tp6 configuration redis cache config\cache.php

<?php

// + -------------------------------------------------- -----------------------
// | cache settings
// | Make sure the redis server is turned on. It is recommended to study this blog with a redis foundation.
// + -------------------------------------------------- -----------------------

return [
    //Default cache driver
    'default' => env('cache.driver', 'redis'),

    // Cache connection mode configuration
    'stores' => [
        'redis' => [
            // drive mode
            'type' => 'redis',
            'host' => '127.0.0.1',
            'port' => 6379,
        ],
        // More cached connections
    ],
];

For this redis configuration file, you can refer to the source code of thinkphp. There are related configuration option files. Just select redis.
vendor\topthink\framework\src\think\cache\driver\Redis.php

2. Use zset ordered collection to collect popularity information

zadd adds an ordered set
zcard counts the number of ordered sets
zrem removes elements from a sorted set

 /**
     * Add post name and popularity
     */
    public function add()
    {<!-- -->
    //Add form information using interface testing tool
        $data['title'] = request()->post('title');
        $data['hot'] = (int)request()->post('hot', 0);

        //Add redis
        cache()->zadd('topic', $data['hot'], $data['title']);
        
//redis only saves the first 5 pieces of data
        if (cache()->zcard('topic') > 5) {<!-- -->
        //Remove the last ranked data
            cache()->zrem('topic', cache()->zrange('topic', '0', '-1')[0]);
        }

        return json_encode(['code'=>200,'msg'=>'insert success']);
    }

Use apipost to add data and use the reids command line to view cached data
redis command: zrevrange topic 0 -1 withscores
Reference: https://www.redis.net.cn/tutorial/3512.html

3. Breakthrough: Binding heat and time in controller

After implementing the basic ranking list, the rest is business logic, such as using time nodes as classification, or hot information consisting of a series of algorithms such as likes + retweets + comments. Next, we will introduce the implementation of time based on simply using redis. Classification!
Source code path: https://github.com/xiaopacairq/tpAdmin

  1. When the popularity is cached into reids, the current timestamp is spliced to the back of the popularity
 /**
     * Add post name and popularity
     */
    public function add()
    {<!-- -->
        $data['title'] = request()->post('title');
        $data['hot'] = (int)request()->post('hot', 0);

        //Add redis
        cache()->zadd('topic_v4', $data['hot'] . time(), $data['title']);

        return json_encode(['code'=>200,'msg'=>'insert success']);
    }

  1. Make some judgment logic based on time

The logic here can be customized. The main thing is to know the idea of implementation. The core point is 1. Points 2 and 3 are just for reference.

 public function index()
    {<!-- -->
//Get get as a conditional judgment
        $type = request()->get('type');
        if (empty($type) || $type == 'all') {<!-- -->
            $where = null;
        }
        if ($type == 'day') {<!-- -->
            $where = $this->actionDay();
        }
        if ($type == 'week') {<!-- -->
            $where = $this->actionWeek();
        }
        if ($type == 'month') {<!-- -->
            $where = $this->actionMonth();
        }
        if ($type == 'year') {<!-- -->
            $where = $this->actionYear();
        }

//Get the redis data and splice the array
        $data['res'] = [];
        $title_list = cache()->zrevrange('topic_v4', '0', '-1');
        if (!empty($title_list)) {<!-- -->
            for ($i = 0; $i < count($title_list); $i + + ) {<!-- -->
                $score = (int)cache()->zscore('topic_v4', $title_list[$i]);
                $add_time = strtotime(date("Y-m-d H:i:s", substr($score, -10)));

                if ($where == null) {<!-- -->
                    $data['res'][] = [
                        'title' => $title_list[$i],
                        'hot' => str_replace($add_time, "", $score),
                        'add_time' => $add_time
                    ];
                } else if ($add_time >= $where[0] & amp; & amp; $add_time <= $where[1]) {<!-- -->

                    $data['res'][] = [
                        'title' => $title_list[$i],
                        'hot' => str_replace($add_time, "", $score),
                        'add_time' => $add_time
                    ];
                }
            }
        }
        halt($data);
    }

After splicing a two-dimensional array, the client can call it to get the corresponding ranking!

time interval function

// Get the start and end time of the day
    public function actionDay()
    {<!-- -->
        $time = time();
        $start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, date("m", $time), date("d", $time), date("Y", $time))));
        $end = strtotime(date("Y-m-d H:i:s", mktime(23, 59, 59, date("m", $time), date("d", $time), date("Y", $time))));

        return [$start, $end];
    }
    // Get the start and end time of the current week
    public function actionWeek()
    {<!-- -->
        $time = time();
        $start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, date("m", $time), date("d", $time) - date("w", $time) + 1, date("Y", $time))));
        $end = strtotime(date("Y-m-d H:i:s", mktime(23, 59, 59, date("m", $time), date("d", $time) - date("w", $time) + 7, date("Y", $time))));

        return [$start, $end];
    }

    // Get the start and end time of the month
    public function actionMonth()
    {<!-- -->
        $start = mktime(0, 0, 0, date('m'), 1, date('y'));
        $end = mktime(23, 59, 59, date('m'), date('t'), date('y'));
        return [$start, $end];
    }


    // Get the start and end time of the year
    public function actionYear()
    {<!-- -->
        $date = date('Y-m-d H:i:s');
        $start = strtotime(date(date("Y-01-01 00:00:00", strtotime("$date"))));
        $end = strtotime(date('Y-12-31 23:59:59', strtotime("$date")));
        return [$start, $end];
    }

This blog ends here, thinkphp, and your hardworking self!