#region 调用---负载均衡
{
//string url = "http://localhost:5726/api/users/get";
//string url = "http://localhost:5727/api/users/get";
//string url = "http://localhost:5728/api/users/get";
string url = "http://{域名}/api/users/get";
//consul解决使用服务名字 转换IP:Port----DNS
Uri uri = new Uri(url);
string groupName = uri.Host;
using (ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri("http://localhost:8500/");
c.Datacenter = "dc1";
}))
{
var dictionary = client.Agent.Services().Result.Response;
var list = dictionary.Where(k => k.Value.Service.Equals(groupName, StringComparison.OrdinalIgnoreCase));//获取consul上全部对应服务实例
KeyValuePair<string, AgentService> keyValuePair = new KeyValuePair<string, AgentService>();
//拿到3个地址,只需要从中选择---可以在这里做负载均衡--
//{
// keyValuePair = list.First();//直接拿的第一个
//}
//{
// var array = list.ToArray();
// //随机策略---平均策略
// keyValuePair = array[new Random(iSeed++).Next(0, array.Length)];
//}
//{
// var array = list.ToArray();
// //轮询策略---平均策略
// keyValuePair = array[iSeed++ % array.Length];
//}
{
//权重---注册服务时指定权重,分配时获取权重并以此为依据
List<KeyValuePair<string, AgentService>> pairsList = new List<KeyValuePair<string, AgentService>>();
foreach (var pair in list)
{
int count = int.Parse(pair.Value.Tags?[0]);
for (int i = 0; i < count; i++)
{
pairsList.Add(pair);
}
}
keyValuePair = pairsList.ToArray()[new Random(iSeed++).Next(0, pairsList.Count())];
}
resultUrl = $"{uri.Scheme}://{keyValuePair.Value.Address}:{keyValuePair.Value.Port}{uri.PathAndQuery}";
string result = WebApiHelperExtend.InvokeApi(resultUrl);
userList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Users>>(result);
}
}
#endregion
C#/.NET 微服务专题(consul实现负载均衡)
猜你喜欢
转载自blog.csdn.net/weixin_41181778/article/details/104012566
今日推荐
周排行