Install Consul

1. Download the corresponding version from the official website and decompress it

The official website: www.consul.io/

2. Open CMD, CD, and run one of the following commands

This demonstration is all on the same computer, so this paper chooses command 1; Use these two commands in the development environment but not in the production environment.

Command 1: “consul.exe agent-dev” specifies the IP address of the service center. 127.0.0.1 will be used

Exe agent-dev-client X.X.X.X specifies the IP address of the service center

3. After the command is successfully executed, open thehttp://127.0.0.1:8500/, the following screen is displayed

2. Create a service

1. General structure of server project:

2. Create a.net Core ClassLibrary project, name it “ClassLibrary”, then NuGet search and install

“Consul,” “Microsoft. Extensions. The Configuration”, “Microsoft. Extensions. Configuration. Json”

Common. Cs code:

using Consul;
using Microsoft.Extensions.Configuration;
using System;

namespace ClassLibrary
{
    public class Common
    {
        public static IConfiguration Configuration { get; }
        static Common()
        {
            Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json".false.true).Build();
        }

        /// <summary>
        ///Address of the service to be registered
        /// </summary>
        public static string ConsulServiceIP
        {
            get
            {
                return Configuration["Consul:ServiceIP"]; }}/// <summary>
        ///Service port to be registered
        /// </summary>
        public static int ConsulServicePort
        {
            get
            {
                string str = Configuration["Consul:ServicePort"];
                return int.Parse(str); }}/// <summary>
        ///The service registry
        /// </summary>
        public static void ConsulRegister()
        {
            ConsulClient client = new ConsulClient(
                (ConsulClientConfiguration c) =>
                {
                    c.Address = new Uri(Configuration["Consul:Address"]); //Consul service centre address
                    c.Datacenter = Configuration["Consul:DataCenter"]; // Specify the data center. If not, default to the broker's data center.});string checkUrl = Configuration["Consul:CheckUrl"];
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = Guid.NewGuid().ToString(), // The service number cannot be repeated
                Name = Configuration["Consul:ServiceName"].// Service name
                Port = ConsulServicePort, // The port number of this program
                Address = ConsulServiceIP, // The IP address of this program
                Check = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromMilliseconds(1), // How long to log out after the service stops
                    Interval = TimeSpan.FromSeconds(5), // Service health check interval
                    Timeout = TimeSpan.FromSeconds(5), // Check the timeout
                    HTTP = $"http://{ConsulServiceIP}:{ConsulServicePort}{checkUrl}" // Check the address}}); }}}Copy the code

3. Create a WebAPI project for.net Core, name it ServiceStudent, and deselect Configure for HTTPS

The Controller code:

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace ServiceStudent.Controllers{[Route("api/[controller]/[action]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        static List<Student> list = new List<Student>() {
            new Student(){ ID = "001", StudentName = "Student 1", StudentAge = 16 },
            new Student(){ ID = "002", StudentName = Student 2 "", StudentAge = 18 },
            new Student(){ ID = "003", StudentName = "Students 3", StudentAge = 17}};/// <summary>
        ///Health Check Interface
        /// </summary>
        [HttpGet]
        public string Check()
        {
            return "1";
        }

        [HttpGet]
        public List<Student> GetList()
        {
            Console.WriteLine(DateTime.Now.ToString());
            return list;
        }

        [HttpGet]
        public Student GetModel(string id)
        {
            Console.WriteLine(DateTime.Now.ToString());
            returnlist.Find(t => t.ID == id); }}}Copy the code

There is a section of health check interface, the function is to let the service center know that the service is still accessible, do not need any business, so how simple how to:



The Model code:

public class Student
{
    public string ID { get; set; }
    public string StudentName { get; set; }
    public int StudentAge { get; set; }}Copy the code

Appsettings. json configuration, add “Consul” to ServiceIP, change it to your PC’s IP address (do not set it to 127.0.0.1, there will be abnormal access later)

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"."Microsoft": "Warning"."Microsoft.Hosting.Lifetime": "Information"}},"AllowedHosts": "*"."Consul": {
    "Address": "http://127.0.0.1:8500"."CheckUrl": "/api/Default/Check"."DataCenter": "dc1"."ServiceIP": "192.168.2.119"."ServicePort": 551."ServiceName": "Student"}}Copy the code

Change the CreateHostBuilder method from program. cs to:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            string ip = Common.ConsulServiceIP;
            int port = Common.ConsulServicePort;
            webBuilder.UseStartup<Startup>().UseUrls($"http://{ip}:{port}");
        });
Copy the code

In a Startup. Cs is added in the Configure method of “ClassLibrary.Com mon. ConsulRegister ();”

The “Student” service is created, and the “Teacher” service is created, but with the appSettings. json service name and port number changed.

3. Start the service

To start the service, run the CMD command, CD to the Debug directory, and run dotnet ServiceStudent. DLL and dotnet Serviceteacher. DLL respectively.

Check whether the port is occupied or out of range. If this fails, try changing it to another port in the configuration file.





After the service runs successfully, open thehttp://127.0.0.1:8500/ “, the following screen successfully registered



A service may be deployed on multiple servers, using “Teacher” to simulate running on multiple machines.

Do not close the previously running service, open the configuration file under Teacher Debug directory,

Open a CMD file and run dotnet Serviceteacher.dll.



Then the service center will change

Use of services

1. General structure of client project:



2. Create a.net core ClassLibrary project, name it “ClassLibrary”, then NuGet search and install

“Consul,” “Microsoft. Extensions. The Configuration”

Common. Cs code:

using Consul;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace ClassLibrary
{
    public class Common
    {
        public static IConfiguration Configuration { get; }
        static Common()
        {
            Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json".false.true).Build();
        }

        public static string ConsulAddress
        {
            get { return Configuration["ConsulAddress"]; }}/// <summary>
        ///Access to services
        /// </summary>
        public static string GetService(string serviceName)
        {
            ConsulClient client = new ConsulClient(c => c.Address = new Uri(ConsulAddress));

            var response = client.Agent.Services().Result.Response;

            / / service names are case sensitive, if want to distinguish: Equals (serviceName, StringComparison. OrdinalIgnoreCase)
            var services = response.Where(s => s.Value.Service.Equals(serviceName)).Select(s => s.Value);

            // Perform modularization, randomly acquire a server, or use other load balancing strategies
            var service = services.ElementAt(Environment.TickCount % services.Count());

            return service.Address + ":" + service.Port;
        }

        /// <summary>
        ///Getting the service (asynchronous method)
        /// </summary>
        public async Task<string> GetService2(string serviceName)
        {
            ConsulClient client = new ConsulClient(c => c.Address = new Uri(ConsulAddress));

            var response = (await client.Agent.Services()).Response;

            / / service names are case sensitive, if want to distinguish: Equals (serviceName, StringComparison. OrdinalIgnoreCase)
            var services = response.Where(s => s.Value.Service.Equals(serviceName)).Select(s => s.Value);

            // Perform modularization, randomly acquire a server, or use other load balancing strategies
            var service = services.ElementAt(Environment.TickCount % services.Count());

            return service.Address + ":" + service.Port;
        }

        public static string HttpGetString(string url)
        {
            HttpClient httpClient = new HttpClient();
            string result = httpClient.GetAsync(url)
            .Result.Content.ReadAsStringAsync().Result;
            httpClient.Dispose();
            return result;
        }

        public static T HttpGetObject<T> (string url)
        {
            string result = HttpGetString(url);
            returnNewtonsoft.Json.JsonConvert.DeserializeObject<T>(result); }}}Copy the code

3. Create a webAPI project for.net Core, name it ClientSite, and deselect Configure for HTTPS

StudentController code:

using ClassLibrary;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace ClientSite.Controllers{[Route("api/[controller]/[action]")]
    [ApiController]
    public class StudentController : ControllerBase{[HttpGet]
        public object GetList()
        {
            string ip = Common.GetService("Student");
            List<Student> list = Common.HttpGetObject<List<Student>>($"http://{ip}/api/Default/GetList");
            return new
            {
                address = ip,
                data = list
            };
        }

        [HttpGet]
        public object GetModel(string id)
        {
            string ip = Common.GetService("Student");
            Student model = Common.HttpGetObject<Student>($"http://{ip}/api/Default/GetModel? id={id}");
            return new{ address = ip, data = model }; }}}Copy the code

TeacherController code:

using ClassLibrary;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace ClientSite.Controllers{[Route("api/[controller]/[action]")]
    [ApiController]
    public class TeacherController : ControllerBase{[HttpGet]
        public object GetList()
        {
            string ip = Common.GetService("Teacher");
            List<Teacher> list = Common.HttpGetObject<List<Teacher>>($"http://{ip}/api/Default/GetList");
            return new
            {
                address = ip,
                data = list
            };
        }

        [HttpGet]
        public object GetModel(string id)
        {
            string ip = Common.GetService("Teacher");
            Teacher model = Common.HttpGetObject<Teacher>($"http://{ip}/api/Default/GetModel? id={id}");
            return new{ address = ip, data = model }; }}}Copy the code

Appsettings. Json to join:

"ConsulAddress": "http://127.0.0.1:8500"
Copy the code



4. Launch the site with VS and access it with Postman

“Http://ip:port/api/Student/GetList”

“Http://ip:port/api/Student/GetModel? Id = 002”





Visit “http://ip:port/api/Teacher/GetList” for many times, the address will random switching, look for the return of the port number



Code:Files.cnblogs.com/files/shous…