Objective
With the emergence of micro-services, the management of services is extremely important. All know that microservices are "split", the bloated single-block application, split into a number of lightweight services, each service can be in a short period of time to reconstruct, iterate, delivery. With the increase in the number of micro-services, due to quantitative quality, resulting in a new problem one of which is the management of services. With the growth of micro-services in the business, it is possible that the technology leader can not clearly remember the deployment of services, the health of services can not always pay attention to, so the role of service governance system is essential.
The source code of this article:
Demo:https://github.com/skychensky/consul.demo
Package: Https://github.com/SkyChenSky/Sikiro.Tookits.Consul
Consul
Consul is a simple, easy-to-use, scalable and strong service governance system.
The main core features are:
- Service discovery
- Health Check
- Key-Value Storage
- Multi-Data center
The consul agent accesses the Registry's service node each time, if the response code of "20X" is considered healthy.
A key-value store can be thought of as a simple k/v database, so you can use this to store configuration information.
Service discovery
Service Discovery Sub-service registration and service lookup.
Service Registration
Add (remove) the Service node information (address + port) to the registry, which records the node information and status of the service
Service Finder
The node information that is queried by other services or systems through the registry to the specified available service.
How services are discovered
The way of service discovery is divided into autonomous and proxy type.
Autonomous type
Each service actively adds (deletes) its own node information to the registry. The implementation is through the unified encapsulation or the library, by the service each node undertakes the service discovery function, compared with the proxy type to share the access pressure by the respective node.
Proxy type
Service discovery is done by a system (load balancing System) or service (API Gateway). Because a system or service is complete, as the enrollment service increases the performance bottleneck, you need to do this cluster.
Consul mode
There are two modes of consul, client and server, and there is a consul agent in all modes.
Client mode
The client mode is a lightweight consul agent that only has functions such as registration services, health checks, and forwarding queries.
Server mode
Compared with client mode, the server mode has more data storage, leader elections, and so on, besides the function of client mode.
The official recommendation server mode should be guaranteed 3-5, and should be odd, for what, because less than 3 can not guarantee high availability, more than 5 will give the consistency of database synchronization pressure, and the client number control is not fastidious.
Cluster deployment
Download Consul https://www.consul.io/downloads.html
On Server A, open cmd,
Consul agent-server-bootstrap-expect=1 -bind=192.168. 20.80 -client=192.168. 20.80 -join=192.168. 20.80 -datacenter=dc1-data-dir=data-ui-node=consul-
On Server B, open cmd,
Consul agent-server-bind=192.168. 20.81 -client=192.168. 20.81 -join=192.168. 20.80 -data-dir=data-node=consul-Bayi
Open Browser Input http://192.168.20.80:8500
Brief analysis of Directives
- -server
- Consul is started in server mode and is not populated by default in client mode
- -bootstrap-expect=1
- Number of cluster nodes, data synchronization occurs when the number of cluster nodes reaches the number of claims
- -bind=192.168. 20.80
- Current Consul Service binding address
- -client=192.168. 20.80
- HTTP interface binding address, client call required
- -join=192.168. 20.80
- Join target cluster when starting service
- -node=consul-Bayi
- -ui
- Start Web Management background
Client-side Practice installation Consul
Encapsulation extension
Only part of the core code, the specific can view the demo source.
Inject consulclient
Public Static Iservicecollection Addconsul ( This iservicecollection servicecollection, action<consulconfiguration> optionaction) { new consulconfiguration (); Optionaction (_consulconfiguration); var New Consulclient (x = new Uri (_consulconfiguration.host)); Servicecollection.addsingleton (consulclient); return servicecollection; }
Register the current service to consul
Private Staticconsulconfiguration _consulconfiguration; Public StaticIapplicationbuilder Useconsul ( ThisIapplicationbuilder app, Iapplicationlifetime lifetime, action<serverconfiguration>optionaction) { varConsulclient = App. Applicationservices.getservice<consulclient>(); if(Consulclient = =NULL) Throw NewException ("Please Addconsul first"); varServerconfiguration =Newserverconfiguration (); Optionaction (serverconfiguration); varServiceregistration =getserviceregistration (serverconfiguration); //Add RegistrationConsulClient.Agent.ServiceRegister (serviceregistration). Wait (); //Cancel RegistrationLifetime. Applicationstopping.register (() ={consulClient.Agent.ServiceDeregister (serviceregistration.id). Wait (); }); returnapp; }Private StaticUri Getselfuri (stringuristring) { return NewUri (uristring); } Private Staticagentserviceregistration getserviceregistration (serverconfiguration serverconfiguration) {varLocalip =Getselfuri (serverconfiguration.selfhost); varServiceregistration =Newagentserviceregistration {Check=Newagentservicecheck//Health Check {deregistercriticalserviceafter= Timespan.fromseconds ( -), Interval= Timespan.fromseconds ( -), HTTP= $"Http://{localip.host}:{localip.port}/api/health", Timeout= Timespan.fromseconds (3)}, ID= Guid.NewGuid (). ToString ("N"), Name=Serverconfiguration.servername, Address=Localip.host, Port=Localip.port, Tags=New[] {serverconfiguration.servername}}; returnserviceregistration; }
Add Health Check Interface
With the above package can be in the same library, avoid each Web service to write a
[Route ("Api/[controller]")] Public class Healthcontroller:controller { [httpget] public okresult Get () { return Ok (); } }
On the Startup.csConsulEncapsulation is called configureservices
Public void configureservices (iservicecollection services) { = = { option. Withhost (configuration["consulconfiguration:host"); }). Addmvc (); }
Configure
App. Useconsul (lifetime, option ={ option. Withselfhost (configuration["selfhost"]); Option. Withservername (configuration["consulconfiguration:servername");});
k/v extension
Only put, get, delete are implemented, and the rest can be added on demand
Public Static classconsulkyextensions { Public Static Asynctask<BOOL> Kvputasync ( ThisConsulclient Consulclient,stringKeystringvalue) { varKvpair =NewKvpair (key) {Value=Encoding.UTF8.GetBytes (value)}; varresult =awaitConsulClient.KV.Put (Kvpair); if(result.) StatusCode = =Httpstatuscode.ok)returnresult. Response; return false; } Public Static BOOLKvput ( ThisConsulclient Consulclient,stringKeystringvalue) { varKvpair =NewKvpair (key) {Value=Encoding.UTF8.GetBytes (value)}; varresult = ConsulClient.KV.Put (Kvpair). Configureawait (false). Getawaiter (). GetResult (); if(result.) StatusCode = =Httpstatuscode.ok)returnresult. Response; return false; } Public Static Asynctask<string> Kvgetasync ( ThisConsulclient Consulclient,stringkey) { varresult =awaitConsulClient.KV.Get (key); returnEncoding.UTF8.GetString (result. Response.value); } Public Static stringKvget ( ThisConsulclient Consulclient,stringkey) { varresult = ConsulClient.KV.Get (key). Configureawait (false). Getawaiter (). GetResult (); returnEncoding.UTF8.GetString (result. Response.value); } Public Static Asynctask<BOOL> Kvdeleteasync ( ThisConsulclient Consulclient,stringkey) { varresult =awaitConsulClient.KV.Delete (key); if(result.) StatusCode = =Httpstatuscode.ok)returnresult. Response; return false; } Public Static BOOLKvdelete ( ThisConsulclient Consulclient,stringkey) { varresult = ConsulClient.KV.Delete (key). Configureawait (false). Getawaiter (). GetResult (); if(result.) StatusCode = =Httpstatuscode.ok)returnresult. Response; return false; } }
Deployment Startup
Modify Appsettings.json, fill in the target Consul address and the service address
{ "Logging": { "Includescopes":false, "LogLevel": { "Default":"Warning" } }, "consulconfiguration": { "Host":"http://192.168.20.80:8500", "ServerName":"Consulwebdemo", "Id":"20e2cfbb-95c0-496a-b70f-11111111" }, "Selfhost":"http://localhost:1495/"}
After startup, the effect can be displayed if the service is healthy.
Winserver Consul deployment practices with. NET Core clients (with demo source)