Dapr DotNet5 HTTP 调用
Dapr DotNet5 HTTP 调用
版本介绍
- Dotnet 版本:5.0.100
- Dapr dotnet 版本:0.12.0-preview01
注意: Asp.Net Core 项目中的 launchSettings.json 文件,该文件的中的端口号应和 darp --app-port 端口号相同,否则 dapr 无法正常启动 Asp.Net Core 项目。

工程结构

3 个 .NET 5 项目,ClientA、ServiceB、ServiceC。1 个 .NET Standard 项目,Dtos 。Dtos 用于存储各种传输模型。调用路径如下图所示。新建两个 service 的意义在于展示 http 链路调用通过 dapr 如何实现。
dotnet5-client-a--1-->dotnet5-service-b;
dotnet5-service-b--2-->dotnet5-service-c;
dotnet5-service-c--3-->dotnet5-service-b;
dotnet5-service-b--4-->dotnet5-client-a;
- dotnet5-client-a 做为客户端调用服务 dotnet5-service-b;
- dotnet5-service-b 做为服务中转,既收来自 dotnet5-client-a 客户端的请求,又发起对 dotnet5-service-c 的调用;
- dotnet5-service-c 响应 dotnet5-service-b 的请求;
- dotnet5-service-b 响应 dotnet5-client-a 的请求。
ServiceC
ServiceC 做为 http 调用链路调用终端只需监听 http 调用端口。通过 nuget 包管理工具,选中->Show pre-release packages,搜索 dapr ,选中 Dapr.AspNetCore 安装包。

