Flutter请求限流插件shelf_throttle的使用
Flutter请求限流插件shelf_throttle的使用
shelf_throttle
是一个用于 Shelf
的中间件,它为所有传入的请求应用全局限流,以给定的时间窗口为准。
示例代码
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_throttle/shelf_throttle.dart';
void main() async {
const message = 'Responding at most once each 5 seconds';
// 限制每5秒内只能响应一次请求
final handler = throttle(Duration(seconds: 5)).addHandler((request) => Response.ok(message));
// 启动服务器并监听本地8080端口
await serve(handler, 'localhost', 8080);
}
安装
在你的 pubspec.yaml
文件中添加依赖:
dependencies:
shelf_throttle: ^0.5.0
然后运行以下命令获取包:
dart pub get
或者使用 Dart CLI 来添加和获取包:
dart pub add shelf_throttle
在你的处理管道中使用它:
import 'package:shelf_throttle/shelf_throttle.dart';
const window = Duration(seconds: 5);
Pipeline().addMiddleware(throttle(window)).addHandler(handleRequest);
详细说明
-
Server
import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart'; import 'package:shelf_throttle/shelf_throttle.dart'; void main() async { const message = 'Responding at most once each 5 seconds'; // 设置时间窗口为5秒 final handler = throttle(Duration(seconds: 5)).addHandler((request) => Response.ok(message)); // 在本地8080端口启动服务器 await serve(handler, 'localhost', 8080); }
在这个例子中,服务器会在每5秒内只响应一次请求。第一次请求会立即得到响应,之后的请求将会被延迟直到下一个5秒窗口开始。
-
Client
import 'package:http/http.dart' as http; void main() async { final baseUrl = 'http://localhost:8080'; // 第一次请求,立即响应 var response1 = await http.get(Uri.parse('$baseUrl/hello')); print('First response: ${response1.body}'); // 延迟3秒,第二次请求,仍在5秒窗口内,不会立即响应 await Future.delayed(Duration(seconds: 3)); var response2 = await http.get(Uri.parse('$baseUrl/world')); print('Second response: ${response2.body}'); // 再次延迟2秒,第三次请求,已经进入新的5秒窗口,可以立即响应 await Future.delayed(Duration(seconds: 2)); var response3 = await http.get(Uri.parse('$baseUrl/hello')); print('Third response: ${response3.body}'); }
更多关于Flutter请求限流插件shelf_throttle的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复