. net core learning notes, components: service registration and discovery


1. What is a service registry?

In learning service registration and discovery, we should first understand what is service registration and discovery.

Here I give a very common example in our life – online shopping to briefly illustrate that online shopping is very common in our daily life. In fact, the online shopping (merchant rookie post buyer) constitutes a very simple registration discovery logic. After we buy the goods, we need to get the goods. If it is an ordinary point-to-point service, the merchant will directly express the goods to the buyer. If the buyer is not at home temporarily, the receiving will fail at this time.

When introducingRegistration Center – rookie stationAfter delivery, the merchant only needs to send the goods to the rookie post station (service registration), and the buyer can go to the rookie post station to get their goods (service discovery) at the right time through the express number or scanning code. In this link, the rookie post station is only responsible for receiving and sending the goods, which constitutes a simple service discovery logic.

2. Why use a service registry?

1. Decoupling:

There is complete decoupling between service consumers and service providers. Just like the above example: buyers don’t need to care about what express the seller sends, as long as I go to the express station to get the goods.

2. Extension:

When service consumers and service providers add or delete new services, there is no impact on both sides. For example, if the buyer has bought many different goods, then the buyer only needs to go to the rookie post station to get the corresponding goods according to different pick-up credentials.

3. Different service registry components


Zookeeper is a distributed, open source distributed application coordination service, an open source implementation of Google chubby, and an important component of Hadoop and HBase. It is a software that provides consistency services for distributed applications, including configuration maintenance, domain name service, distributed synchronization, group service, etc. The goal of zookeeper is to encapsulate complex and error prone key services, and provide users with simple and easy-to-use interfaces and high-performance and stable systems. Zookeeper contains a simple set of primitives that provide Java and C interfaces.


Consul is an open source product launched by hashicorp company, which is used to realize service discovery, service isolation and service configuration of distributed system. Each of these functions can be used separately or at the same time. Currently, the official website of consul mainly promotes the use of consul in service grid.


Etcd is an open source project launched by the coreos team in June 2013. Its goal is to build a highly available distributed key value database. Etcd internal useraftAs a consistency algorithm, etcd is implemented based on go language.


Eureka registration center has been closed, so it is not recommended to study at home.

4. What is consul

Consul is an open source tool for service discovery and configuration in distributed systems. It is developed by go language. It mainly consists of several parts

  • Service discovery:Clients provide services through consul, similar to API, mysql, or other clients, which can use consul to discover service providers. Using services like DNS or HTTP, applications and applications can easily find the services they rely on.

  • Physical examination:Consul clients can provide health checks related to a given service (the web server returns 200 OK) or local nodes (“memory utilization is less than 90%”). This information can monitor the operation of the cluster and keep access away from unhealthy host components.

  • Key value pair storage:Applications can use cousul’s hierarchical key value pairs.

  • Multi data center:Consul has multiple data centers that can be opened and used.

5. How to use asp.net Using consul in core

Now that we have talked about the conceptual content, let’s take a look at how to use it asp.net Use consul under core + windows.

5.1. Download Consul

Official website address:https://www.consul.io/

Download address:https://releases.hashicorp.com/consul/1.7.2/orhttps://www.consul.io/downloads.html

5.2 start Consul

consul.exe agent -dev



Parameter introduction:

  • Version: consumer version
  • Node ID: the node ID currently started by the consumer
  • Node name: the name of the currently started node. The default is the name of the current computer
  • Datacenter: Data Center
  • Service: the startup mode of consumer. True means server mode and false means client mode
  • Client addr: client connection address, supports HTTP, HTTPS, grpc and DNS, and uses HTTP by default
  • Cluster addr: cluster address, which is the startup mode in server mode

5.3 coding

5.3.1 create two asp.net Core webapi project, and reference the package of consul respectively.

5.3.2 write service provider code

Write the following code in the configure method of the startup class of the consulservice:

1 // create a client connection for consul
 2             var consulClient = new ConsulClient(configuration =>
 3             {
 4 // consul's connection address
 5                 configuration.Address = new Uri("");
 6             });
 7 // create the service registration information of consul
 8             var registration = new AgentServiceRegistration()
 9             {
10 // service ID
11                 ID = Guid.NewGuid().ToString(),
12 // service name
13                 Name = "demoService",
14 // service connection address
15                 Address = "https://localhost",
16 // port
17                 Port = 5001
18 // there are some other properties of the agentserviceregistration object. I'll learn more about them later
19             };
20 // registration service
21             consulClient.Agent.ServiceRegister(registration);

Then start the project:



The project starts successfully. We visit the visual web page of consul (the default address is port 8500) to see if the service is registered successfully






As can be seen from the above screenshot, the demoservice service we just registered has been successfully registered.

5.3.3 write service consumer code

Add a service folder to the service consumer project, add a service consumption interface, and then implement this interface

1     public interface IDemoService
 2     {
 3         Task GetDemoService();
 4     }
 5     public class DemoService : IDemoService
 6     {
 7         private readonly IHttpClientFactory httpClientFactory;
 9         public DemoService(IHttpClientFactory httpClientFactory)
10         {
11             this.httpClientFactory = httpClientFactory;
12         }
14         public async Task GetDemoService()
15         {
16             var res = "";
17 // create a consumer connection object
18             var consulClient = new Consul.ConsulClient(configuare =>
19             {
20 // consul's connection address
21                 configuare.Address = new Uri("");
22             });
23 // get the corresponding service according to the service name just registered
24             var queryResult = await consulClient.Catalog.Service("demoService");
25 // service connection address
26             var serviceUrls = new List();
27 // traverse the obtained service list
28             foreach (var service in queryResult.Response)
29             {
30 // splicing connection address
31                 serviceUrls.Add(service.ServiceAddress + ":" + service.ServicePort);
32             }
33             HttpClient httpClient = httpClientFactory.CreateClient();
34             HttpResponseMessage response = await httpClient.GetAsync(serviceUrls[0] + "/api/Home/");
35             if (response.StatusCode == HttpStatusCode.OK)
36             {
37                 res = await response.Content.ReadAsStringAsync();
38             }
39             return res;
40         }
41     }

Call this service on the controller:

1         private readonly ILogger _logger;
 2         private readonly IDemoService _demoService;
 4         public HomeController(ILogger logger, IDemoService demoService)
 5         {
 6             _logger = logger;
 7             _demoService = demoService;
 8         }
10         [HttpGet]
11         public Task Get()
12         {
13             return _demoService.GetDemoService();
14         }

Note: remember to inject the above service interface and class into the configureservice method in the startup class. I don’t need to tell you more about why.

1 services.AddScoped();

Finally, we start the consumer project and request the corresponding interface to see the effect. Obviously, the service has been successfully requested.


That’s all for the moment. The above is the simplest application of. Net core to consult. With the deepening of learning, there will be corresponding learning notes.

Because I am also in the exploratory stage, what I have written above is just some study notes, so some understanding may not be accurate enough. I hope that some of the contents I have written are wrong, and you can be tolerant and correct.