当前位置:网站首页>Teach you to learn dapr - 4 Service invocation
Teach you to learn dapr - 4 Service invocation
2022-06-26 16:45:00 【Masa technical team】
Introduce
By using a service call , Your application can use standard gRPC or HTTP The protocol is reliable with other applications 、 Communicate safely .
Why not use it directly HttpClientFactory Well
Ask a few questions first :
- How to discover and invoke methods of different services
- How to call other services safely , And apply access control to the method
- How to handle retry and transient errors
- How to use distributed tracking metrics to view call graphs to diagnose problems in production
At this point you will find these things HttpClientFactory I didn't help you finish it , These are essential capabilities in microservices , Next, let's look at what the service call does
How service invocation works
Let's first look at the call sequence between two services

service A To service B To launch a HTTP/gRPC Call to . The call went to the local Dapr sidecar
Dapr Use the name resolution component to discover the service B The location of
Dapr Forward the message to the service B Of Dapr sidecar
notes : Dapr sidecar All calls between are made through gRPC To improve performance . Only services and Dapr sidecar The call between can be HTTP or gRPC
service B Of Dapr sidecar Forward the request to the service B A specific endpoint on the ( Or method ) . service B Then run its business logic code
service B Send a response to the service A. The response will go to the service B Of Dapr sidecar
Dapr Forward the response to the service A Of Dapr sidecar
service A Receiving response
Namespace scope
By default , Other services calling the same namespace can directly use AppID( The assumption is :nodeapp)
localhost:3500/v1.0/invoke/nodeapp/method/neworderService invocation also supports cross namespace invocation , On all supported hosting platforms ,Dapr AppID follow FQDN Format , This includes the target namespace .
FQDN:(Fully Qualified Domain Name) Fully qualified domain name : Name with both host name and domain name .( By means of symbols “.”)
for example : The host name is bigserver, Domain name is mycompany.com, that FQDN Namely bigserver.mycompany.com
** notes :**FQDN Through the symbol . To splice domain names , That explains AppID Why not use symbols ., If you don't remember here , There should be many friends who will step on the pit
such as .net Developers are used to using A.B.C To name the project , but AppID Need to put . Switch to - And all words should also be lowercase (a-b-c), It is suggested to turn it into an agreement to abide by
For example, call namespace :production,AppID:nodeapp
localhost:3500/v1.0/invoke/nodeapp.production/method/neworderThis is in K8s Cross namespace calls in clusters are particularly useful
Inter service security
Through mutual on the hosting platform (mTLS) Authentication , Including passage Dapr Sentry Automatic certificate transfer for services , To ensure that Dapr Security for all calls between applications . The following figure shows a self managed application .
Access control
Applications can control which other applications can call them , And what they are authorized to do through access policies . This enables you to restrict sensitive applications with personal information from being accessed by unauthorized applications , And combine service to service secure communication , Provides soft multi tenant deployment .
Specific access control will be introduced in subsequent chapters
retry
In case of call failure and transient error , Service call execution auto retry , And execute... Within the fallback period .
** notes :** Automatic retry , On by default , You can turn it off . But if it's not related and the business doesn't support idempotence, it's dangerous . It is suggested that the service interface should be designed to support idempotent , This is also a standard choice in microservices .
The errors causing the retry are :
Network error , Including endpoint unavailability and connection rejection .
Due to calling / The called Dapr sidecars Authentication error caused by updating certificate on .
The fallback interval for each call retry is 1 second , At most 3 Time . adopt gRPC And target Sidecar The timeout for the connection is 5 second
Pluggable service discovery
Dapr Can run on a variety of managed platforms . To enable service discovery and service invocation ,Dapr Use pluggable name resolution components . for example ,K8s The name resolution component uses K8s DNS Service to resolve the location of other applications running in the cluster . Self managed machines can use mDNS Name resolution component . Consul The name resolution component can be used in any managed environment , Include K8s Or self managed environment
Focus on , Self managed machines use mDNS, In the development environment, the following articles will recommend VS Seamless development experience on , Is based on mDNS Of
But it has a little problem , We have solved . You just need to develop a console program , be based on Minimal API happy F5 That's all right.
The suggestion is not understood yet Minimal API My little partner can study it , It's delicious
Use mDNS Perform polling load balancing
A picture is worth a thousand words , Just use mDNS Call in turn

Observability tracking and indicators
By default , All calls between applications are tracked , And collect indicators , To provide application insight and diagnostics , This is particularly important in production scenarios . This provides you with call graphs and metrics for calls between services .
The service call API and gRPC agent
pythonapp adopt Dapr sidecar call nodeapp, Through service invocation API And gRPC The proxy is still the calling process seen above , It has nothing to do with language

