C # and Consul cluster service registration and discovery

What Consul that?

Socket Consul on essentially a communication middleware

It implements two main functions, service registration and discovery with its own load balancing cluster.

We can understand him without the application interface, because there is no interface, so you want to start Consul can only use the command line; also because there is no interface, use the command line to start once the Consul, then execute the command line cmd .exe program, became Consul of the host; once closed Cmd window, Consul stopped running.

What is the nature of the service registration and discovery is?

In fact, service registration and discovery of principle is very simple.

When we run natively Consul, he will automatically listen 8500 port; then we (the open-source library can be retrieved on nuget, the following article will explain) through an open-source library, call it in different ways to to this Consul process sends TCP messages, or to register service discovery service.

Consul process upon receipt of the registration message, put the registered service information is stored to a local disk or memory (because I do not have specific data to investigate whether the use of a database to store Consul, but we all know that the data stored in the database is a local disk, so, it is certainly the data into the disk or in memory of).

data center

Consul place to store data, its official name for the data center, which is said above, we save a local disk or memory registered service information.

Consul provides load balancing cluster

Consul cluster is well understood, after the successful launch of our Consul, in addition to its listening port other than 8500, it listens a 8031 ​​port.

The 8031 ​​port is used to communicate with each other Consul cluster.

We all know that cluster to more than two computers, so we need to find two or more computers installed Consul middleware.

Then, using the Consul command line to connect two computers together, so that the cluster is formed.

Within the cluster that is installed on each computer Consul middleware, we referred to as server agent (Agent); when the cluster starts, will elect a Leader in between multiple proxy servers.

Election Leader nature is communication between the proxy server, which is port 8031 ​​to communicate through the above-mentioned.

When elected Leader, proxy server itself can load information to the Leader, so client calls Consul data retrieval service, you can go on the best performance of the machine to get information. (Note: this is an example, not actual processing mode of load balancing Consul)

Consul Proxy Server installation

First, go to the official website to download Consul, the official website Download https://www.consul.io/downloads.html

Pull the bottom of the site, select the Consul Window64-bit download, as shown below:

After the download is complete, we get a compressed consul_1.6.2_windows_amd64.zip; decompressed give consul.exe file, as shown below:

Because we have to use the command line to run the consul, therefore, the directory where we will consul.exe add environment variables, so that when we execute consul-related commands in the CMD window, the system will automatically send the commands to the consul.exe file is executed.

Configuration environment variable as shown below:

After configuring the environment variables, we open a cmd command line window and enter the consul to confirm our environment variable configuration is successful, as shown below

See figure information, on behalf of our consul environment variable is configured, ready to run.

Next, we enter consul command cmd in this form to start the consul proxy server, the command is as follows:

Command interpreter as follows:

1
consul agent -server -ui -bootstrap-expect=1 -data-dir=/tmp/consul -node=consul-1 -client=0.0.0.0 -bind=192.168.1.111 -datacenter=dc1

In fact, it is consul command can be found to their definitions on the Web, but I think the explanation is too official, so, I'm here I think a better explanation.

consul agent: Command head, there must be.

-server: surface we are going to start the server agent (agent) is a service mode. Consul Agent operating mode, there are two, Server mode and Client mode. The difference is simply Server Agent mode can be elected as Leader, and Client mode can not, of course, there are other differences, we are interested can inform themselves about.

-ui: After consul run, it will provide a http://127.0.0.1:8500/ui/ site, which stores the Consul Agent each node, and services related to registration information, that is reflected in the data center web page. This parameter represents whether to create the site, this parameter related to this data center site.

bind: ip address of the machine, another proxy server in the cluster can access this computer's consul proxy server through the ip.

bootstrap-expect: a cluster start conditions, means that when the server mode (Server Mode) agents after reaching this number, began to run.

data-dir: Data Center data is located, the directory must be stable, the system is restarted also continue to exist.

datacenter: name of the current data center agent, the default is dc1.

node: The node name in the cluster in a cluster must be unique, the default is the host name of the node (on behalf of a machine).

client: the local ip address used here 0.0.0.0, it means that all IP server can be, that is, when this computer has two ip, 192.168.1.111 and 192.168.1.112, you can access to the machine by IP maybe the consul proxy server.

Running the command, as shown below:

You can see, our Consul agency services has already been closed.

Now, we go to another computer, open cmd window, run the following command consul:

