Пример #1
0
        private async Task RegisterService()
        {
            var _node_id = this.Client.getSessionId().ToString();

            var list = this._contracts.Invoke().Select(x => new AddressModel()
            {
                Url              = x.Url,
                ServiceNodeName  = ServiceManageHelper.ParseServiceName(x.Contract),
                EndpointNodeName = ServiceManageHelper.EndpointNodeName(_node_id),
            }).ToList();

            var now = DateTime.Now;

            foreach (var m in list)
            {
                m.UpdateTime = now;

                var service_path = this._base_path + "/" + m.ServiceNodeName;
                await this.Client.EnsurePersistentPath(service_path);

                var path = service_path + "/" + m.EndpointNodeName;
                var data = this._serializer.Serialize(m);
                if (await this.Client.ExistAsync_(path))
                {
                    //如果节点存在,就刷新节点数据
                    await this.Client.setDataAsync(path, data);
                }
                else
                {
                    //创建临时节点,服务端下线自动删除
                    await this.Client.CreateNode_(path, CreateMode.EPHEMERAL, data);
                }
            }
        }
Пример #2
0
        public AddressModel Resolve <T>(TimeSpan?timeout = null)
        {
            var name = ServiceManageHelper.ParseServiceName <T>();
            var list = this.AllService(timeout: timeout).Where(x => x.ServiceNodeName == name).ToArray();

            if (ValidateHelper.IsNotEmpty(list))
            {
                //这里用thread local比较好,一个线程共享一个随机对象
                lock (this._ran)
                {
                    var theone = this._ran.Choice(list) ?? throw new DataNotExistException("server information is empty");
                    //根据权重选择
                    //this._ran.ChoiceByWeight(list, x => x.Weight);
                    this.OnServerSelected?.Invoke(theone);
                    return(theone);
                }
            }
            return(null);
        }