Startup
在 ConfigureServices(IServiceCollection services) 方法中通过链式调用 AddDapr() 方法注册 Dapr 到 IOC 容器中。内容如下:
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ServiceC
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddDapr().AddJsonOptions(options => {
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
}
);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
HelloController
在 HelloController 中添加 Talk 方法,打印接收的信息并告诉调用方当前服务是谁。具体内容如下:
[ApiController]
public class HelloController : Controller
{
[HttpPost("talk")]
public async Task<SomeResponseBody> Talk(SomeRequestBody someRequestBody)
{
Console.WriteLine(string.Format("{0}:{1}", someRequestBody.Id, someRequestBody.Time));
return await Task.FromResult(new SomeResponseBody
{
Msg = "This is ServiceC"
});
}
}
launchSetting.json
profiles.ServiceC.applicationUrl 端口号一定要修改为 --app-port 相同的端口号,否则通过 dapr 启动项目的时候无法正常启动
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:35737",
"sslPort": 44379
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ServiceC": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:9201",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
启动
dapr run --app-id dotnet-server-c --app-port 9201 --dapr-http-port 3520 dotnet run
ServiceB
ServiceB 做为调用链中的一个中转节点,既要监听服务,同时还要发起请求。由于 Dapr.AspNetCore 已经引用了 Dapr.Client 。因此不需要再次引用 Dapr.Client。
Startup
下面是 Dapr.AspNetCore AddDapr() 源码,从源码中可知 AddDapr() 方法向控制器中注册 Dapr 集成。同时通过依赖注入容器注册 DaprClient 。DaprClient 可以和 Dapr 运行时交互。比如 HTTP 调用,也正因为如此,ServiceB 的 Startup 文件我们只需拷贝 ServiceC 的 Startup 文件即可。源码如下:
/// <summary>
/// Provides extension methods for <see cref="IMvcBuilder" />.
/// </summary>
public static class DaprMvcBuilderExtensions
{
/// <summary>
/// Adds Dapr integration for MVC to the provided <see cref="IMvcBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder" />.</param>
/// <param name="configureClient">The (optional) <see cref="DaprClientBuilder" /> to use for configuring the DaprClient.</param>
/// <returns>The <see cref="IMvcBuilder" /> builder.</returns>
public static IMvcBuilder AddDapr(this IMvcBuilder builder, Action<DaprClientBuilder> configureClient = null)
{
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// This pattern prevents registering services multiple times in the case AddDapr is called
// by non-user-code.
if (builder.Services.Any(s => s.ImplementationType == typeof(DaprMvcMarkerService)))
{
return builder;
}
builder.Services.AddDaprClient(configureClient);
builder.Services.AddSingleton<DaprMvcMarkerService>();
builder.Services.AddSingleton<IApplicationModelProvider, StateEntryApplicationModelProvider>();
builder.Services.Configure<MvcOptions>(options =>
{
options.ModelBinderProviders.Insert(0, new StateEntryModelBinderProvider());
});
return builder;
}
private class DaprMvcMarkerService
{
}
}
HelloController
通过构造器注入 DaprClient 以发起 Http 调用 ServiceC 提供的服务。
[ApiController]
public class HelloController : ControllerBase
{
private readonly DaprClient daprClient;
public HelloController(DaprClient daprClient)
{
this.daprClient = daprClient;
}
[HttpPost("talk")]
public async Task<SomeResponseBody> Talk(SomeRequestBody someRequestBody)
{
var data = new { Time = DateTime.Now.ToLongDateString(), Id = "This is Service C." };
HTTPExtension httpExtension = new HTTPExtension()
{
Verb = HTTPVerb.Post
};
SomeResponseBody responseBody = await daprClient.InvokeMethodAsync<object, SomeResponseBody>("dotnet-server-c", "talk", data, httpExtension);
Console.WriteLine(string.Format("{0}:{1} \n recieve message:{2}", someRequestBody.Id, someRequestBody.Time, responseBody.Msg));
return await Task.FromResult(new SomeResponseBody
{
Msg = "This is ServiceB"
});
}
launchSetting.json
参考 ServiceC 更改端口号。
启动
dapr run --app-id dotnet-server-b --app-port 9200 --dapr-http-port 3521 dotnet run
ClientA
ClientA 的目的是发起对 ServiceB 服务的调用,因此只需添加 Dapr.Client 用于和 Dapr 运行时交互即可。内容如下:
class Program
{
static async Task Main(string[] args)
{
var jsonOptions = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
};
var client = new DaprClientBuilder()
.UseJsonSerializationOptions(jsonOptions)
.Build();
var data = new { Time = DateTime.Now.ToLongDateString(), Id="This is Client A" };
HTTPExtension httpExtension = new HTTPExtension()
{
Verb = HTTPVerb.Post
};
while (true)
{
var a = await client.InvokeMethodAsync<object, SomeResponseBody>("dotnet-server-b", "talk", data, httpExtension);
Console.WriteLine(a.Msg);
await Task.Delay(5 * 1000);
}
}
}
每间隔 5 秒向 ServiceB 发送一次请求。
启动
dapr run --app-id dotnet5-http-client dotnet run
ClientA 接收内容:
== APP == This is ServiceB
SerivceB 接收内容:
== APP == This is Client A:2020年11月27日 星期五
== APP == recieve message:This is ServiceC
ServiceC 接收内容:
== APP == This is Service C.:2020年11月27日 星期五
总结
至此,DOTNET5 通过 dapr HTTP 调用的示例就结束了。

