http_pool.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import 'dart:async';
  2. import 'package:fis_common/http/http.dart';
  3. import 'package:fis_common/http/options.dart';
  4. import 'package:dio/dio.dart' as dio;
  5. class _JsonRpcHttpPool {
  6. _JsonRpcHttpPool({int limitCount = 2}) {
  7. _limitCount = limitCount;
  8. }
  9. static const _TimerInterval = 60 * 1000;
  10. static const _LifecycleTime = 60 * 1000;
  11. Timer? _timer;
  12. final Map<int, _ClientState> _pool = {};
  13. late int _limitCount;
  14. int get limitCount => _limitCount;
  15. bool _closed = false;
  16. bool _firstCall = true;
  17. void _handleFirstLoad() {
  18. if (!_firstCall) return;
  19. _timer =
  20. Timer.periodic(const Duration(milliseconds: _TimerInterval), (timer) {
  21. final now = DateTime.now();
  22. _pool.forEach((key, value) {
  23. var secDiff = now.difference(value.lastVisitTime).inSeconds;
  24. if (_LifecycleTime < secDiff) {
  25. _pool.remove(key);
  26. }
  27. });
  28. });
  29. _firstCall = false;
  30. }
  31. void close() {
  32. if (!_closed) {
  33. _closed = true;
  34. _timer?.cancel();
  35. }
  36. }
  37. /// 设置连接池缓存数
  38. void setLimitCount(int count) => _limitCount = count;
  39. /// 获取客户端实例
  40. FHttp getClient(
  41. String baseUrl, {
  42. int? timeout,
  43. Map<String, dynamic>? headers,
  44. }) {
  45. if (!_pool.containsKey(baseUrl.hashCode)) {
  46. // 浏览器跨域限制: Content-Type非简单类型 Fetch前会先发一个Options,Server不支持Options导致Cors
  47. // 简单类型:
  48. // - application/x-www-form-urlencoded
  49. // - multipart/form-data
  50. // - text/plain
  51. final _client = FHttp(FHttpBaseOptions(
  52. baseUrl: baseUrl,
  53. timeout: timeout ?? 15 * 1000,
  54. headers: headers,
  55. contentType: dio.Headers.textPlainContentType,
  56. responseType: FHttpResponseType.json,
  57. ));
  58. final _state = _ClientState(_client);
  59. _pool[baseUrl.hashCode] = _state;
  60. if (_pool.length > limitCount) {
  61. _pool.remove(_pool.keys.first); // 删除第一个
  62. }
  63. }
  64. final state = _pool[baseUrl.hashCode]!;
  65. state.lastVisitTime = DateTime.now();
  66. _handleFirstLoad();
  67. return state.client;
  68. }
  69. }
  70. class _ClientState {
  71. _ClientState(this.client);
  72. final FHttp client;
  73. DateTime lastVisitTime = DateTime.now();
  74. }
  75. final _JsonRpcHttpPool jrpcHttpPool = _JsonRpcHttpPool();