Table of Contents
Source code analysis
运行部署
困惑
写在最后
Home Backend Development C#.Net Tutorial Catalog Service - Analysis of Microsoft microservice architecture example code

Catalog Service - Analysis of Microsoft microservice architecture example code

May 29, 2018 pm 03:31 PM
service Microsoft Serve parse

We talked about Identity Service in the previous article. Because it is developed based on IdentityServer4, there are not many knowledge points. Today we will take a look at Catalog Service. In the future explanations, we will focus on different and key points. I hope everyone understands. .

Source code analysis

Let’s first look at its directory structure, a very standard webapi directory:

Catalog Service - Analysis of Microsoft microservice architecture example code

First look at Program, followed by IdentityService is similar, with the addition of UseWebRoot ("Pics"). The pics directory is set to webroot, and everything else is the same.

In the construction method of Startup, we also saw the use of the secret manager tool, but there is one more parameter. Here we see the Assembly type. In fact, the secret only needs the userSecretsId.

In ConfigureServices, we see the following code:

services.AddMvc(options =>
{
	options.Filters.Add(typeof(HttpGlobalExceptionFilter));
}).AddControllersAsServices();
Copy after login

Added a filter. This HTtpGlobalExceptionFilter can be found in the project. The general meaning is that when an error of CatalogDomainException type is thrown, Returns a specific error code.

AddControllersAsServices This extension method registers all the Controllers in the project into Services. Let’s take a look at the source code:

        public static IMvcCoreBuilder AddControllersAsServices(this IMvcCoreBuilder builder)
        {
            var feature = new ControllerFeature();
            builder.PartManager.PopulateFeature(feature);foreach (var controller in feature.Controllers.Select(c => c.AsType()))
            {
                builder.Services.TryAddTransient(controller, controller);
            }

            builder.Services.Replace(ServiceDescriptor.Transient<icontrolleractivator>());return builder;
        }</icontrolleractivator>
Copy after login

The foreach section in the middle is, so that we can use dependency injection in the project to You can easily access each controller.

