In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article Xiaobian for you to introduce in detail "Asp.Net Core how to use Ocelot to achieve service registration and discovery", the content is detailed, the steps are clear, and the details are handled properly. I hope this "Asp.Net Core how to use Ocelot to achieve service registration and discovery" article can help you solve your doubts.
1. Service Registration and Discovery (Service Discovery)
Service registration: by writing a registration code in each service instance, the instance will first register with the registry (such as Consul, ZooKeeper, etcd, Eureka) when starting, then the client can know the address, port number, health status and other information of each service instance through the registry, and you can also delete the service instance through the registry. Here the registry is equivalent to the control center responsible for maintaining service instances.
Service discovery: after service instances are registered in the registry, the client can know the health status of these service instances through the registry.
2.Consul
If you want to implement service registration and discovery, you need a registry, and the main introduction here is Consul.
Consul official website: https://www.consul.io/, its main functions are: service registration and discovery, health check, Key/Value, multi-data center.
If you deploy Consul on Windows, execute the consul.exe agent-dev command line in the consul.exe directory.
3.Asp.Net Core registers the service instance with Consul
The process of calling Asp.Net Core to the Consul registration service instance is shown in the following figure:
For Asp.Net Core to register a service instance with Consul, you need to reference the NuGet software package supported by Consul in the Gateway project. The installation command is as follows:
Install-Package Ocelot.Provider.Consul
Then add the following to your ConfigureServices method:
Services.AddOcelot () .AddConsul ()
In the Ocelot service discovery project example, service registration and discovery can be configured through the APIGateway project GlobalConfiguration option. The specific code for file configuration is as follows:
{"Routes": [{"UseServiceDiscovery": true, "DownstreamPathTemplate": "/ {url}", "DownstreamScheme": "http", "ServiceName": "MyService", "LoadBalancerOptions": {"Type": "RoundRobin"}, "UpstreamPathTemplate": "/ {url}", "UpstreamHttpMethod": ["Get"], "ReRoutesCaseSensitive": false}] "GlobalConfiguration": {/ / Service Discovery configuration "ServiceDiscoveryProvider": {/ / Registry Consul address "Host": "192.168.113.128", / / Registry Consulting Port number "Port": 8500, "Type": "Consul", / / in milliseconds Tell Ocelot how often to call Consul to change the service configuration. "PollingInterval": 100, / / if you have configured key/value on Consul, enter the configuration key here. ConfigurationKey: "MyService_AB"}
The ServiceDiscoveryProvider option description:
Host: registry Consul address.
Port: Port number of the registry consultant.
Type: registry type.
PollingInterval: tells Ocelot how often to call Consul to change the service configuration in milliseconds.
ConfigurationKey: if you have configured key/value on Consul, enter the configuration key here.
4. Project demo 4.1APIGateway project
ConfigureServices add Ocelot, Consul injection:
Services.AddOcelot () .AddConsul ()
Configure is added using Ocelot:
App.UseOcelot () .Wait ()
The service discovery configuration is the same as the Ocelot service discovery project example.
4.2Common project
First install the NuGet package of Consul with the following installation command:
Install-Package Consul
Add an AppExtensions extension class to the project to register instances in Consul for service APIServiceA and APIServiceB projects. In order to show the effect, the specific code is slightly modified as follows:
Public static class AppExtensions {public static IServiceCollection AddConsulConfig (this IServiceCollection services, IConfiguration configuration) {services.AddSingleton (p = > new ConsulClient (consulConfig = > {var address = configuration.GetValue ("Consul:Host"); consulConfig.Address = new Uri (address);}); return services } public static IApplicationBuilder UseConsul (this IApplicationBuilder app, string host = null, string port = null) {/ / get consul client instance var consulClient = app.ApplicationServices.GetRequiredService (); var logger = app.ApplicationServices.GetRequiredService (). CreateLogger ("AppExtensions"); var lifetime = app.ApplicationServices.GetRequiredService (); if (! (app.Properties ["server.Features"] is FeatureCollection features) return app / / var addresses = features.Get (); / / var address = addresses.Addresses.FirstOrDefault (); / / if (address = = null) / / {/ / return app; / /} var address = host + ":" + port; if (string.IsNullOrWhiteSpace (host) | | string.IsNullOrWhiteSpace (port)) {Console.WriteLine ($"host or port is empty!") ; return app;} Console.WriteLine ($"address= {address}"); var uri = new Uri (address); Console.WriteLine ($"host= {uri.Host}, port= {uri.Port}") Var registration = new AgentServiceRegistration () {ID = $"MyService- {uri.Port}", Name = "MyService", Address = $"{uri.Host}", Port = uri.Port, Check = new AgentServiceCheck () {DeregisterCriticalServiceAfter = TimeSpan.FromSeconds (5) / / how long after the service starts, register Interval = TimeSpan.FromSeconds (10), / / Health check interval HTTP = $"{address} / HealthCheck", / / Health check address Timeout = TimeSpan.FromSeconds (5) / / timeout}} Logger.LogInformation ("Registering with Consul"); logger.LogInformation ($"Consul RegistrationID: {registration.ID}"); / / unregister consulClient.Agent.ServiceDeregister (registration.ID) .ConfigureAwait (true); / / register consulClient.Agent.ServiceRegister (registration) .ConfigureAwait (true) / / when the application shuts down, lifetime.ApplicationStopping.Register (() = > {/ / is logging out of logger.LogInformation ("Unregistering from Consul"); consulClient.Agent.ServiceDeregister (registration.ID) .ConfigureAwait (true);}); / / each service needs to provide an interface for health check, which has no business function. When the service is registered, the address of this interface is also told to the registry, and the registry will call the interface regularly to detect whether the service is normal, and if it is abnormal, remove it, so as to ensure the availability of the service. App.Map ("/ HealthCheck", s = > {s.Run (async context = > {await context.Response.WriteAsync ("ok");}); return app;}} 4.3APIServiceA project
Add a Get method to the project, corresponding to the upstream and downstream routing configuration of the APIGateway project. The specific code is as follows:
[Route ("api/ [controller]")] [ApiController] public class ValuesController: ControllerBase {/ / GET api/values [HttpGet] public ActionResult Get () {var port = Request.Host.Port; return new string [] {"value1", "value2", port.Value.ToString ()};}}
Appsettings.json configuration join Consul address:
"Consul": {"Host": "http://192.168.113.128:8500"}4.4APIServiceB Project
Add a Get method to the project, corresponding to the upstream and downstream routing configuration of the APIGateway project. The specific code is as follows:
[Route ("api/ [controller]")] [ApiController] public class ValuesController: ControllerBase {/ / GET api/values [HttpGet] public ActionResult Get () {var port = Request.Host.Port; return new string [] {"value3", "value4", port.Value.ToString ()};}}
Appsettings.json configuration join Consul address:
"Consul": {"Host": "http://192.168.113.128:8500"}4.5 project runs
Add Consul configuration to the ConfigureServices of APIServiceA and APIServiceB projects:
Services.AddConsulConfig (Configuration)
Add Consul service registration at Configure:
APIServiceA:app.UseConsul ("http://172.168.18.73"," 9999 "); APIServiceB:app.UseConsul (" http://172.168.18.73", "9998")
Deploy APIGateway, APIServiceA and APIServiceB projects to IIS:
After the three projects are running, you can see the MyService node service through the browser Consul client:
Click to open the MyService node to see the status of APIServiceA and APIServiceB services registered with Consul:
If you stop the APIServiceB service instance site:
Through the Consul client, you will see that the APIServiceB service instance has been removed:
If you type CTRL+C to shut down one of the Consul services in the cluster, the cluster will re-elect a new leader to handle all service instance queries and transactions:
After reading this, the article "how Asp.Net Core uses Ocelot to achieve service registration and discovery" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it. If you want to know more about the article, you are 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: 274
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.