Use HTTP Call the service
establish Assignment.Server
establish ASP.NET Core empty project , And modify it launchSettings.json, Let's start HTTP The boot port of becomes 5000
profiles.Assignment.Server.applicationUrl To change the value of "https://localhost:6000;http://localhost:5000"
modify Program.cs file
var builder = WebApplication.CreateBuilder(args);var app = builder.Build();app.MapPost("/", () => Console.WriteLine("Hello!"));app.MapGet("/Hello1", () =>{ Console.WriteLine("Hello World1!"); return $"\"Hello World1!\"";});app.MapPost("/Hello2", () => Console.WriteLine("Hello World2!"));app.Map("/Hello3", () => Console.WriteLine("Hello World3!"));app.Run();There is a total of 4 A service
/ :Post Method , Print Hello!
/Hello1:Get Method , Print Hello World1!, return Hello World1!
** notes :** The returned type is Json character string , convenient SDK Deserialization
/Hello2:Post Method , Print Hello World2!
/Hello3: No suffix means that all methods are adapted , Print Hello World3!
First use Dapr CLI So let's verify that
function Assignment.Server: In the catalog dapr-study-room\Assignment04\Assignment.Server Open the command line tool , And execute the following command
dapr run --app-id assignment-server --app-port 5000 dotnet watchCareful friends should find that it is a little different from the command in the previous article ,dontet run Turned into dotnet watch, This turns on the thermal overload , Convenient debugging
Call the service : Open a new command line tool , And execute the following command
dapr invoke --app-id assignment-server --method /dapr invoke --app-id assignment-server --method Hello1dapr invoke --app-id assignment-server --method Hello2dapr invoke --app-id assignment-server --method Hello3 You can find 4 All commands were called successfully , however Assignment.Server The output is a little unexpected
== APP == Hello!== APP == Hello World2!== APP == Hello World3! Yes , No, Hello World1!, Then what shall I do? ? We put Hello1 Change your order
dapr invoke --app-id assignment-server --method Hello1 --verb GETinvoke The output of the call is except App invoked successfully There is another line besides Hello World1!
meanwhile Assignment.Server Your output is correct
== APP == Hello World1! besides invoke There are also some parameters , such as --data,--data-file, Like to study Dapr CLI My little partner can continue to try . But in general SDK That's all right.
establish Assignment.Client
HTTP The service call
establish Console Application project , Use NuGet Package manager add Dapr.Client SDK, And modify it Program.cs file
using Dapr.Client;var appId = "assignment-server";var client = new DaprClientBuilder().Build();await client.InvokeMethodAsync(appId, "/");var resp = await client.InvokeMethodAsync<string>(HttpMethod.Get, appId, "Hello1");Console.WriteLine($"Hello1 Response: {resp}");await client.InvokeMethodAsync(appId, "Hello2");await client.InvokeMethodAsync(appId, "Hello3");Look at a few details
DaprClient It's from
DaprClinetBuilderBuild Coming outThere is another way to use DaprClient, adopt DI
First of all, you need to add
Dapr.AspNetCoreNuGet packageThen there began to be branches , If it was before Web API It can be done in Startup.cs file
ConfigureServicesMethod to add a line of codeservices.AddControllers().AddDapr();If you use Minimal API The default is No Controllers Of , That can be in
var builder = WebApplication.CreateBuilder(args);Then add a line of codebuilder.Services.AddDaprClient();Successfully injected , stay
Constructorsperhaps[FromServices]Have fun in theHttpMethod.Post I didn't specify , The default is Post
HttpMethod.Get When , The return value will be automatically used Json Deserialization
Don't like Json? Can pass DaprClient.CreateInvokeHttpClient structure HttpClient, Smart, you must know what to do later
notes :
1. Minimal API Though fragrant , But new , So not all functions support , For example, directly mapping state management from parameters , Have to wait Minimal API Support Model Binder Later and SDK Only when synchronization is supported 2. DaprClient yes TCP Of , It's also thread safe , You can reuse it boldly , If not DI You don't need to build frequently DaprClientVerification call succeeded
Open the directory using the command line tool dapr-study-room\Assignment04\Assignment.Client, And then execute the command
dotnet runIf you don't use VS Code Terminal PowerShell perform dapr run You may encounter the following errors
Even if you don't encounter it, it is recommended to learn how to support non default ports
An exception occurred while invoking method: '/' on app-id: 'assignment-server' ---> System.Net.Http.HttpRequestException: Because the target computer actively refuses , Unable to connect . (127.0.0.1:3500) ---> System.Net.Sockets.SocketException (10061): Because the target computer actively refuses , Unable to connect .Because it uses dapr run There was no designation of dapr http port, And default client What I visited was 3500 port
There are two solutions :
modify
Assignment.ServerLaunch parameters , increase--dapr-http-port 3500, This method does not cure the symptoms , Because we may start multiple services in the futuredapr run --app-id assignment-server --app-port 5000 --dapr-http-port 3500 dotnet watchmodify
Assignment.ClientEnvironment variables ofFirst, execute
dapr listCheck the port , Take the following as an example ,HTTP PORT yes51460APP ID HTTP PORT GRPC PORT APP PORT COMMAND AGE CREATED PID
assignment-server 51460 51461 5000 dotnet watch 7s 2021-10-29 14:13.49 11676
modify
Assignment.ClientStart parameter of , Pay attention to the51460Change to your own port , UsePowerShellExecute the following command$Env:DAPR_HTTP_PORT = 51460dotnet run
Execute it again dotnet run You can see the correct output
Hello1 Response: Hello World1!gRPC The service call
It's too long , Draw inferences from one instance . It's called InvokeMethodGrpcAsync, then dapr-http-port Switch to dapr-grpc-port,DAPR_HTTP_PORT Switch to DAPR_GRPC_PORT
View tracking
Remember dapr init When docker There is a zipkin Well , adopt zipkin You can take a look at the call trace , Open the following address through the browser
The page is empty

