#regionCall -- load balancing
{
    //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:// {domain} / API/users/get";
    Consul resolves using service name translation 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));Obtain all corresponding service instances on Consul
        KeyValuePair<string, AgentService> keyValuePair = new KeyValuePair<string, AgentService>();
        // Get 3 addresses, just choose from them - load balancing can be done here
        / / {
        // keyValuePair = list.First(); // Take the first one directly
        / /}
        / / {
        // var array = list.ToArray();
        // // Random strategy -- average strategy
        // keyValuePair = array[new Random(iSeed++).Next(0, array.Length)];
        / /}
        / / {
        // var array = list.ToArray();
        // // Polling policy: average policy
        // keyValuePair = array[iSeed++ % array.Length];
        / /}
        {
            // Weights -- Specify weights when registering services, get weights when assigning services, and use this as a basis
            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}";
        stringresult = WebApiHelperExtend.InvokeApi(resultUrl); userList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Users>>(result); }}#endregion
Copy the code