MICROSERVICE - Dev Mentor - Consul + Fabio

Setup rabbitmq using Docker 

[root@szsit148 ~]# docker run --name rabbitmq -d -p 5672:5672 -p 15672:15672 --h ostname rabbitmq rabbitmq:3-management

[root@szsit148 ~]# docker ps

CONTAINER ID IMAGE                           COMMAND                  CREATED     STATUS       PORTS                                                                                                                                       NAMES
8b27776fa3eb rabbitmq:3-management "docker-entrypoint.s…" 11 hours ago Up 11 hours 4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp, 15671/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp rabbitmq

[root@szsit148 ~]# docker rm rabbitmq -f

Setup rabbitmq, redis, using Docker Compose

[root@szsit148 ~]# docker-compose -f mongo-rabbit-redis.yml up -d

version: "3.5"services:mongo:image: mongo:4container_name: mongoports:- 27017:27017networks:- dshop# network_mode: hostvolumes:- mongo:/data/dbrabbitmq:image: rabbitmq:3-managementcontainer_name: rabbitmqports:- 5672:5672- 15672:15672networks:- dshop# network_mode: hostvolumes: - rabbitmq:/var/lib/rabbitmqredis:image: rediscontainer_name: redisports:- 6379:6379networks:- dshop# network_mode: hostvolumes: - redis:/datanetworks:dshop:name: dshop-networkvolumes:mongo:driver: localrabbitmq:driver: localredis:driver: local
mango-rabbit-redis

 [root@szsit148 compose]# docker inspect dshop-network

[
{
"Name": "dshop-network",
"Id": "1545e967cc479ed40e859c1b82a8477b6ff90ccd7ff868b91c2788f9e15e2ae2",
"Created": "2019-01-29T08:38:48.739641213+08:00",
"Scope": "local",
"Driver": "bridge",
"EnableIPv6": false,
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.18.0.0/16",
"Gateway": "172.18.0.1"
}
]
},
"Internal": false,
"Attachable": true,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"7cdfdf302de6c7fea656670e3076f1b36309791409ff2f9db510013630897068": {
"Name": "mongo",
"EndpointID": "5cc3bb708e274be58d2fb2450aa1a6054848d89738e653d62f90cc1bdeffca58",
"MacAddress": "02:42:ac:12:00:04",
"IPv4Address": "172.18.0.4/16",
"IPv6Address": ""
},
"9a66c04a4171791121bfb319d5f3dbaef8c326e89a1384239d485bc72b93364b": {
"Name": "redis",
"EndpointID": "4ab30409c9a3b786dd566cc424b4257edc5664a2383e4ed768ba51afeed14e84",
"MacAddress": "02:42:ac:12:00:02",
"IPv4Address": "172.18.0.2/16",
"IPv6Address": ""
},
"c2f328b8896ac1c53701dfc15b1f563e63bd3818dedfb87ad03bc95eb14e238e": {
"Name": "rabbitmq",
"EndpointID": "103ce313867ac5069f7416ba713879329fead30233ebed39005c355402acb769",
"MacAddress": "02:42:ac:12:00:03",
"IPv4Address": "172.18.0.3/16",
"IPv6Address": ""
}
},
"Options": {},
"Labels": {
"com.docker.compose.network": "dshop-network",
"com.docker.compose.project": "compose",
"com.docker.compose.version": "1.22.0-rc1"
}
}
View Result

Start all applicaiton up using start-all.sh

#!/bin/bash
export ASPNETCORE_ENVIRONMENT=local
DOTNET_RUN=./scripts/dotnet-run.sh
PREFIX=DNC-DShop
SERVICE=$PREFIX.Services
REPOSITORIES=($PREFIX.Api $SERVICE.Customers $SERVICE.Identity $SERVICE.Operations $SERVICE.Orders $SERVICE.Products $SERVICE.Signalr)for REPOSITORY in ${REPOSITORIES[*]}
doecho ========================================================echo Starting a service: $REPOSITORYecho ========================================================cd $REPOSITORY$DOTNET_RUN &cd ..
done
Use git bash to run

 

 MangoDB tool

 

 

