Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

.net Core micro-service how to implement service governance based on Consul

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you ".NET Core microservices how to achieve service governance based on Consul", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn ".NET Core microservices how to achieve service governance based on Consul" this article.

1. Configuration file for Consul service registration 1.1 Review of Consul experimental cluster

Here we have three Consul Server nodes, one Consul Client node, and two ClientService instances running on the Client node, occupying ports 8810 and 8820, respectively. As for the API gateway service based on Ocelot, it has not been implemented yet, so I will share it with you later. It is assumed that we have started these nodes and are able to successfully access the two ClientService instances (either through IIS or from the command line to start the Kerstel server to run).

Instance 1: 192.168.80.71, purl 8810

Example 2: 192.168.80.71, purl 8820

1.2 prepare the json configuration file

Here I have prepared a JSON configuration file (eg. Net) as shown below. Name it services_config.json), and configure two services in it:

{"services": [{"id": "EDC_DNC_MSAD_CLIENT_SERVICE_01", "name": "CAS ClientService", "tags": ["urlprefix-/ClientService01"], "address": "192.168.80.71", "port": 8810 "checks": [{"name": "clientservice_check", "http": "http://192.168.80.71:8810/api/health"," interval ":" 10s " "timeout": "5s"}]}, {"id": "EDC_DNC_MSAD_CLIENT_SERVICE_02", "name": "CAS ClientService", "tags": ["urlprefix-/ClientService02"] "address": "192.168.80.71", "port": 8820, "checks": [{"name": "clientservice_check", "http": "http://192.168.80.71:8820/api/health"," interval ":" 10s " "timeout": "5s"}]]}

As for the meaning of the configuration file, I won't repeat it here, which is consistent with the items registered in the code in the previous article.

After editing, we create a new folder in the Consul Client node, put in the json configuration file, and then start / restart the Consul Client service:

192.168.80.71 > consul agent-bind 0.0.0.0-client 192.168.80.71-config-dir=C:\ Server\ Consul\ config- data-dir=C:\ Server\ Consul\ tempdata-node EDC.DEV.WebServer-join 192.168.80.100

After startup, you can see that Consul has registered the two instances of ClientService by scanning the configuration file.

1.3 View service status through WebUI

As you can see, two ClientService instances have been successfully registered.

1.4 Service Discovery through API

URL > 192.168.80.100:8500/v1/catalog/service/CAS Client Service

You can see that the information of two service instances is returned. Of course, it is recommended that there is no space in the service name. In addition, in the process of service discovery, a certain load balancing strategy will be applied, and one of the two service instances will be returned to the service consumer, such as random, polling, weighted polling, minimum number of connections based on performance, and so on. This piece will be shared with you later in the API Gateway practice.

2. Key/Value storage of Consul cluster

In addition to implementing service registration and service discovery, Consul also provides powerful KV (Key/Value) storage. We can use Consul's hierarchical KV storage to do anything, such as dynamic configuration, signature, coordination, leader election, etc. The API stored by KV is based on http.

2.1 View all KV

We can query in the consul node from the command line:

192.168.80.100 > curl-v http://192.168.80.100:8500/v1/kv/?recurse

As you can see, 404 Not Found is returned, so you can see that there is no Key/Value storage entry.

*。 About the? recurse parameter = > is used to specify to view multiple KV

Of course, we can also view and manage KV through WebUI, as shown in the following figure. Later, we all use the Shell command line to call API, without calling the WebUI interface.

2.2 add KV

Let's assume that we want to configure the account of a video live streaming platform:

192.168.80.100 > curl-X PUT-d 'edisonchou' http://192.168.80.100:8500/v1/kv/web/vhallaccount

Key:vhallaccount, value:edisonchou

After being added, you can view the Value of this Key by calling the API with the following command

192.168.80.100 > curl http://192.168.80.100:8500/v1/kv/web/vhallaccount

*。 Since the Value of Consul is encoded by Base64 (mainly to allow non-UTF-8 characters), what you see here is the encoded result. We can get the final value by decoding.

2.3 verify that KV is synchronized

Since we are calling the KV storage carried out by the Leader node, we want to verify whether synchronization is performed on the other two nodes, otherwise there is only one node in the KV that cannot achieve the effect of synchronization.

192.168.80.101 node:

192.168.80.102 node:

You can see that the key value has been synchronized among the three nodes in the cluster.

2.4Editing KV and deleting KV

Editing a KV is exactly the same as adding a KV, as shown below:

192.168.80.100 > curl-X PUT-d 'andyai' http://192.168.80.100:8500/v1/kv/web/vhallaccount

HTTP DELETE is mainly used to delete KV

192.168.80.100 > curl-X DELETE http://192.168.80.100:8500/v1/kv/web/vhallaccount

The results will not be demonstrated here.

3. Watch mechanism of Consul service alarm

Circuit breaker protection is implemented in both Consul and Ocelot, which means that when a service is abnormal (for example, one of our service instances is down and the health check mechanism of Consul is detected), the system maintainer should be alerted. In Consul, service alarms are also implemented through configuration files.

3.1 add watch.json profile

{"watches": [{"type": "checks", "handler_type": "http", "state": "critical", "http_handler_config": {"path": "http://192.168.80.71:9000/notice"," method ":" POST "," timeout ":" 10s " "header": {"Authorization": ["token"]}}]}

*。 For details of watch, please refer to: https://www.consul.io/docs/agent/watches.html

After editing here, you can put it in the config directory, and the new watches_config.json configuration file will be loaded when the Consul Client Agent service is restarted.

3.2 add NoticeService services

Write a new ASP.NET Core WebAPI program, its main function is to accept the parameters from Consul POST and call the method to send e-mail.

(1) Controller compilation

[Route ("api/ [controller]")] public class HomeController: Controller {public IConfiguration Configuration {get;} public HomeController (IConfiguration configuration) {Configuration = configuration;} [HttpPost ("/ notice")] public IActionResult Notice () {var bytes = new byte [10240]; var I = Request.Body.ReadAsync (bytes, 0, bytes.Length) Var content = System.Text.Encoding.UTF8.GetString (bytes) .trim ('\ 0') EmailSettings settings = new EmailSettings () {SmtpServer = Configuration ["Email:SmtpServer"], SmtpPort = Convert.ToInt32 (Configuration ["Email:SmtpPort"]), AuthAccount = Configuration ["Email:AuthAccount"], AuthPassword = Configuration ["Email:AuthPassword"], ToWho = Configuration ["Email:ToWho"] ToAccount = Configuration ["Email:ToAccount"], FromWho = Configuration ["Email:FromWho"], FromAccount = Configuration ["Email:FromAccount"], Subject = Configuration ["Email:Subject"]} EmailHelper.SendHealthEmail (settings, content); return Ok ();}}

No longer interpret this code.

(2) compiling SendHealthEmail method

Public class EmailHelper {public static void SendHealthEmail (EmailSettings settings, string content) {try {dynamic list = JsonConvert.DeserializeObject (content); if (list! = null & & list.Count > 0) {var emailBody = new StringBuilder ("Health check failure:\ r\ n") Foreach (var noticy in list) {emailBody.AppendLine ($"- -"); emailBody.AppendLine ($"Node: {noticy.Node}") EmailBody.AppendLine ($"ServiceID: {noticy.ServiceID}"); emailBody.AppendLine ($"ServiceName: {noticy.ServiceName}"); emailBody.AppendLine ($"CheckID: {noticy.CheckID}"); emailBody.AppendLine ($"Check Name: {noticy.Name}") EmailBody.AppendLine ($"Check Status: {noticy.Status}"); emailBody.AppendLine ($"Check Output: {noticy.Output}"); emailBody.AppendLine ($"-") } var message = new MimeMessage (); message.From.Add (new MailboxAddress (settings.FromWho, settings.FromAccount)); message.To.Add (new MailboxAddress (settings.ToWho, settings.ToAccount)); message.Subject = settings.Subject Message.Body = new TextPart ("plain") {Text = emailBody.ToString ()}; using (var client = new SmtpClient ()) {client.ServerCertificateValidationCallback = (s, c, h, e) = > true; client.Connect (settings.SmtpServer, settings.SmtpPort, false) Client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Authenticate (settings.AuthAccount, settings.AuthPassword); client.Send (message); client.Disconnect (true) } catch (Exception ex) {Console.WriteLine (ex.Message);}}

The MailKit library (.net core is supported) is used here, which can be searched and installed through NuGet. In addition, why do you accept these parameter properties? you can take a look at the checks type in the watches page of the Consul official document, as shown in the following figure:

(3) if you publish NoticeService to 192.168.80.71 server, you can also add it to the Consul configuration file:

View Code

After the release is completed, restart the Consul service of the Consul Client node (192.168.80.71), and you can see that NoticeService is also registered successfully:

3.3 Test Service Alert

(1) manually shut down a ClientService service in IIS, for example: here I shut down ClientService.01

(2) check the automatically sent Email content: from the Email, we can know which Server node which Service has a problem, and can roughly understand the cause (Check Output), then our system maintenance staff should get up and work overtime.

These are all the contents of the article "how .NET Core microservices implement service governance based on Consul". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report