[练手] 使用 Redis 模拟登陆用户浏览商品页面的 token 维护,足迹记录,清理多余记录的实现

将以下代码保存到对应文件,执行start.sh 即可查看redis中的数据变化

其中的数量级和每次执行清除脚本的step值根据自身情况设置
需要phpredis拓展
start.sh需要执行权限
我是在linux上试的

  • updatetoken.php
  <?php
  $ip = '127.0.0.1';
  $port = 6379;
  $redis = new Redis();

  $redis->pconnect($ip,$port,1);

  //得到毫秒
  function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
  }

  //数量级
  $record_num = pow(10,5)*3;
  $start = time();

  //统计已经执行的数量
  $redis->set('num',1);
  //开启清除脚本
  $redis->set('clean_token_record_open',1);
  //模拟浏览
  for($i=1;$i<=$record_num;$i++){
    $record = ['user_id'=>mt_rand(1,1500),'product_id'=>mt_rand(1,40)];

    $token = date('YmdH').$record['user_id'];
    $redis->hset('login_token',$token,$record['user_id']);

    $redis->zadd('token_time',getMillisecond(),$token);

    $redis->zadd('record:'.$record['user_id'],getMillisecond(),$record['product_id']);

    $redis->zremrangebyrank('record:'.$record['user_id'],0,-31); 

    $redis->incr('num');
  }

  echo '访问结束,共耗时:'.(time() - $start) . '秒!'.PHP_EOL;
  //关闭清除脚本
  $redis->set('clean_token_record_open',2);
?>
  • clean_token_record.php
<?php
  $ip = '127.0.0.1';
  $port = 6379;
  $redis = new Redis();

  $redis->pconnect($ip,$port,1);

  $threshold = 600;
  $step = 0.1;
  $del_token_num = 10;

  do{
    $token_time_num = $redis->zcard('token_time');

    $is_out = $token_time_num - $threshold;
    if($is_out > 0){
      //得到要删除的token
      $tokens = $redis->zrange('token_time',0,min($is_out,$del_token_num)-1);

      //记录每次被删除的token的值
      $redis->zadd('del_token',time(),implode(',',$tokens));

      //删除记录
      foreach($tokens as $value){
        $redis->hdel('login_token',$value);
      }
      $redis->zremrangebyrank('token_time',0,min($is_out,$del_token_num)-1);
    }else{
      sleep($step);
    }
  }while($redis->get('clean_token_record_open')==1);

  echo '清理结束!'.PHP_EOL;
?>
  • start.sh
#/bin/bash
/usr/bin/php updatetoken.php &
/usr/bin/php clean_token_record.php

主要是观察redis中的数据变化

本作品采用《CC 协议》,转载必须注明作者和本文链接
Luerdog
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!