Conditional Resolving multiple implementation from generic interface base on types

articles

Dependency injection is applied where there is only one implementation to the interface, DI via constructor is mostly seen.

but if a interface has multiple implementation, resolving the right one can be done in runtime and determined by the paramterized type variables

 

   public IServiceProvider ConfigureServices(IServiceCollection services){services.Configure<CookiePolicyOptions>(options =>{// This lambda determines whether user consent for non-essential cookies is needed for a given request.options.CheckConsentNeeded = context => true;options.MinimumSameSitePolicy = SameSiteMode.None;});services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);var builder = new ContainerBuilder();builder.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).AsImplementedInterfaces();builder.Populate(services);Container = builder.Build();return new AutofacServiceProvider(Container);}
Use Autofac as DI framework at startup.cs
[HttpPost]public IActionResult GetAll([FromBody] GetAllQuery query){var handleType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(List<DemoModel>));dynamic QueryHandler = _context.Resolve(handleType);return new JsonResult(QueryHandler.execute((dynamic)query));}namespace DynamicDI.Query
{public interface IQuery<TResult>{}
}namespace DynamicDI.Query
{public class GetAllQuery : IQuery<List<DemoModel>> {public int Id { get; set; }}
}namespace DynamicDI.QueryHandler
{interface IQueryHandler<IQuery, TResult>{TResult execute(IQuery query);}
}namespace DynamicDI.QueryHandler
{public class GetAllQueryHandler : IQueryHandler<GetAllQuery, List<DemoModel>>{public GetAllQueryHandler(){//Here you can put repository implmentation at the constructor
        }public List<DemoModel> execute(GetAllQuery query){//repo.getallreturn new List<DemoModel>{new DemoModel{Id=0, Name="Matt"},new DemoModel{Id=1, Name="Yang"}};}}
}
View Code

 Spin up docker compose for Consul, 

[root@szsit148 ~]# docker-compose -f consul-fabio-vault.yml up -d

version: "3.5"services:consul:image: consulcontainer_name: consulports:- 6500:6500networks:- dshop# network_mode: hostvolumes:- consul:/consul/datafabio:image: fabiolb/fabiocontainer_name: fabioenvironment:- FABIO_REGISTRY_CONSUL_ADDR=consul:6500networks:- dshop# network_mode: hostports:- 9998:9998- 9999:9999vault:image: vaultcontainer_name: vaultports:- 8200:8200networks:- dshop# network_mode: hostenvironment:- VAULT_ADDR=http://127.0.0.1:8200
      - VAULT_DEV_ROOT_TOKEN_ID=secretcap_add:- IPC_LOCKnetworks:dshop:name: dshop-networkexternal: truevolumes:consul:driver: local
View Code

Access  http://10.89.24.148:8500

Add a common library and create a extension method to take servicecollection and register the consul configuration

Add microsoft.extensions.dependencyinjection and configuration

microsoft.extensions.dependencyinjection is the namespace for IServiceCollection 

Add 3 import type to transcient service

  • ConsulClient - component of Consul Library provided by Nuget, responsible for sending request to consul and getting the service info in return
  • ConsulServiceRegistry - which takes the ConsulClient at constructor and leverage it to get the AgentService(Consul type) which has the service name and its host name and port
  • ConsultHttpClient - a wrapper class of HttpClient that aggregate ConsulServiceRegistry via ConsulServiceDiscoveryMessageHandler

Service A register to Consul

client.Agent.ServiceRegister(new AgentServiceRegistration{servicename="ServiceA"});

using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;namespace Common.Consul
{public static class ConsulExtensions{public static IServiceCollection AddConsul(this IServiceCollection services){IConfiguration configuration;using (var servicebuilder = services.BuildServiceProvider()){configuration = servicebuilder.GetService<IConfiguration>();}var options = new ConsulOptions();configuration.GetSection("Consul").Bind(options);services.Configure<ConsulOptions>(configuration.GetSection("consul"));services.AddTransient<IConsulServicesRegistry, ConsulServiceRegistry>();services.AddTransient<ConsulServiceDiscoveryMessageHandler>();services.AddHttpClient<IConsulHttpClient, ConsulHttpClient>().AddHttpMessageHandler<ConsulServiceDiscoveryMessageHandler>();return services.AddSingleton<IConsulClient>(c =>new ConsulClient(cfg => cfg.Address = new System.Uri(options.url)));}public static string UseConsul(this IApplicationBuilder app){using (var scope = app.ApplicationServices.CreateScope()){var consulOptions = scope.ServiceProvider.GetService<IOptions<ConsulOptions>>();// var fabioOptions = scope.ServiceProvider.GetService<IOptions<FabioOptions>>();var enabled = consulOptions.Value.enabled;var consulEnabled = Environment.GetEnvironmentVariable("CONSUL_ENABLED")?.ToLowerInvariant();if (!string.IsNullOrWhiteSpace(consulEnabled)){enabled = consulEnabled == "true" || consulEnabled == "1";}if (!enabled){return string.Empty;}var address = consulOptions.Value.address;if (string.IsNullOrWhiteSpace(address)){throw new ArgumentException("Consul address can not be empty.",nameof(consulOptions.Value.pingEndpoint));}var uniqueId = Guid.NewGuid();var client = scope.ServiceProvider.GetService<IConsulClient>();var serviceName = consulOptions.Value.service;var serviceId = $"{serviceName}:{uniqueId}";var port = consulOptions.Value.port;var pingEndpoint = consulOptions.Value.pingEndpoint;var pingInterval = consulOptions.Value.pingInterval <= 0 ? 5 : consulOptions.Value.pingInterval;var removeAfterInterval =consulOptions.Value.removeAfterInterval <= 0 ? 10 : consulOptions.Value.removeAfterInterval;var registration = new AgentServiceRegistration{Name = serviceName,ID = serviceId,Address = address,Port = port,Tags = null//Tags = fabioOptions.Value.Enabled ? GetFabioTags(serviceName, fabioOptions.Value.Service) : null
                };if (consulOptions.Value.pingEnabled )//|| fabioOptions.Value.Enabled)
                {var scheme = address.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)? string.Empty: "http://";var check = new AgentServiceCheck{Interval = TimeSpan.FromSeconds(pingInterval),DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(removeAfterInterval),HTTP = $"{scheme}{address}{(port > 0 ? $":{port}" : string.Empty)}/{pingEndpoint}"};registration.Checks = new[] { check };}client.Agent.ServiceRegister(registration);return serviceId;}}}
}
ConsulExtension

 

Service B user service discovery

only aware the SERVICE NAME for Service A and reach out to Consul to resolve the name into host name and forward the rquest to the Service A 

 Unregister consul when applicaiton exit

applicationLifetime.ApplicationStopped.Register(() =>
{
client.Agent.ServiceDeregister(consulServiceId);
// Container.Dispose();
});

Add config section consul

{"consul": {"enabled": true,"url": "http://localhost:8500","service": "conditionalinjection-service","address": "localhost","port": "5000","pingEnabled": true,"pingEndpoint": "ping","pingInterval": 5,"removeAfterInterval": 10,"requestRetries": 3},"Logging": {"LogLevel": {"Default": "Warning"}},"AllowedHosts": "*"
}

 Fabio LoadBalancing 

Fabio's unqiueness is unlike Nginx which needs to manually set up the reseverse proxied ip address.

Fabio pair with Consul to provide service. Consul does not provide LB features

Fabio collect the ipaddress from Consul where IP are binded during runtime. and re-route the traffice to registered instance address

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1174502.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于深度学习的杂草检测系统(YOLOv10+YOLO数据集+UI界面+Python项目+模型)

一、项目介绍 本项目使用YOLO&#xff08;You Only Look Once&#xff09;目标检测算法进行特定杂草的自动识别&#xff0c;目标是通过计算机视觉技术识别并定位农田中的“0 ridderzuring”杂草&#xff0c;从而帮助农业自动化管理。杂草的及时识别与处理对于提高农业生产效率、…

DEV TEST- Test Driven Development (Integration Test)

DEV TEST- Test Driven Development (Integration Test)Tdd is about showing external observable behavior, it is a design tool and rely on your test to dictate how your structure your code.[TestMethod]pu…

dify/coze/n8n 智能体开发避坑指南

点赞、关注、收藏&#xff0c;不迷路 智能体&#xff08;AI Agent&#xff09;开发中&#xff0c;Dify&#xff08;专注可视化 LLM 应用搭建&#xff09;、Coze&#xff08;字节智能体开发平台&#xff09;、N8N&#xff08;开源自动化工作流工具&#xff09;是新手入门的核心工…

DEV TEST- Test Driven Development (Integration Test)

DEV TEST- Test Driven Development (Integration Test)Tdd is about showing external observable behavior, it is a design tool and rely on your test to dictate how your structure your code.[TestMethod]pu…

基于深度学习的昆虫识别检测系统(YOLOv10+YOLO数据集+UI界面+Python项目+模型)

一、项目介绍 本系统基于YOLOv10模型&#xff0c;专门设计用于检测和识别10类常见的农业害虫。这些害虫包括&#xff1a;army worm&#xff08;粘虫&#xff09;、legume blister beetle&#xff08;豆芫菁&#xff09;、red spider&#xff08;红蜘蛛&#xff09;、rice gall …

DEV TEST - Full stack Bootstrap and ASP.NET MVC - Testing

DEV TEST - Full stack Bootstrap and ASP.NET MVC - Testing,General topic : https://www.cnblogs.com/Mattcoder/p/8878481.html Unit Test Integration Test - NetCoreIntegration Test - Net4.5 Unit Test at al…

DEV TEST - Full stack Bootstrap and ASP.NET MVC - Testing

DEV TEST - Full stack Bootstrap and ASP.NET MVC - Testing,General topic : https://www.cnblogs.com/Mattcoder/p/8878481.html Unit Test Integration Test - NetCoreIntegration Test - Net4.5 Unit Test at al…

基于深度学习的鸡检测系统(YOLOv10+YOLO数据集+UI界面+Python项目+模型)

一、项目介绍 本研究开发了一种基于YOLOv10的鸡检测和跟踪系统&#xff0c;专注于检测单一类别&#xff1a;rooster&#xff08;鸡&#xff09;。该系统旨在实现对鸡的实时检测和跟踪&#xff0c;适用于养殖场管理、行为研究等场景。YOLOv10作为一种高效的目标检测模型&#xf…

VIRTUALIZATION - Kubernates - Azure Kubernetes Service

VIRTUALIZATION - Kubernates - Azure Kubernetes Service retag the image to make it azure friendly

WEB - AngularJS and Typescript

WEB - AngularJS and TypescriptSource code https://github.com/mattcoder2017/CoreTypescript/tree/master/WebApplication1 AngularIO: https://angular.io/ Nodejs vs angular compatiblity matrix https://angul…

基于深度学习的香蕉成熟度识别检测系统(YOLOv10+YOLO数据集+UI界面+Python项目源码+模型)

一、项目介绍 本文介绍了基于YOLOv10的香蕉成熟度检测系统&#xff0c;旨在通过计算机视觉技术自动识别和分类香蕉的成熟度。该系统能够准确区分六种不同的成熟度类别&#xff1a;新鲜成熟&#xff08;freshripe&#xff09;、新鲜未成熟&#xff08;freshunripe&#xff09;、…

基于深度学习的疲劳驾驶检测系统(YOLOv10+YOLO数据集+UI界面+Python项目+模型)

一、项目介绍 本项目旨在开发一个基于YOLOv10的疲劳检测系统&#xff0c;用于实时检测驾驶员的疲劳状态。系统通过分析驾驶员的面部表情&#xff0c;特别是眼睛和嘴巴的状态&#xff0c;来判断其是否处于疲劳状态。模型共分为四类&#xff1a;打哈欠&#xff08;Yawn&#xff0…

强烈安利!自考必看TOP8一键生成论文工具测评

强烈安利&#xff01;自考必看TOP8一键生成论文工具测评 2026年自考论文工具测评&#xff1a;为何需要一份权威榜单&#xff1f; 随着自考人数逐年增加&#xff0c;论文写作成为众多考生必须面对的难题。从选题构思到文献整理&#xff0c;再到格式规范和内容润色&#xff0c;每…

基于深度学习的生菜周期检测系统(YOLOv10+YOLO数据集+UI界面+Python+模型)

一、项目介绍 YOLOv10生菜生长周期检测系统 是一个基于YOLOv10&#xff08;You Only Look Once version 10&#xff09;目标检测算法的智能系统&#xff0c;专门用于检测和分类生菜在不同生长阶段的生长状态。该系统能够自动识别生菜的生长周期&#xff0c;并将其分类为五个不…

西门子200Smart加Smart 1000 IE水处理程序画面案例。 采用成熟、可靠、先进、...

西门子200Smart加Smart 1000 IE水处理程序画面案例。 采用成熟、可靠、先进、自动化程度高的反渗透精混床除盐水处理工艺&#xff0c;确保处理后的超纯水水质确保处理后出水电阻率达到18.2MΩ.cm, 高纯水制取设备关键设备及耗材采用国际主流先进可靠产品&#xff0c;采用PLC触摸…

震惊!这家浙江头部AI科技公司,竟然藏着这样的秘密!

震惊&#xff01;这家浙江头部AI科技公司&#xff0c;竟然藏着这样的秘密&#xff01;当前行业内对AI技术的认知多聚焦于技术迭代&#xff0c;却鲜少关注落地环节的“适配成本”问题。尤其在中小微企业中&#xff0c;这一痛点尤为突出。许多企业在推进AI转型时&#xff0c;常常…

计算机毕业设计 java 疫苗预约系统 基于 Java 的智能疫苗接种预约管理平台 Java 疫苗接种全流程管理系统

计算机毕业设计 java 疫苗预约系统 9&#xff08;配套有源码 程序 mysql 数据库 论文&#xff09;本套源码可以先看具体功能演示视频领取&#xff0c;文末有联 xi 可分享随着网络科技的飞速发展和人们健康意识的提升&#xff0c;疫苗预约需求日益增长&#xff0c;传统线下预约模…

PERFORMANCE TEST - WebPerf Test

PERFORMANCE TEST - WebPerf TestNo web browser Organize your test early on -could be base on user stories Small granularity so you know what is slowAdding Validatation Rule All have LEVEL to indicate im…

震惊!浙江这家头部AI公司光景泽创,究竟藏着啥秘密?

震惊&#xff01;浙江这家头部AI公司光景泽创&#xff0c;究竟藏着啥秘密&#xff1f;当多数AI企业还在卷技术参数时&#xff0c;浙江光景泽创科技公司&#xff08;以下简称“光景泽创”&#xff09;却用一组数据刺痛了行业神经&#xff1a;服务企业超500家&#xff0c;帮助广州…

震惊!浙江这家AI科技头部公司光景泽创,究竟有何过人之处?

跨境生意的“效率革命”&#xff1a;解码光景泽创的AI破局之道当前跨境电商行业正陷入一场“效率焦虑”——多语言素材人工翻译成本高、海外直播时区适配难、客户咨询响应慢导致流失率超30%&#xff0c;这些隐性痛点正在吞噬企业的利润空间。浙江光景泽创科技有限公司&#xff…