private HttpPool GetPool(string server) { lock (_pools) { foreach (var pool in _pools) { if (pool.Server == server) { return(pool); } } var p = new HttpPool { Server = server, ConnectionsLimit = ConnectionsPerServer, QueueLimit = QueueLimit, ReceiveTimeout = ReceiveTimeout }; _pools.Add(p); return(p); } }
/// <summary> /// 获取服务连接 /// </summary> /// <param name="serviceName">服务名</param> /// <param name="protocolTags">协议标签,决定连接池类型,默认使用配置内指定标签</param> /// <returns>服务连接</returns> public ISerClient GetServiceClient(string serviceName, string protocolTags = null) { //参数检查 ISerClient client = null; protocolTags = protocolTags ?? ConsulCache.Instance.GetServiceTags(serviceName); if (string.IsNullOrEmpty(serviceName) || string.IsNullOrEmpty(protocolTags)) { return(client); } //筛选有效协议标签 string protocolTag = null; foreach (var tag in protocolTags.Split(',')) { switch (tag) { case "http": case "thrift": case "wcf": case "grpc": protocolTag = tag; break; default: continue; } } if (protocolTag == null) { return(client); } //获取或创建连接池 var poolKey = string.Join(":", serviceName, protocolTag); SerPool pool = null; if (serverPools.ContainsKey(poolKey)) { pool = serverPools[poolKey]; } else { lock (serviceLock) { if (serverPools.ContainsKey(poolKey)) { pool = serverPools[poolKey]; } else { //读取连接池配置值 var config = new SerConfig(); foreach (var key in ConsulCache.Instance.GetKeys()) { if (key.Contains(poolKey)) { var configKey = key.Split(':').Last(); config.Add(configKey, GetKeyValue(key)); //设置键值回调 AddKvHook(key, (k, v) => { config[k.Split(':').Last()] = v; }); } } //配置加入服务名 config.Add("ServiceName", serviceName); //创建连接池 switch (protocolTag) { case "http": pool = new HttpPool(GetServiceHosts(serviceName, protocolTags), config); break; case "thrift": pool = new ThriftPool(GetServiceHosts(serviceName, protocolTags), config); break; case "wcf": pool = new WcfPool(GetServiceHosts(serviceName, protocolTags), config); break; case "grpc": pool = new GrpcPool(GetServiceHosts(serviceName, protocolTags), config); break; default: return(client); } //设置连接池重置回调,负载信息变更 AddServiceHook(serviceName, (s) => { pool.ResetPool(GetServiceHosts(s, ConsulCache.Instance.GetServiceTags(s))); }); //添加连接池 serverPools.Add(poolKey, pool); } } } //返回连接 return(pool.BorrowClient()); }