1
consul agent -server -ui -bootstrap-expect=1 -data-dir=d:\consul -node=consul-2 -client=0.0.0.0 -bind=192.168.80.112 -datacenter=dc1 -join 192.168.80.111

You can see, we added a join 192.168.80.111 on the command line of the last surface; this command, we join this successful proxy server computer to the consul cluster above.

Service registration and discovery

 

Consul service registration

First, we create a WebAPI, here created a Web API to use the Core framework, in order to facilitate testing, I'll just take the local VisualStudio start testing.

After creating WebAPI, we find the Consul Net version of the library in Nuget.

Search Consul in Nuget, and then select the installation option in the following figure.

Then, we Startup folder, add a function, as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static void RegisterConsul()
{
   var consulClient = new ConsulClient(p => { p.Address = new Uri($ "http://127.0.0.1:8500" ); });//请求注册的 Consul 地址
   //这里的这个ip 就是本机的ip,这个端口8500 这个是默认注册服务端口
   var httpCheck = new AgentServiceCheck()
   {
     DeregisterCriticalServiceAfter = TimeSpan.FromSeconds( 5 ), //服务启动多久后注册
     Interval = TimeSpan.FromSeconds( 10 ), //间隔固定的时间访问一次,https://localhost:44308/api/Health
     HTTP = $ "https://localhost:44308/api/Health" ,//健康检查地址 44308 是visualstudio启动的端口
     Timeout = TimeSpan.FromSeconds( 5 )
   };
    
   var registration = new AgentServiceRegistration()
   {
     Checks = new [] { httpCheck },
     ID = Guid.NewGuid().ToString(),
     Name = "test1" ,
     Address = "https://localhost/" ,
     Port = 44308 ,
     
   };
 
   consulClient.Agent.ServiceRegister(registration).Wait(); //注册服务
 
   //consulClient.Agent.ServiceDeregister(registration.ID).Wait();//registration.ID是guid
   //当服务停止时需要取消服务注册,不然,下次启动服务时,会再注册一个服务。
   //但是,如果该服务长期不启动,那consul会自动删除这个服务,大约2,3分钟就会删了
 
}

Then call this method in Configure, so, when we debug or run the project, it will automatically register the Webapi to Consul Lane.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   if (env.IsDevelopment())
   {
     app.UseDeveloperExceptionPage();
   }
   
   app.UseHttpsRedirection();
 
   app.UseRouting();
 
   app.UseAuthorization();
 
   app.UseEndpoints(endpoints =>
   {
     endpoints.MapControllers();
   });
   RegisterConsul(); //注册本服务到consul集群
  
}

After registration service, you can visit the local data center http://127.0.0.1:8500/ui/dc1/services [] to view the status of registration services.

Consul Service Discovery

After the service the registration is complete, we'll create a console project to service discovery.

Once created project, also need to reference consul libraries, like the server searches in Nuget.

Write code as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static void Main( string [] args)
{
   var consulClient = new ConsulClient(x => x.Address = new Uri($ "http://192.168.1.178:8500" ));//请求注册的 Consul 地址
   var ret = consulClient.Agent.Services();
    
   var allServer = ret.GetAwaiter().GetResult();
   //这个是个dictionary的返回值,他的key是string类型,就是8500/ui上services的instance的id
   var allServerDic = allServer.Response;
   var test1 = allServerDic.First();
   string name = test1.Value.Service; //服务名,就是注册的那个test1
   string serverAddress = test1.Value.Address;
   int serverPort = test1.Value.Port;
   Console.WriteLine($ "serverAddress:{serverAddress}==serverPort{serverPort}" );
   //我们可以在客户端启动的时候,调用一下consul来查找服务
   //比如,我们可以在服务集合里查找 服务名叫test1的服务 然后在调用它
   //这样,当服务器改变了test1的ip和端口,我们依然可以在集群里找他test1新的ip和端口了
   Console.ReadKey();
}

Results are as follows:

You can see, we have successfully called Consul, also successfully acquired the service information.

In fact Consul in addition to registration and inquiry services, may also be Key-Value store, that is to say, this is a distributed Key-Value storage cluster.

Key-Value存储的用法在Github已经有例子了,网址:https://github.com/PlayFab/consuldotnet

C#使用Consul进行服务注册与发现就讲完了。

Guess you like

Origin www.cnblogs.com/wwkk/p/12590237.html