Going down:

            services.AddDbContext<catalogcontext>(options =>
            {
                options.UseSqlServer(Configuration["ConnectionString"],
                                     sqlServerOptionsAction: sqlOptions =>
                                     {
                                         sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);                                         //Configuring Connection Resiliency:   sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                                     });// Changing default behavior when client evaluation occurs to throw. // Default in EF Core would be to log a warning when client evaluation is performed.options.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));//Check Client vs. Server evaluation: });</catalogcontext>
Copy after login

When configuring DBContext, the Connection Resiliency (bounce connection) method is used here, and you can see when using migration , it uses MigrationsAssembly(AssemblyName). This method is somewhat similar to the FluentNhibernate I talked about before. EnableRetryOnFailure sets the failed attempt mechanism of this Action. If a Failure is encountered during Migration, it will automatically retry. This method avoids The impact of occasional connection failures caused by separation of app and database. Why is there this mechanism? Because when our database is in the cloud, such as Azure SQL, network connection problems will inevitably occur. Even if we put the app and database in a data center, I believe there will occasionally be this problem. We can now configure , so that if it encounters a failure, it will restart the operation, which avoids occasional problems caused by the network to a certain extent. You can also set some policies to enable retries when running commands. By default, EF only records warnings in client evaluation. We can make it throw this warning through ConfigureWarnings, and you can also configure it to ignore it.

Next we see the following code:

services.Configure<catalogsettings>(Configuration);</catalogsettings>
Copy after login

We can find similar statements in each eShop project. It will register some project-related Settings into services, so that It becomes an environment variable and we can configure it through setting.json. In addition to configuration through setting.json, we can also perform flexible configuration through Docker run –e.

Here our CatalogSetting contains an ExternalCatalogBaseUrl attribute. We can enter the following command when docker run:

docke run -e "ExternalCatalogBaseUrl=http://localhost:5011/" ....
Copy after login

This way we can flexibly configure it through the docker command, which is very convenient. You can also use -e to assign values ​​to variables in our setting.json, such as ConnectionString. You can click to learn more about it.

            // Add framework services.services.AddSwaggerGen();
            services.ConfigureSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SingleApiVersion(new Swashbuckle.Swagger.Model.Info()
                {
                    Title = "eShopOnContainers - Catalog HTTP API",
                    Version = "v1",
                    Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample",
                    TermsOfService = "Terms Of Service"
                });
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
Copy after login

The above two pieces of code are configured with SwaggerGen and Cors (cross-domain) strategies respectively. SwaggenGen is a very practical framework that can automatically convert our api to web mode and present it in front of us. Very useful for debugging. The configuration of Cors is not used well here. It allows all requests. It is recommended to follow the actual needs, otherwise there is no meaning in cross-domain settings.

Next we saw a series of add service operations, all related to EventBus. After looking at it for a while, we found that only the log action was done so far. Let’s take a look at the code:

if (raiseProductPriceChangedEvent) // Save and publish integration event if price has changed{//Create Integration Event to be published through the Event Busvar priceChangedEvent = new ProductPriceChangedIntegrationEvent(catalogItem.Id, productToUpdate.Price, oldPrice);// Achieving atomicity between original Catalog database operation and the IntegrationEventLog thanks to a local transactionawait _catalogIntegrationEventService.SaveEventAndCatalogContextChangesAsync(priceChangedEvent);// Publish through the Event Bus and mark the saved event as publishedawait _catalogIntegrationEventService.PublishThroughEventBusAsync(priceChangedEvent);
}
Copy after login

The above code means that when the price changes, we call EventService to save and record the operation. The PublishThroughEventBusAsync method changes the State of this record to published. At present, I don't know why this method is used, and I don't know why it is named EventBus. However, I have raised this question in the project's issue, and I hope the developers of the project can give me an answer. I have checked Basket.Api. There will be subscription behavior in this project. We will take a closer look at the details in the next chapter.

ok, let’s look at the Configure method again. We can study the following piece of code:

var context = (CatalogContext)app
            .ApplicationServices.GetService(typeof(CatalogContext));

WaitForSqlAvailability(context, loggerFactory);
Copy after login

We see that here it calls the previously registered CatalogContext, and it is not instantiated through new. Instead, the previous registration is obtained through GetService, so that other instances that the context depends on are also brought in, which is very convenient and easy to use.

WaitForSqlAvailability method is to try to make the database available, because it requires data migration later.

CatalogService contains 2 Controllers, one is PicController and the other is CatalogController. PicController only obtains pictures based on ID. CatalogController shows how to use webapi to do CURD.

运行部署

如果你要运行Catalog.Api,你必须安装MSSQL和RabbitMQ,这次我把我的系统换成了Win10 Pro,并在电脑上使用Docker安装了MSSQL-Server-Linux和RabbitMQ。安装这2个非常简单,仅仅需要输入几条命令即可:

docker run --name mssql -e &#39;ACCEPT_EULA=Y&#39; -e &#39;SA_PASSWORD=Pass@word&#39; -p 5433:1433 -d microsoft/mssql-server-linux

docker run -d --hostname my-rabbit --name rabbitmq -p 8080:15672 -p 5672:5672 rabbitmq:3-management
Copy after login

ok,我们使用docker创建了mssql和rabbitmq,这里注意一下,我把mssql的端口映射到了本机的5433上,还有rabbitmq的管理页面,我映射到了本机的8080端口,你可以通过http://localhost:8080 进行访问。

上一篇我们说过我们可以通过iisexpress/Kestrel或者docker的形式运行因为牵涉到配置,所以这两种方式的运行有些不同。

一、iisExpress或Kestrel方式下,因为刚刚我们把mssql和rabbitmq的端口都映射到了本机,所以我们只需要在setting.json中把数据库连接和rabbitmq的地址指向本机即可,如下:

{  "ConnectionString": "Server=tcp:127.0.0.1,5433;Initial Catalog=Microsoft.eShopOnContainers.Services.CatalogDb;User Id=sa;Password=Pass@word",  "ExternalCatalogBaseUrl": "http://localhost:5101",  "EventBusConnection": "localhost",  "Logging": {"IncludeScopes": false,"LogLevel": {      "Default": "Debug",      "System": "Information",      "Microsoft": "Information"}
  }
}
Copy after login

ok,Ctrl+F5,运行一下看看:

Catalog Service - Analysis of Microsoft microservice architecture example code

当看到上面这个页面,说明你的运行正常了,你还得测试下api是否运行正常,比如Pic,比如Items。

二、docker中运行,参照上一篇的方式,先publish再build Catalog Service - Analysis of Microsoft microservice architecture example code, 不过这里要注意一点,因为你之前的ConnectionString和EventBusConnection都是指向本机(127.0.0.1)的,所以这里必须改一下,改成主机的ip地址或者是对应容器的ip也可以,如果您不想更改的话,也可以通过docker -e进行设置,比如:

docker run -p 8899:80 --name catalog -e "EventBusConnection=172.17.0.2" -d catalog:01
Copy after login

我这里的172.17.0.2是我rabbitmq容器的ip地址,你可以通过docker inspect containerId 进行查看容器的ip。

如果一切配置都正确的话,你就可以通过浏览器http://localhost:8899 进行浏览了。

当然,除了正常浏览外,你还需测试下api是否正常。

Catalog Service - Analysis of Microsoft microservice architecture example code

困惑

在这个项目中有一些疑惑,希望大家能够给我答案。

Connection Resiliency,我看了很久,字面意思是弹性连接,但我觉得用弹性好像不太适合,一般来讲我们说的弹性都是指架构或者系统的伸缩性,我一开始也是从这个角度去了解,但看了很多文章,觉得它只是让我们在启动的时候,设置一些重试策略,在后面调用中可使用此策略,策略会根据你设置的重试次数、延迟时间等去自动重试,避免因为偶尔的错误造成的影响,所以觉得用弹回比较恰当。

EventBus,我感觉很奇怪,为什么一定要取这个名字呢?在Android中,很明确的,它是进行订阅发布,消息传递,可以解耦发布者和订阅者,但在Catalog.Api里,变成了记录操作,没有看到解耦,也没有看到订阅。在我的理解中,应该在Startup进行订阅操作,发布者CatalogController在进行update操作的时候,订阅者进行add log动作,但在这个实例中,我看到的是同步进行了这些操作,所以很不解。

Mssql-server-linux,当你用Docker安装了以后,你却不能使用visual studio 2017的sql server data tools进行查询(只能进行连接),为了查看效果,还需要安装Microsoft Sql Server Management Studio(必须17版本以后)进行查看数据。

写在最后

这次的文章来的比较晚,一方面有点忙,另一方面就是上面提到的困惑,面对困惑我试着去解答,但有时候真的无法解答,所以提出来集思广益。

后面可能会比较慢,需要学习的东西真多,一边写一边学习成为这次系列的乐趣,现在每天坚持6公里快走,夜走能够是我保持头脑清晰,思考项目中的疑问,现在发觉生活越发有趣。

或许有很多人觉得只看了Startup就够了吗?其实真不够,我目前先把框架的源码过一遍,后面会分篇讲述,比如Connection Resiliency。

The above is the detailed content of Catalog Service - Analysis of Microsoft microservice architecture example code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
Microsoft releases Win11 August cumulative update: improving security, optimizing lock screen, etc. Microsoft releases Win11 August cumulative update: improving security, optimizing lock screen, etc. Aug 14, 2024 am 10:39 AM

According to news from this site on August 14, during today’s August Patch Tuesday event day, Microsoft released cumulative updates for Windows 11 systems, including the KB5041585 update for 22H2 and 23H2, and the KB5041592 update for 21H2. After the above-mentioned equipment is installed with the August cumulative update, the version number changes attached to this site are as follows: After the installation of the 21H2 equipment, the version number increased to Build22000.314722H2. After the installation of the equipment, the version number increased to Build22621.403723H2. After the installation of the equipment, the version number increased to Build22631.4037. The main contents of the KB5041585 update for Windows 1121H2 are as follows: Improvement: Improved

Microsoft Edge upgrade: Automatic password saving function banned? ! Users were shocked! Microsoft Edge upgrade: Automatic password saving function banned? ! Users were shocked! Apr 19, 2024 am 08:13 AM

News on April 18th: Recently, some users of the Microsoft Edge browser using the Canary channel reported that after upgrading to the latest version, they found that the option to automatically save passwords was disabled. After investigation, it was found that this was a minor adjustment after the browser upgrade, rather than a cancellation of functionality. Before using the Edge browser to access a website, users reported that the browser would pop up a window asking if they wanted to save the login password for the website. After choosing to save, Edge will automatically fill in the saved account number and password the next time you log in, providing users with great convenience. But the latest update resembles a tweak, changing the default settings. Users need to choose to save the password and then manually turn on automatic filling of the saved account and password in the settings.

Microsoft Win11's function of compressing 7z and TAR files has been downgraded from 24H2 to 23H2/22H2 versions Microsoft Win11's function of compressing 7z and TAR files has been downgraded from 24H2 to 23H2/22H2 versions Apr 28, 2024 am 09:19 AM

According to news from this site on April 27, Microsoft released the Windows 11 Build 26100 preview version update to the Canary and Dev channels earlier this month, which is expected to become a candidate RTM version of the Windows 1124H2 update. The main changes in the new version are the file explorer, Copilot integration, editing PNG file metadata, creating TAR and 7z compressed files, etc. @PhantomOfEarth discovered that Microsoft has devolved some functions of the 24H2 version (Germanium) to the 23H2/22H2 (Nickel) version, such as creating TAR and 7z compressed files. As shown in the diagram, Windows 11 will support native creation of TAR

Microsoft's full-screen pop-up urges Windows 10 users to hurry up and upgrade to Windows 11 Microsoft's full-screen pop-up urges Windows 10 users to hurry up and upgrade to Windows 11 Jun 06, 2024 am 11:35 AM

According to news on June 3, Microsoft is actively sending full-screen notifications to all Windows 10 users to encourage them to upgrade to the Windows 11 operating system. This move involves devices whose hardware configurations do not support the new system. Since 2015, Windows 10 has occupied nearly 70% of the market share, firmly establishing its dominance as the Windows operating system. However, the market share far exceeds the 82% market share, and the market share far exceeds that of Windows 11, which will be released in 2021. Although Windows 11 has been launched for nearly three years, its market penetration is still slow. Microsoft has announced that it will terminate technical support for Windows 10 after October 14, 2025 in order to focus more on

Microsoft launches new version of Outlook for Windows: comprehensive upgrade of calendar functions Microsoft launches new version of Outlook for Windows: comprehensive upgrade of calendar functions Apr 27, 2024 pm 03:44 PM

In news on April 27, Microsoft announced that it will soon release a test of a new version of Outlook for Windows client. This update mainly focuses on optimizing the calendar function, aiming to improve users’ work efficiency and further simplify daily workflow. The improvement of the new version of Outlook for Windows client lies in its more powerful calendar management function. Now, users can more easily share personal working time and location information, making meeting planning more efficient. In addition, Outlook has also added user-friendly settings, allowing users to set meetings to automatically end early or start later, providing users with more flexibility, whether they want to change meeting rooms, take a break or enjoy a cup of coffee. arrange. according to

Microsoft plans to phase out NTLM in Windows 11 in the second half of 2024 and fully shift to Kerberos authentication Microsoft plans to phase out NTLM in Windows 11 in the second half of 2024 and fully shift to Kerberos authentication Jun 09, 2024 pm 04:17 PM

In the second half of 2024, the official Microsoft Security Blog published a message in response to the call from the security community. The company plans to eliminate the NTLAN Manager (NTLM) authentication protocol in Windows 11, released in the second half of 2024, to improve security. According to previous explanations, Microsoft has already made similar moves before. On October 12 last year, Microsoft proposed a transition plan in an official press release aimed at phasing out NTLM authentication methods and pushing more enterprises and users to switch to Kerberos. To help enterprises that may be experiencing issues with hardwired applications and services after turning off NTLM authentication, Microsoft provides IAKerb and

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

Microsoft Edge Android version now provides Copilot translation function, and the Windows version is under small-scale testing Microsoft Edge Android version now provides Copilot translation function, and the Windows version is under small-scale testing Apr 27, 2024 am 08:40 AM

According to news from this site on April 26, as we all know, Microsoft is currently trying its best to promote its AI assistant Copilot. In addition to the Copilot that comes with Windows 10/11, the Copilot function is also integrated in the Edge browser and Office. At present, Copilot still has weaknesses compared to AI tools such as GPT, but some of the functions it provides are also very practical for Windows users and Edge users, such as its own translation function. As discovered by @Leopeva64, Microsoft has added this feature to the Android version of the EdgeDev browser and is also testing it for a small number of desktop Edge users. This site points out that C

See all articles