internal void AddBeatInfo(string serviceName, BeatInfo beatInfo) { _logger?.LogInformation("[BEAT] adding beat: {0} to beat map.", beatInfo); string key = BuildKey(serviceName, beatInfo.Ip, beatInfo.Port); if (Dom2Beat.TryRemove(key, out var exitBeat)) { exitBeat.Stopped = true; } Dom2Beat.AddOrUpdate(key, beatInfo, (x, y) => beatInfo); var timer = new Timer( async x => { var info = x as BeatInfo; await BeatTask(info); }, beatInfo, beatInfo.Period, beatInfo.Period); _beatTimer.AddOrUpdate(key, timer, (x, y) => timer); }
private async Task BeatTask(BeatInfo beatInfo) { if (beatInfo.Stopped) { return; } long nextTime = beatInfo.Period; try { Newtonsoft.Json.Linq.JObject result = await _serverProxy.SendBeat(beatInfo, false); long interval = result.GetValue("clientBeatInterval").ToObject <long>(); bool lightBeatEnabled = false; if (result.ContainsKey(CommonParams.LIGHT_BEAT_ENABLED)) { lightBeatEnabled = result.GetValue(CommonParams.LIGHT_BEAT_ENABLED).ToObject <bool>(); } if (interval > 0) { nextTime = interval; } int code = 10200; if (result.ContainsKey(CommonParams.CODE)) { code = result.GetValue(CommonParams.CODE).ToObject <int>(); } if (code == 20404) { Instance instance = new Instance { Port = beatInfo.Port, Ip = beatInfo.Ip, Weight = beatInfo.Weight ?? 1, Metadata = beatInfo.Metadata, ClusterName = beatInfo.Cluster, ServiceName = beatInfo.ServiceName, Ephemeral = true, // InstanceId = "" }; try { await _serverProxy.RegisterServiceAsync(beatInfo.ServiceName, NamingUtils.GetGroupName(beatInfo.ServiceName), instance); } catch { } } } catch (NacosException ex) { _logger?.LogError(ex, "[CLIENT-BEAT] failed to send beat: {0}, code: {1}, msg: {2}", beatInfo, ex.ErrorCode, ex.ErrorMsg); } string key = BuildKey(beatInfo.ServiceName, beatInfo.Ip, beatInfo.Port); if (_beatTimer.TryGetValue(key, out var timer)) { timer.Change(nextTime, Timeout.Infinite); } }