当前位置:网站首页>3. Caller 服务调用 - dapr
3. Caller 服务调用 - dapr
2022-06-28 15:34:00 【InfoQ】
前言
Caller.Dapr 入门
- 改造Caller 服务调用 - HttpClient的中的服务端,使得服务端支持dapr调用
- 调整客户端代码,使客户端支持通过dapr来做到服务调用,并达到与HttpClient调用相同的结果
准备工作
- 安装.Net 6.0
- 创建ASP.NET Core 空白解决方案
Assignment03
- 将
Assignment02文件夹下的Assignment.Server复制到Assignment03的文件夹下,然后将项目Assignment.Server添加到解决方案Assignment03中
- 选中
Assignment.Server并安装Masa.Utils.Development.Dapr.AspNetCore
dotnet add package Masa.Utils.Development.Dapr.AspNetCore --version 0.4.0-rc1- 修改
Assignment.Server项目下的Program.cs
//忽略命名空间引用
var builder = WebApplication.CreateBuilder(args);
// 添加DaprStarter,用于服务端启动dapr sidecar,改造服务端支持dapr调用的重点(建议在开发环境下使用,线上环境使用k8s部署)
builder.Services.AddDaprStarter(option =>
{
option.AppId = "Assignment-Server";
option.DaprGrpcPort = 7007;
option.DaprHttpPort = 7008;
option.AppIdSuffix = string.Empty;
});
var app = builder.Build();
/// 忽略路由等
- 创建ASP.NET Core 空项目
Assignment.Client.DaprClientWeb作为客户端并安装Masa.Utils.Caller.DaprClient
dotnet add package Masa.Utils.Caller.DaprClient --version 0.4.0-rc1- 修改
Assignment.Client.DaprClientWeb项目下的Program.cs
using Masa.Utils.Caller.Core;
using Masa.Utils.Caller.DaprClient;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCaller(option =>
{
// 注意: 与Caller.HttpClient相比,需要修改的地方
options.UseDapr(masaDaprClientBuilder =>
{
masaDaprClientBuilder.Name = "userCaller"; // 当前Caller的别名(仅有一个Caller时可以不填),Name不能重复
masaDaprClientBuilder.IsDefault = true; // 默认的Caller支持注入ICallerProvider获取(仅有一个Caller时可不赋值)
masaDaprClientBuilder.AppId = "Assignment-Server";//设置当前caller下Dapr的AppId
});
});
var app = builder.Build();
app.MapGet("/", () => "Hello HttpClientWeb.V1!");
app.MapGet("/Test/User/Get", async ([FromServices] ICallerProvider callerProvider) =>
{
var user = await callerProvider.GetAsync<object, UserDto>("User", new { id = new Random().Next(1, 10) });
return $"获取用户信息成功:用户名称为:{user!.Name}";
});
app.MapGet("/Test/User/Add", async ([FromServices] ICallerProvider callerProvider) =>
{
var dateTimeOffset = new DateTimeOffset(DateTime.UtcNow);
string timeSpan = dateTimeOffset.ToUnixTimeSeconds().ToString();
var userName = "ss_" + timeSpan; //模拟一个用户名
string? response = await callerProvider.PostAsync<object, string>("User", new { Name = userName });
return $"创建用户成功了,用户名称为:{response}";
});
app.Run();
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; } = default!;
}
Assignment.Client.HttpClientWebAssignment.Client.DaprClientWebProgram.csUseHttpClientUseDapr- 添加环境变量
DAPR_GRPC_PORT,值为7007、DAPR_HTTP_PORT,值为7008
- Q: 为什么要添加环境变量? A: 由于当前客户端并未使用dapr sidecar,若当前客户端也使用dapr sidecar,此处可以不添加环境变量
Assignment.ServerAssignment.Client.DaprClientWebhttp://localhost:5042/Test/User/Gethttp://localhost:5042/Test/User/Add

DaprClient 最佳实践
Assignment.Client.DaprClientWebAssignment.Client.HttpClientWeb- 创建ASP.NET Core 空项目
Assignment.Client.DaprClientWeb.V2作为调用方V2版本
- 选中
Assignment.Client.DaprClientWeb.V2并安装Masa.Utils.Caller.DaprClient
dotnet add package Masa.Utils.Caller.DaprClient --version 0.4.0-rc1- 添加类
ServerCallerBase(对应服务端服务)
using Masa.Utils.Caller.DaprClient;
namespace Assignment.Client.DaprClientWeb.V2;
/// <summary>
/// 注意:ServerCallerBase是抽象类哟(抽象类不会被DI注册), 与使用Caller.HttpClient相比,需要修改的是继承的基类改为DaprCallerBase
/// </summary>
public abstract class ServerCallerBase : DaprCallerBase
{
protected override string AppId { get; set; } = "Assignment-Server";//设置当前Caller需要请求的服务端项目Dapr的AppId
public ServerCallerBase(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
}
- 添加类
UserCaller.cs
namespace Assignment.Client.DaprClientWeb.V2;
public class UserCaller : ServerCallerBase
{
public UserCaller(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
/// <summary>
/// 调用服务获取用户信息
/// </summary>
/// <param name="id">用户id</param>
/// <returns></returns>
public Task<UserDto?> GetUserAsync(int id)
=> CallerProvider.GetAsync<object, UserDto>("User", new { id = id });
/// <summary>
/// 调用服务添加用户
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public Task<string?> AddUserAsync(string userName)
=> CallerProvider.PostAsync<object, string>("User", new { Name = userName });
}
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; } = default!;
}
- 添加环境变量
DAPR_GRPC_PORT,值为7007、DAPR_HTTP_PORT,值为7008
Assignment.ServerAssignment.Client.DaprClientWeb.V2http://localhost:5102/Test/User/Gethttp://localhost:5102/Test/User/Add

