swoole如何对ip限制访问频率

在我们开发api的过程中,有的时候我们还需要考虑单个用户(ip)访问频率控制,避免被恶意调用。

归根到底也就只有两个步骤:

  • 用户访问要统计次数
  • 执行操作逻辑之前要判断次数频率是否过高,过高则不执行

easyswoole中实现Ip访问频率限制

本文章举例的是在easyswoole框架中实现的代码,在swoole原生中实现方式是一样的。

只要在对应的回调事件做判断拦截处理即可。

  • 使用swoole\Table,储存用户访问情况(也可以使用其他组件、方式储存)
  • 使用定时器,将前一周期的访问情况清空,统计下一周期

如以下IpList类,实现了初始化Table、统计IP访问次数、获取一个周期内次数超过一定值的记录

  1. <?php
  2. /**
  3. * Ip访问次数统计
  4. * User: Siam
  5. * Date: 2019/7/8 0008
  6. * Time: 下午 9:53
  7. */
  8. namespace App;
  9. use EasySwoole\Component\Singleton;
  10. use EasySwoole\Component\TableManager;
  11. use Swoole\Table;
  12. class IpList
  13. {
  14. use Singleton;
  15. /** @var Table */
  16. protected $table;
  17. public function __construct()
  18. {
  19. TableManager::getInstance()->add('ipList', [
  20. 'ip' => [
  21. 'type' => Table::TYPE_STRING,
  22. 'size' => 16
  23. ],
  24. 'count' => [
  25. 'type' => Table::TYPE_INT,
  26. 'size' => 8
  27. ],
  28. 'lastAccessTime' => [
  29. 'type' => Table::TYPE_INT,
  30. 'size' => 8
  31. ]
  32. ], 1024*128);
  33. $this->table = TableManager::getInstance()->get('ipList');
  34. }
  35. function access(string $ip):int
  36. {
  37. $key = substr(md5($ip), 8,16);
  38. $info = $this->table->get($key);
  39. if ($info) {
  40. $this->table->set($key, [
  41. 'lastAccessTime' => time(),
  42. 'count' => $info['count'] + 1,
  43. ]);
  44. return $info['count'] + 1;
  45. }else{
  46. $this->table->set($key, [
  47. 'ip' => $ip,
  48. 'lastAccessTime' => time(),
  49. 'count' => $info['count'] + 1,
  50. ]);
  51. return 1;
  52. }
  53. }
  54. function clear()
  55. {
  56. foreach ($this->table as $key => $item){
  57. $this->table->del($key);
  58. }
  59. }
  60. function accessList($count = 10):array
  61. {
  62. $ret = [];
  63. foreach ($this->table as $key => $item){
  64. if ($item['count'] >= $count){
  65. $ret[] = $item;
  66. }
  67. }
  68. return $ret;
  69. }
  70. }

封装完IP统计的操作之后

我们可以在EasySwooleEvent.php的mainServerCreate回调事件中初始化IpList和定时器

  1. <?php
  2. public static function mainServerCreate(EventRegister $register)
  3. {
  4. // 开启IP限流
  5. IpList::getInstance();
  6. $class = new class('IpAccessCount') extends AbstractProcess{
  7. protected function run($arg)
  8. {
  9. $this->addTick(5*1000, function (){
  10. /**
  11. * 正常用户不会有一秒超过6次的api请求
  12. * 做列表记录并清空
  13. */
  14. $list = IpList::getInstance()->accessList(30);
  15. // var_dump($list);
  16. IpList::getInstance()->clear();
  17. });
  18. }
  19. };
  20. }

接着我们在OnRequest回调中,判断和统计Ip的访问

  1. <?php
  2. public static function onRequest(Request $request, Response $response): bool
  3. {
  4. $fd = $request->getSwooleRequest()->fd;
  5. $ip = ServerManager::getInstance()->getSwooleServer()->getClientInfo($fd)['remote_ip'];
  6. // 如果当前周期的访问频率已经超过设置的值,则拦截
  7. // 测试的时候可以将30改小,比如3
  8. if (IpList::getInstance()->access($ip) > 30) {
  9. /**
  10. * 直接强制关闭连接
  11. */
  12. ServerManager::getInstance()->getSwooleServer()->close($fd);
  13. // 调试输出 可以做逻辑处理
  14. echo '被拦截'.PHP_EOL;
  15. return false;
  16. }
  17. // 调试输出 可以做逻辑处理
  18. echo '正常访问'.PHP_EOL;
  19. }

以上就实现了对同一IP访问频率的限制操作。

具体还可以根据自身需求进行扩展,如对具体的某个接口再进行限流。

::: warning Easyswoole提供了一个基于Atomic计数器的限流器组件。可以直接使用,使用教程请移步查看限流器文档。 :::