using dotnet_etcd; using Etcdserverpb; using Google.Protobuf; using HealthMonitor.Model.Config; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace HealthMonitor.Service.Etcd { public class EtcdService { private readonly ServiceConfig _configService; private readonly ILogger _logger; private readonly EtcdClient _etcdClient; public EtcdService(IOptions _optConfigService, ILogger logger) { _configService = _optConfigService.Value; _logger = logger; _etcdClient = new EtcdClient(_configService.EtcdServerAddress); } public async Task GetValAsync(string key) { return await _etcdClient.GetValAsync(key); } public async Task GetResponseAsync(string key) { return await _etcdClient.GetAsync(key); } public async Task GetValWithPrefixAsync(string keyWithPREFIX) { return await _etcdClient.GetRangeAsync(keyWithPREFIX); } // public async Task PutValAsync(string key, string value, long? ttl = null, bool? keepalived = false) { try { PutRequest request = new() { Key = ByteString.CopyFromUtf8(key), Value = ByteString.CopyFromUtf8(value), }; if (ttl != null) { long leaseId = _etcdClient.LeaseGrant(new LeaseGrantRequest { TTL = (long)ttl }).ID; request = new PutRequest { Key = ByteString.CopyFromUtf8(key), Value = ByteString.CopyFromUtf8(value), Lease = leaseId }; if ((bool)keepalived!) { //await _etcdClient.PutAsync(request); _ = _etcdClient.LeaseKeepAlive(leaseId, CancellationToken.None); //await _etcdClient.LeaseKeepAlive(leaseId, CancellationToken.None); request = new PutRequest { Key = ByteString.CopyFromUtf8(key), Value = ByteString.CopyFromUtf8(value), Lease = leaseId }; //await _etcdClient.PutAsync(request); //return; } } await _etcdClient.PutAsync(request); } catch (Exception ex) { _logger.LogInformation($"{nameof(EtcdService)} --- {nameof(PutValAsync)} 出错\n{ex.Message}\n{ex.StackTrace}"); } // await _etcdClient.PutAsync(key, value,null); } public async Task PutValAsync(string key, string value, DateTime deadline) { PutRequest request = new() { Key = ByteString.CopyFromUtf8(key), Value = ByteString.CopyFromUtf8(value), }; await _etcdClient.PutAsync(request, null, deadline); // await _etcdClient.PutAsync(key, value,null); } public async Task DeleteKeyValAsync(string key) { await _etcdClient.DeleteAsync(key); } public async Task DeleteKeyValWithPrefixAsync(string keyWithPREFIX) { await _etcdClient.DeleteRangeAsync(keyWithPREFIX); } public async Task WacthKeysWithPrefixAsync(string keyWithPREFIX, Action action) { await _etcdClient.WatchRangeAsync(keyWithPREFIX, action); } public async Task WacthKeysWithPrefixResponseAsync(string keyWithPREFIX, Action action) { await _etcdClient.WatchRangeAsync(keyWithPREFIX, action); } } }