常见问题
- 一个项目在同一个k8s集群部署了两套环境,为什么会出现代码调用混乱(开发环境调用线上环境)?
在于同一个K8s集群下,dapr会将服务组网,并将它们认为是同一个服务(AppId一致的服务)。- 如何解决同一个k8s集群中调用混乱的问题?
解决方案有两种:
1. 将不同环境下的服务分别部署在不同的K8s集群
2. 根据环境调整相对应服务的dapr sidecar的配置,其`AppId`的命名规则:`AppId`-`环境名`。修改自定义Caller的规则:
public abstract class CustomizeDaprCallerBase : DaprCallerBase
{
protected CustomizeDaprCallerBase(IServiceProvider serviceProvider) : base(serviceProvider)
{
var hostEnvironment = serviceProvider.GetRequiredService<IWebHostEnvironment>();
if (!hostEnvironment.IsDevelopment() || hostEnvironment.IsStaging())
AppId = AppId + "-" + hostEnvironment.EnvironmentName;
}
}
- 如何修改支持自定义Header?
目前Caller.Dapr不支持自定义Header,目前只能使用`SendAsync`才能自定义Header,不过此功能已经在0.5.0的开发计划中,在0.5.0中会支持总结
Caller.HttpClientCaller.Dapr本章源码
开源地址

边栏推荐
- 论文解读(GCC)《Efficient Graph Convolution for Joint Node RepresentationLearning and Clustering》
- R语言ggplot2可视化:使用patchwork包(直接使用加号+)将一个ggplot2可视化结果和数据表格横向组合起来形成最终结果图
- Yiwen teaches you to quickly generate MySQL database diagram
- R language ggplot2 visualization: the patchwork package horizontally combines a ggplot2 visualization result and a plot function visualization result to form a final result graph, aligns the two visua
- R language ggplot2 visualization: use the patchwork package to horizontally form two ggplot2 visualization results into a new result visualization combination diagram (using the | symbol)
- Qt5.5.1配置MSVC2010编绎器和windbg调试器
- The Web3.0 era is coming. See how Tianyi cloud storage resources invigorate the system to enable new infrastructure (Part 1)
- 不要使用短路逻辑编写 stl sorter 多条件比较
- R language ggplot2 visualization: the patchwork package is used to customize and combine the three ggplot2 visualization results to form a composite graph. After the horizontal combination of two sub
- Flutter dart语言特点总结
猜你喜欢

有哪些好用的供应商管理系统

字节跳动数据平台技术揭秘:基于 ClickHouse 的复杂查询实现与优化

VS2013 帮助文档中没有 win32/com

IPDK — Overview

教育行业SaaS应用管理平台解决方案:助力企业实现经营、管理一体化

Visual Studio 2010 配置和使用Qt5.6.3

看界面控件DevExpress WinForms如何创建一个虚拟键盘

Go zero micro Service Practice Series (VII. How to optimize such a high demand)

使用Karmada实现Helm应用的跨集群部署

【LeetCode】13、罗马数字转整数
随机推荐
Validate palindrome string
ROS知识点——话题消息的定义与使用
MIPS汇编语言学习-02-逻辑判断-前台输入
How can the digital intelligent supply chain management platform of the smart Park optimize process management and drive the development of the park to increase speed and quality?
数组中的第K大元素[堆排 + 建堆的实际时间复杂度]
SaaS application management platform solution in the education industry: help enterprises realize the integration of operation and management
论文解读(GCC)《Efficient Graph Convolution for Joint Node RepresentationLearning and Clustering》
A bug liver a week I can't help mentioning issue
利用MySqlBulkLoader实现批量插入数据的示例详解
Opengauss kernel: analysis of SQL parsing process
SQL statement exercises
What is the difference between treasury bonds and time deposits
R语言ggplot2可视化:使用patchwork包(直接使用加号+)将两个ggplot2可视化结果横向组合起来形成单个可视化结果图
一个bug肝一周...忍不住提了issue
使用Karmada实现Helm应用的跨集群部署
Oracle11g database uses expdp to back up data every week and upload it to the backup server
NFT pledge LP liquidity mining system development details
openGauss内核:SQL解析过程分析
R language ggplot2 visualization: use the patchwork package (directly use the plus sign +) to horizontally combine a ggplot2 visualization result and a plot function visualization result to form a fin
QT create 5.0.3 configuring qt4.8.7