Dapr DotNet5 HTTP 调用的更多相关文章
- Dapr Golang HTTP 调用
Dapr Golang HTTP 调用 版本介绍 Go 版本:1.15 Dapr Go SKD 版本:0.11.1 工程结构 从上图可知,新建 3 个 Go 启动项目,cmd 为启动项目目录,其中 c ...
- Dapr Java Http 调用
版本介绍 Java 版本:8 Dapr Java SKD 版本:0.9.2 Dapr Java-SDK HTTP 调用文档 有个先决条件,内容如下: Dapr and Dapr CLI. Java J ...
- 手把手教你学Dapr - 4. 服务调用
上一篇:手把手教你学Dapr - 3. 使用Dapr运行第一个.Net程序 介绍 通过使用服务调用,您的应用程序可以使用标准的gRPC或HTTP协议与其他应用程序可靠.安全地通信. 为什么不直接用Ht ...
- Dapr 运用之集成 Asp.Net Core Grpc 调用篇
前置条件: <Dapr 运用> 改造 ProductService 以提供 gRPC 服务 从 NuGet 或程序包管理控制台安装 gRPC 服务必须的包 Grpc.AspNetCore ...
- Dapr微服务应用开发系列3:服务调用构件块
题记:这篇开始逐一深入介绍各个构件块,从服务调用开始 原理 所谓服务调用,就是通过这个构件块让你方便的通过HTTP或者gRPC协议同步调用其他服务的方法,这些方法也是通过HTTP或者gRPC来暴露的. ...
- Dapr初体验之服务调用
初次理解服务调用 在微服务中,有一个难点就是:如果你想使用各个服务组件,你就得知道不同服务的地址和端口,也就是服务发现. 在传统应用我们是怎么做的?就是在web项目里配置上api地址,如下: 在一个w ...
- Caller 服务调用 - Dapr
前言 上一篇我们讲了使用HttpClient的方式调用,那么如果我们现在需要更换为通过dapr实现服务调用,我们需要做哪些事情呢? Caller.Dapr 入门 如果我们的项目原本使用的是Caller ...
- 3. Caller 服务调用 - dapr
前言 上一篇我们讲了使用HttpClient的方式调用,那么如果我们现在需要更换为通过dapr实现服务调用,我们需要做哪些事情呢? Caller.Dapr 入门 如果我们的项目原本使用的是Caller ...
- 微软的分布式应用框架 Dapr
微服务架构已成为构建云原生应用程序的标准,微服务架构提供了令人信服的好处,包括可伸缩性,松散的服务耦合和独立部署,但是这种方法的成本很高,需要了解和熟练掌握分布式系统.为了使用所有开发人员能够使用任何 ...
随机推荐
- 循序渐进VUE+Element 前端应用开发(24)--- 修改密码的前端界面和ABP后端设置处理
用户在系统登录后,一般会提供一个入口给当前用户更改当前的密码,其实更改密码操作是很简单的一个处理,不过本篇随笔主要是介绍结合前后端来实现这个操作,后端是基于ABP框架的,需要对密码的安全性进行一个设置 ...
- U138097 小鱼吃大鱼 埃氏筛
题目描述 小P同学在养殖一种非常凶狠的鱼,而且与其他鱼类不同,这种鱼越大越温顺,反而小鱼最凶残.当两条鱼相遇时, 小鱼会不断撕咬大鱼,每一口都咬下与它自身等重的肉(小鱼保持体重不变),直到大鱼的体重小 ...
- 震惊!你还不知道SpringBoot真正的启动引导类
引言 SpringBoot项目中的启动类,一般都是XXApplication,例如「StatsApplication」,「UnionApplication」. 每个项目的启动类名称都不一样.但是它的启 ...
- vue项目优化与上线
一.项目优化策略 1.生成打包报告 2.第三方库启用CDN 3.Element-ui组件按需加载 4.首页内容定制 5.路由懒加载 1.生成打包报告 1.1通过vue-cli的UI面板直接查看 1.2 ...
- pycharm pro2020版专业版永久激活
pycharm2020版本专业版永久激活[亲测有效] pycharm2020.1版安装包与破解工具下载 可私信我获取资源. 公众号,轻松学编程 教程 1.先下载安装包和破解补丁压缩包,然后点击pych ...
- How to refresh datasource args caller[X++]
To refresh datasource args caller, you must add override method close on form like source code belo ...
- Ubuntu 16.04升级18.04
原文:https://blog.csdn.net/sean_8180/article/details/81075659 1.更新资源$ sudo apt-get update$ sudo apt-ge ...
- 3.2spring源码系列----循环依赖源码分析
首先,我们在3.1 spring5源码系列--循环依赖 之 手写代码模拟spring循环依赖 中手写了循环依赖的实现. 这个实现就是模拟的spring的循环依赖. 目的是为了更容易理解spring源码 ...
- hive 下载和导入数据 hive -e
1. 从97导出dim_channel_terminal_flag表数据到txt(数据下载) hive -e 'select * from dim.dim_city' >> dim_cit ...
- 使用Selenium爬取京东电商数据(以手机商品为例)
进入京东(https://www.jd.com)后,我如果搜索特定的手机产品,如oppo find x2,会先出现如下的商品列表页: 如果点击进入其中一个商品会进入到如下图所示的商品详情页,可以看到用 ...