Dapr .NetCore 调用方法 电脑版发表于:2021/9/28 10:45 ![](https://img.tnblog.net/arcimg/hb/896fd38e95b346f9a0d98c54b135bb94.jpg) >#Dapr .NetCore 调用方法 [TOC] ![](https://img.tnblog.net/arcimg/hb/0f8d684f968a4a25be3730f5f39a04b5.png) 创建客户端项目(InvokeMethod) ------------ ![](https://img.tnblog.net/arcimg/hb/b04fad9dbafc404584897a7740f75054.png) tn2>在Program类中设置日志控制台输出,在 launchSettings.json 设置运行的端口为`5001` ```csharp public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); logging.AddDebug(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); ``` ```json { "profiles": { "InvokeMethod": { "commandName": "Project", "launchBrowser": true, "launchUrl": "weatherforecast", "applicationUrl": "http://localhost:5001", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ``` tn2>安装dapr的依赖包 `Dapr.AspNetCore`,我这里的版本是`1.4.0` ```bash Install-Package Dapr.AspNetCore # or dotnet add package Dapr.AspNetCore ``` tn2>安装json序列化的包(Newtonsoft.Json) ```csharp Install-Package Newtonsoft.Json # or dotnet add package Newtonsoft.Json ``` tn2>安装Dapr服务 ```csharp services.AddControllers().AddDapr(); ``` tn2>创建 SendMessageController 控制器,其中里面有三个可请求的方法 (Send) 将mydata发送Get请求到appId为`myserver`的`Request`方法中 (Sendv2) 比上面一个多一种http请求方式,且是POST方法,判断请求是否成功 (Sendv3) 比上面多接受处理返回结果 ```csharp [ApiController] [Route("[controller]")] public class SendMessageController : ControllerBase { private readonly ILogger<SendMessageController> _logger; private readonly DaprClient _client; public SendMessageController(ILogger<SendMessageController> logger,DaprClient client ) { _logger = logger; _client = client; } [HttpGet] public async Task<string> Send() { var idnumber = new Random().Next(0,99); _logger.LogInformation("正在发送"); var mydata = new MyClass(idnumber,$"MyClass{idnumber}"); await _client.InvokeMethodAsync<MyClass>(HttpMethod.Get,"myserver","Request",mydata); _logger.LogInformation("发送成功"); return "ok"; } [HttpGet("sendv2")] public async Task<string> Sendv2() { var idnumber = new Random().Next(0,99); var mydata = new MyClass(idnumber,$"MyClass{idnumber}"); _logger.LogInformation("正在发送"); var client = DaprClient.CreateInvokeHttpClient(appId: "myserver"); _logger.LogInformation("发送成功"); // http的方式 var response = await client.PostAsJsonAsync("/Request/v2", mydata); if (response.IsSuccessStatusCode) { return "ok"; }else{ return "bad"; } } [HttpGet("sendv3")] public async Task<string> Sendv3() { var idnumber = new Random().Next(0,99); var mydata = new MyClass(idnumber,$"MyClass{idnumber}"); var client = DaprClient.CreateInvokeHttpClient(appId: "myserver"); // http的方式 var response = await client.PostAsJsonAsync("/Request/v3", mydata); if (response.IsSuccessStatusCode) { var newdata = await response.Content.ReadFromJsonAsync<MyClass>(); _logger.LogInformation($"得到服务器端处理的新数据:{newdata.Id} {newdata.Name}"); return JsonConvert.SerializeObject(newdata); }else{ return "bad"; } } public class MyClass { public MyClass(){} public MyClass(int id,string name) { Id = id; Name = name; } public int Id { get; set; } public string Name { get; set; } } } ``` 创建服务端项目(InvokeMethodServer) ------------ ![](https://img.tnblog.net/arcimg/hb/9d75d1c1139945a88996bbca74cd3cdc.png) tn2>在Program类中设置日志控制台输出,在 launchSettings.json 设置运行的端口为`5000` ```csharp public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); logging.AddDebug(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); ``` ```json { "profiles": { "InvokeMethod": { "commandName": "Project", "launchBrowser": true, "launchUrl": "weatherforecast", "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } ``` tn2>安装dapr的依赖包 `Dapr.AspNetCore` ```bash Install-Package Dapr.AspNetCore # or dotnet add package Dapr.AspNetCore ``` tn2>安装json序列化的包(Newtonsoft.Json) ```csharp Install-Package Newtonsoft.Json # or dotnet add package Newtonsoft.Json ``` tn2>安装Dapr服务 ```csharp services.AddControllers().AddDapr(); ``` tn2>接着定义RequestController控制器与客户端相对应的请求处理方法 ```csharp [ApiController] [Route("[controller]")] public class RequestController : ControllerBase { private readonly ILogger<RequestController> _logger; public RequestController(ILogger<RequestController> logger) { _logger = logger; } [HttpGet] public void Get(MyClass mydata) { _logger.LogInformation($"Server Finish! Result: {mydata.Id} {mydata.Name}"); } [HttpPost("v2")] public void GetV2(MyClass mydata) { _logger.LogInformation($"Server Finish v2 ! Result: {mydata.Id} {mydata.Name}"); } [HttpPost("v3")] public Task<MyClass> GetV3(MyClass mydata) { _logger.LogInformation($"Server Get Data v3 ! Data: {mydata.Id} {mydata.Name}"); mydata.Id = new Random().Next(1,99); mydata.Name = "From My Server Data"; _logger.LogInformation($"Server Updata Data: {mydata.Id} {mydata.Name}"); return Task.FromResult(mydata); } public class MyClass { public MyClass(){} public MyClass(int id,string name) { Id = id; Name = name; } public int Id { get; set; } public string Name { get; set; } } } ``` 运行测试 ------------ ```bash # 客户端运行 dapr run --app-id myclient --app-port 5001 --dapr-http-port 3501 -- dotnet run # 服务器端运行 dapr run --app-id myserver --app-port 5000 --dapr-http-port 3500 -- dotnet run ``` tn2>通过`dapr list`查看运行列表 ![](https://img.tnblog.net/arcimg/hb/f3f1d1e8ac4445d4a68b5fa8899cfdea.png) tn2>测试方法 ```bash dapr invoke --app-id myclient --method SendMessage --verb GET dapr invoke --app-id myclient --method SendMessage/sendv2 --verb GET dapr invoke --app-id myclient --method SendMessage/sendv3 --verb GET ``` tn2>或者以http请求的方式进行访问 ```bash curl http://localhost:3501/v1.0/invoke/myclient/method/SendMessage curl http://localhost:3501/v1.0/invoke/myclient/method/SendMessage/sendv2 curl http://localhost:3501/v1.0/invoke/myclient/method/SendMessage/sendv3 ``` ![](https://img.tnblog.net/arcimg/hb/adf9ccbd0a644275bba589a71dac0d2a.png) tn2>客户端请求信息 ![](https://img.tnblog.net/arcimg/hb/586924798bca4bad9e93eea918e118d6.png) tn2>服务器端处理信息 ![](https://img.tnblog.net/arcimg/hb/c943f6ab295540d085d75ecd0de4e0dd.png) 示例中的参数与描述 ------------ tn>dapr run的参数 | 参数 | 默认 | 描述 | | ------------ | ------------ | ------------ | | --app-id, -a | | 您的应用程序的 id,用于服务发现 | | --app-max-concurrency | unlimited | 应用的并发级别,否则为无限制 | | --app-port, -p | | 您的应用程序正在侦听的端口 | | --app-protocol, -P | http | Dapr 用于与应用程序通信的协议(gRPC 或 HTTP)。有效值为:http或grpc | | --app-ssl | false | Dapr 调用应用程序时启用 https | | --components-path, -d | Linux & Mac:`$HOME/.dapr/components`, Windows: `%USERPROFILE%\.dapr\components` | 组件目录的路径 | | --config, -c | Linux & Mac: `$HOME/.dapr/config.yaml`, Windows: `%USERPROFILE%\.dapr\config.yaml` | Dapr 配置文件 | | --dapr-grpc-port | 50001 | Dapr 监听的 gRPC 端口 | | --dapr-http-port | 3500 | Dapr 监听的 HTTP 端口 | | --enable-profiling | false | `pprof`通过 HTTP 端点启用分析 | | --help, -h | | 打印此帮助消息 | | --image | | 用于构建代码的图像。输入是: `repository/image` | | --log-level | info | 日志详细程度。有效值是:`debug`,`info`,`warn`,`error`,`fatal`,或者`panic` | | --placement-host-address | localhost | 安置服务的地址。格式< hostname >适用于默认端口(6050在 Windows 上,50005在 Linux/MacOS 上)或< hostname >:< port >自定义端口 | | --profile-port | 7777 | 配置文件服务器侦听的端口 | | --dapr-http-max-request-size | 4 | 请求正文的最大大小(以 MB 为单位)。 | tn>dapr invoke的参数 | 参数 | 默认 | 描述 | | ------------ | ------------ | ------------ | |--app-id, -a||要调用的应用程序 ID| |--help, -h||打印此帮助消息| |--method, -m||调用的方法| |--data, -d||JSON 序列化数据字符串(可选)| |--data-file, -f||包含 JSON 序列化数据的文件(可选)| |--verb, -v|POST|要使用的 HTTP 动词|