import 'package:redis/redis.dart'; class Redis { final RedisConfig _config; Command? _command; Redis(this._config); static late Redis _redis; static Redis getInstance() { return _redis; } static void setInstance(Redis redis) { _redis = redis; } Future connect({reconnect = false}) async { if (reconnect) { print("尝试重连Redis"); } Future.delayed(Duration(seconds: 1), () async { try { _command = await RedisConnection().connect(_config.host, _config.port); print('Redis Connected successfully!'); //定时检测是否断开连接 Future.delayed(Duration(seconds: 1), () async { do { await Future.delayed(Duration(seconds: 5)); try { var r = await _command!.send_object(["PING"]); if (r != "PONG") { break; } } catch (e) { //发送数据失败 try { print('Redis Connection check failed: $e'); _command!.get_connection().close(); } catch (o) { // } break; } } while (true); connect(reconnect: true); }); } catch (e) { print('Redis Connection error: $e'); connect(reconnect: reconnect); } }); } Future set(String key, String value) async { var response = await _command?.send_object(["SET", key, value]); return response == "OK"; } Future get(String key) async { return await _command?.send_object(["GET", key]); } Future delete(String key) async { return await _command?.send_object(["DEL", key]) == "OK"; } Future setWithExpiry(String key, String value, int ttlInSeconds) async { var response = await _command ?.send_object(["SETEX", key, ttlInSeconds.toString(), value]); return response == "OK"; } } class RedisConfig { String host; int port; RedisConfig({ required this.host, this.port = 6379, }); }