Follow the steps to see

Just click on the end of a line of data SHOW, You can see the call details

Source code of this chapter
Assignment04
https://github.com/doddgu/dapr-study-room
We are acting , New framework 、 New ecology
Our goal is The freedom of the 、 Easy-to-use 、 Highly malleable 、 functional 、 Robust .
So we learn from Building blocks Design concept of , Working on a new framework MASA Framework, What are its characteristics ?
- Native support Dapr, And allow Dapr Replace with traditional means of communication
- Unlimited architecture , Single application 、SOA、 Micro services support
- Support .Net Native framework , Reduce the burden of learning , In addition to the concepts that must be introduced in a specific field , Insist on not making new wheels
- Rich ecological support , In addition to the framework, there are component libraries 、 Authority Center 、 Configuration center 、 Troubleshooting center 、 A series of products such as Alarm Center
- Unit test coverage of the core code base 90%+
- Open source 、 free 、 Community driven
- What is the ? We are waiting for you , Come together and discuss
After several months of production project practice , Completed POC, At present, the previous accumulation is being refactored into new open source projects
At present, the source code has been synchronized to Github( The document site is under planning , Will gradually improve ):
QQ Group :7424099
Wechat group : Plus technology operation wechat (MasaStackTechOps), Remarks , Invite in

Reprinted from :( guiguzi )
边栏推荐
- Interpretation of cloud native microservice technology trend
- 108. simple chat room 11: realize client group chat
- Memory partition model
- [matlab project practice] prediction of remaining service life of lithium ion battery based on convolutional neural network and bidirectional long short time (cnn-lstm) fusion
- Arduino uno + DS1302 simple time acquisition and serial port printing
- Structure the graduation project of actual combat camp
- Cloud platform monitoring system based on stm32+ Huawei cloud IOT design
- Make up the weakness - Open Source im project openim about initialization / login / friend interface document introduction
- Redis 概述整理
- Least squares system identification class II: recursive least squares
猜你喜欢

Qt 5.9.8 安装教程

When a programmer is disturbed 10 times a day, the consequences are amazing!

How to implement interface current limiting?

探讨:下一代稳定币

我把它当副业月入3万多,新手月入过万的干货分享!

用Attention和微调BERT进行自然语言推断-PyTorch

Knowing these commands allows you to master shell's own tools

I regard it as a dry product with a monthly income of more than 30000 yuan for sidelines and more than 10000 yuan for novices!
![[matlab project practice] prediction of remaining service life of lithium ion battery based on convolutional neural network and bidirectional long short time (cnn-lstm) fusion](/img/a6/6d3914360ffe4732db0dbd2aaf1994.png)
[matlab project practice] prediction of remaining service life of lithium ion battery based on convolutional neural network and bidirectional long short time (cnn-lstm) fusion

【MATLAB项目实战】基于卷积神经网络与双向长短时(CNN-LSTM)融合的锂离子电池剩余使用寿命预测
随机推荐
What is the preferential account opening policy of securities companies now? Is it safe to open an account online now?
JS教程之 使用 Electron.JS 构建原生桌面应用程序乒乓游戏
Scala 基础 (二):变量和数据类型
Data analysis - numpy quick start
[机缘参悟-31]:鬼谷子-抵巇[xī]篇-危机是危险与机会并存
5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?
MS|谢黎炜组发现混合益生菌制剂及其代谢产物可缓解结肠炎
Set up your own website (16)
知道这几个命令让你掌握Shell自带工具
C语言所有知识点小结
Multiply the values of the upper triangular elements of the array by M
Calculate the average of N numbers in the index group of X, and return the number that is less than the average and closest to the average through formal parameters
Failed to upload hyperf framework using alicloud OSS
When a programmer is disturbed 10 times a day, the consequences are amazing!
【207】Apache崩溃的几个很可能的原因,apache崩溃几个
Supplement the short board - Open Source im project openim about initialization / login / friend interface document introduction
100+ data science interview questions and answers Summary - basic knowledge and data analysis
我把它当副业月入3万多,新手月入过万的干货分享!
并发编程整体脉络
Science | 红树林中发现的巨型细菌挑战传统无核膜观念