bandwidth_limiter.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. -- lua/bandwidth_limiter.lua
  2. local _M = {}
  3. local redis = require "resty.redis"
  4. local redis_host = "127.0.0.1"
  5. local redis_port = 6379
  6. local redis_password = "Hycpb@123"
  7. local redis_db = 6
  8. local redis_prefix = "tenant:device_count:"
  9. local max_bandwidth = 1024 * 1024 -- 1MB
  10. local min_bandwidth = 64 * 1024 -- 最小限速 64KB
  11. local function get_redis()
  12. local red = redis:new()
  13. red:set_timeout(1000)
  14. local ok, err = red:connect(redis_host, redis_port)
  15. if not ok then
  16. ngx.log(ngx.ERR, "Redis connection error: ", err)
  17. return nil, err
  18. end
  19. -- 认证密码
  20. if redis_password and redis_password ~= "" then
  21. local ok, err = red:auth(redis_password)
  22. if not ok then
  23. ngx.log(ngx.ERR, "Redis auth failed: ", err)
  24. return nil, err
  25. end
  26. end
  27. -- 选择数据库
  28. if redis_db then
  29. local ok, err = red:select(redis_db)
  30. if not ok then
  31. ngx.log(ngx.ERR, "Redis select db failed: ", err)
  32. return nil, err
  33. end
  34. end
  35. return red
  36. end
  37. function _M.register_device(tenant_id)
  38. local red, err = get_redis()
  39. if not red then return min_bandwidth end
  40. local key = redis_prefix .. tenant_id
  41. local count, err = red:incr(key)
  42. if not count then
  43. ngx.log(ngx.ERR, "Redis INCR failed: ", err)
  44. return min_bandwidth
  45. end
  46. red:expire(key, 60) -- 设置 60 秒自动过期
  47. return math.max(math.floor(max_bandwidth / count), min_bandwidth)
  48. end
  49. function _M.unregister_device(tenant_id)
  50. local red, err = get_redis()
  51. if not red then return end
  52. local key = redis_prefix .. tenant_id
  53. red:decr(key)
  54. end
  55. return _M