IP 查询展示最近的 50 次查询, Laravel + Redis

更新日期: 2018-07-20 阅读次数: 5361 分类: Redis

目标是实现后台缓存最近的 50 次 IP 查询,展示到 IP 查询页面 中。

同时对最近的 IP 查询结果做缓存。

redis 定长 list 的使用,保存最近50次查询结果

参考 redis 官方文档

https://redis.io/commands/ltrim

逻辑是,每次 push 之后,执行 trim 操作,将多余的数据清理掉,保持定长。

127.0.0.1:6379> lpush recent_result 1
(integer) 1
127.0.0.1:6379> lpush recent_result 2
(integer) 2
127.0.0.1:6379> lpush recent_result 3
(integer) 3
127.0.0.1:6379> LTRIM recent_result 0 1
OK
127.0.0.1:6379> lrange recent_result 0 -1
1) "3"
2) "2"

laravel 中 redis 的操作方法

参考 Laravel 官方文档

https://laravel.com/docs/5.6/redis

composer require predis/predis

config/database.php 中设置读写超时时间非常重要

'read_write_timeout' => 5,

常见的基本操作

$user = Redis::get('user:profile:'.$id);
Redis::set('name', 'sunzhongwei');
$values = Redis::lrange('names', 5, 10);

设置过期时间

127.0.0.1:6379> ttl recent_result
(integer) -1
127.0.0.1:6379> EXPIRE recent_result 100
(integer) 1
127.0.0.1:6379> ttl recent_result
(integer) 98
127.0.0.1:6379> ttl recent_result
(integer) -2

laravel 向 redis 存取数据时,是否必须使用 json_decode json_encode

目前看是这样的.

pipeline

一次性向 redis 发送多个指令,类似 mysql 的事务。

Redis::pipeline(function ($pipe) {
    for ($i = 0; $i < 1000; $i++) {
        $pipe->set("key:$i", $i);
    }
});

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式