Exemplo n.º 1
0
        /// <summary>
        /// 同步分布式缓存键值对
        /// </summary>
        /// <returns></returns>
        private int SyncKeyValues()
        {
            var kvs = new List <Tuple <string, string> >();

            //刷新键值
            try
            {
                foreach (var key in ConsulCache.Instance.GetKeys())
                {
                    var value = ConsulLoader.GetKeyValue(key)
                                .GetAwaiter().GetResult();
                    if (value != null)
                    {
                        kvs.Add(new Tuple <string, string>(key, value));
                    }
                }
            }
            catch { }

            int count = ConsulCache.Instance.SetKeyValue(kvs.ToArray());

            //刷新Tags
            foreach (var sName in ConsulCache.Instance.GetServiceNames())
            {
                //var serviceTagKey = string.Format(ServiceTagsKeyFormat, serviceName, sName, Dns.GetHostName());
                var serviceTagKey = GetServiceTagsKey(sName);
                ConsulCache.Instance.SetServiceTag(sName, ConsulCache.Instance.GetKeyValue(serviceTagKey));
            }

            return(count);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 替换服务注册标签,旧标签必须存在,新标签必须有效
        /// </summary>
        /// <param name="oldTag">旧标签,如main</param>
        /// <param name="newTag">新标签,如backup</param>
        /// <returns>是否替换成功</returns>
        public bool ReplaceServiceRegisteredTag(string oldTag, string newTag)
        {
            var tagStr = processor.GetServiceTags();

            if (string.IsNullOrEmpty(tagStr) ||
                string.IsNullOrEmpty(oldTag) ||
                string.IsNullOrEmpty(newTag))
            {
                return(false);
            }
            var tags = tagStr.Split(',').Select(tag => tag.Trim()).ToArray();
            var find = Array.FindIndex(tags, tag => tag == oldTag);

            if (find < 0)
            {
                return(false);
            }
            tags[find] = newTag;
            try
            {
                return(ConsulLoader.SetKeyValue(processor.GetRegisterTagKey(), string.Join(",", tags))
                       .GetAwaiter().GetResult());
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// 从Consul直接获取服务连接信息,不缓存,格式为{ip}:{port}
 /// </summary>
 /// <param name="serviceName">服务名称</param>
 /// <param name="serviceTags">服务内部标签,可用于服务分级</param>
 /// <returns>可用Host字符串数组</returns>
 public string[] GetServiceHostsNoCache(string serviceName, string serviceTags)
 {
     return(ConsulLoader.AvaliableServices(
                serviceName,
                serviceTags ?? ConsulCache.Instance.GetServiceTags(serviceName))
            .GetAwaiter()
            .GetResult()
            .Select(service => service.Node.Address + ":" + service.Service.Port)
            .ToArray());
 }
Exemplo n.º 4
0
        /// <summary>
        /// 保存分布式键值对
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>是否成功</returns>
        public bool SetKeyValue(string key, string value)
        {
            try
            {
                ConsulLoader.SetKeyValue(key, value).GetAwaiter().GetResult();
            }
            catch { }

            return(ConsulCache.Instance.SetKeyValue(new Tuple <string, string>(key, value)) > 0);
        }
Exemplo n.º 5
0
 /// <summary>
 /// 服务心跳发送
 /// </summary>
 /// <returns>是否发送成功</returns>
 private bool HeartBreakService()
 {
     try
     {
         return(ConsulLoader.HeartBreak("service:" + serviceName).GetAwaiter().GetResult());
     }
     catch
     {
         return(false);
     }
 }
Exemplo n.º 6
0
 /// <summary>
 /// 注册服务
 /// </summary>
 /// <returns>是否注册成功</returns>
 private bool RegsterService()
 {
     try
     {
         return(ConsulLoader.RegsterService(serviceName,
                                            serviceTags,
                                            servicePort,
                                            heartBreak,
                                            httpCheck,
                                            tcpCheck).GetAwaiter().GetResult());
     }
     catch { }
     return(false);
 }
Exemplo n.º 7
0
        /// <summary>
        /// 根据键获取值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public string GetKeyValue(string key)
        {
            var value = ConsulCache.Instance.GetKeyValue(key);

            try
            {
                if (value == null && !ConsulCache.Instance.GetKeys().Contains(key))
                {
                    value = ConsulLoader.GetKeyValue(key).GetAwaiter().GetResult();
                    ConsulCache.Instance.SetKeyValue(new Tuple <string, string>(key, value));
                }
            }
            catch { }

            return(value);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 同步可用服务信息
        /// </summary>
        /// <param name="serviceNames">服务名集合</param>
        /// <returns>同步更新可用服务负载点数量</returns>
        private int SyncServices()
        {
            var count = 0;

            try
            {
                foreach (var serviceName in ConsulCache.Instance.GetServiceNames())
                {
                    var services = ConsulLoader.AvaliableServices(serviceName,
                                                                  ConsulCache.Instance.GetServiceTags(serviceName))
                                   .GetAwaiter().GetResult();
                    count += ConsulCache.Instance.SetServiceInfo(serviceName, services);
                }
            }
            catch { }
            return(count);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 获取服务连接信息,格式为{ip}:{port}
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <param name="serviceTags">服务内部标签,可用于服务分级</param>
        /// <returns>可用Host字符串数组</returns>
        public string[] GetServiceHosts(string serviceName, string serviceTags)
        {
            var hosts = ConsulCache.Instance.GetServiceHosts(serviceName, serviceTags ?? string.Empty);

            try
            {
                if (hosts.Length == 0 && !ConsulCache.Instance.GetServiceNames().Contains(serviceName))
                {
                    ConsulCache.Instance.SetServiceInfo(serviceName,
                                                        ConsulLoader.AvaliableServices(
                                                            serviceName,
                                                            serviceTags ?? string.Empty)
                                                        .GetAwaiter()
                                                        .GetResult());
                    hosts = ConsulCache.Instance.GetServiceHosts(serviceName, serviceTags ?? string.Empty);
                }
            }
            catch { }
            return(hosts);
        }
Exemplo n.º 10
0
 /// <summary>
 /// 向Consul直接保存分布式键值对,不缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <returns>是否成功</returns>
 public bool SetKeyValueNoCache(string key, string value)
 {
     return(ConsulLoader.SetKeyValue(key, value).GetAwaiter().GetResult());
 }
Exemplo n.º 11
0
        /// <summary>
        /// 根据键从Consul直接获取获取值,不缓存
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public string GetKeyValueNoCache(string key)
        {
            var value = ConsulLoader.GetKeyValue(key).GetAwaiter().GetResult();

            return(value);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 初始化
        /// </summary>
        public void Initialize()
        {
            string basePath = null;

#if !CORECLR
            basePath = System.Web.HttpRuntime.AppDomainAppPath;
#else
            basePath = Directory.GetCurrentDirectory();
#endif

            //读取配置
            var consulConfig = new ConfigurationBuilder()
                               .SetBasePath(basePath)
                               .AddJsonFile("Config/consulplugin.json", true, false)
                               .Build().Get <ConsulConfigSection>();
            serviceName  = consulConfig.ServiceName;
            refreshBreak = consulConfig.RefreshBreak;
            heartBreak   = consulConfig.HeartBreak;

            //注册服务
            try
            {
                ConsulLoader.RegsterService(serviceName,
                                            consulConfig.ServiceTags,
                                            consulConfig.ServicePort,
                                            consulConfig.HeartBreak,
                                            consulConfig.HttpCheck,
                                            consulConfig.TcpCheck).GetAwaiter().GetResult();
            }
            catch { throw; }

            //若不存在HttpCheck且Interval存在时发送初始心跳
            if (string.IsNullOrEmpty(consulConfig.HttpCheck) &&
                string.IsNullOrEmpty(consulConfig.TcpCheck) &&
                heartBreak > 0)
            {
                HeartBreakService();
            }

            //读取缓存键值对配置信息
            if (consulConfig.KeyValues != null)
            {
                foreach (KeyValueElement kvConfig in consulConfig.KeyValues)
                {
                    ConsulCache.Instance.SetKeyValue(new Tuple <string, string>(kvConfig.Name, kvConfig.Value));
                }
            }


            //读取依赖服务配置信息
            if (consulConfig.Services != null)
            {
                foreach (ServiceElement serviceConfig in consulConfig.Services)
                {
                    ConsulCache.Instance.SetServiceTag(serviceConfig.Name, serviceConfig.ServiceTags);
                    var serviceTagKey = GetServiceTagsKey(serviceConfig.Name);
                    try
                    {
                        if (string.IsNullOrEmpty(ConsulLoader.GetKeyValue(serviceTagKey).GetAwaiter().GetResult()))
                        {
                            ConsulLoader.SetKeyValue(serviceTagKey, serviceConfig.ServiceTags).GetAwaiter().GetResult();
                        }
                    }
                    catch { }
                    ConsulCache.Instance.SetKeyValue(new Tuple <string, string>(serviceTagKey, serviceConfig.ServiceTags));
                }
            }

            //初次同步依赖服务信息及缓存信息
            SyncKeyValues();
            SyncServices();

            //若不存在HttpCheck且Interval存在时开启心跳线程
            if (string.IsNullOrEmpty(consulConfig.HttpCheck) &&
                string.IsNullOrEmpty(consulConfig.TcpCheck) &&
                heartBreak > 0)
            {
                new Thread(HeartProcess)
                {
                    IsBackground = true
                }.Start();
            }

            //同步线程开启
            new Thread(SyncProcess)
            {
                IsBackground = true
            }.Start();
        }
Exemplo n.º 13
0
        /// <summary>
        /// 初始化
        /// </summary>
        public void Initialize()
        {
            //读取配置
            var consulConfig = (ConsulConfigSection)ConfigurationManager.GetSection("consulplugin");

            serviceName  = consulConfig.ServiceName;
            refreshBreak = consulConfig.RefreshBreak;
            heartBreak   = consulConfig.HeartBreak;

            //注册服务
            try
            {
                ConsulLoader.RegsterService(serviceName,
                                            consulConfig.ServiceTags,
                                            consulConfig.ServicePort,
                                            consulConfig.HeartBreak,
                                            consulConfig.HttpCheck,
                                            consulConfig.TcpCheck).GetAwaiter().GetResult();
            }
            catch { }

            //若不存在HttpCheck且Interval存在时发送初始心跳
            if (string.IsNullOrEmpty(consulConfig.HttpCheck) &&
                string.IsNullOrEmpty(consulConfig.TcpCheck) &&
                heartBreak > 0)
            {
                HeartBreakService();
            }

            //读取缓存键值对配置信息
            foreach (KeyValueElement kvConfig in consulConfig.KeyValues)
            {
                ConsulCache.Instance.SetKeyValue(new Tuple <string, string>(kvConfig.Name, kvConfig.Value));
            }


            //读取依赖服务配置信息
            foreach (ServiceElement serviceConfig in consulConfig.Services)
            {
                ConsulCache.Instance.SetServiceTag(serviceConfig.Name, serviceConfig.ServiceTags);
                //var serviceTagKey = string.Format(ServiceTagsKeyFormat, serviceName, serviceConfig.Name, Dns.GetHostName());
                var serviceTagKey = GetServiceTagsKey(serviceConfig.Name);
                try
                {
                    if (string.IsNullOrEmpty(ConsulLoader.GetKeyValue(serviceTagKey).GetAwaiter().GetResult()))
                    {
                        ConsulLoader.SetKeyValue(serviceTagKey, serviceConfig.ServiceTags).GetAwaiter().GetResult();
                    }
                }
                catch { }
                ConsulCache.Instance.SetKeyValue(new Tuple <string, string>(serviceTagKey, serviceConfig.ServiceTags));
            }

            //初次同步依赖服务信息及缓存信息
            SyncServices();
            SyncKeyValues();

            //若不存在HttpCheck且Interval存在时开启心跳线程
            if (string.IsNullOrEmpty(consulConfig.HttpCheck) &&
                string.IsNullOrEmpty(consulConfig.TcpCheck) &&
                heartBreak > 0)
            {
                new Thread(HeartProcess)
                {
                    IsBackground = true
                }.Start();
            }

            //同步线程开启
            new Thread(SyncProcess)
            {
                IsBackground = true
            }.Start();
        }