目录
前置条件
- 安装docker与dapr: 手把手教你学Dapr - 3. 使用Dapr运行第一个.Net程序
- 安装k8s
dapr 自托管模式运行
新建一个webapi无权限项目
launchSettings.json中applicationUrl端口改成5001,如下:
"applicationUrl": "http://localhost:5001"
//WeatherForecastController.cs更改如下 using Microsoft.AspNetCore.Mvc; namespace backend.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } [HttpPost(Name = "Hello")] public object SayHello() { return new { message = "Hello" }; //这里返回必须是json对象,如果为字符串,则在daprClient.InvokeMethodAsync调用时会出错 } } }
到backend目录运行运行下面命令:
dapr run --app-id backend --app-port 5001 dotnet run
然后运行:
dapr invoke --app-id backend --method WeatherForecast dapr invoke --app-id backend --method WeatherForecast --verb GET
显示下图表示运行成功
dapr服务调用
新建一个名为front的weiapi无权限项目
launchSettings.json中applicationUrl端口改成5002,如下:
"applicationUrl": "http://localhost:5002"
添加nuget包:Dapr.Client
修改WeatherForecastController.cs如下:
using Dapr.Client; using Microsoft.AspNetCore.Mvc; namespace front.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { [HttpPost(Name = "Hello")] public async Task<string> HelloAsync() { var appId = "backend"; var methodName = "WeatherForecast"; using (var daprClient = new DaprClientBuilder().Build()) { try { var result = await daprClient.InvokeMethodAsync<object>(HttpMethod.Post, appId, methodName); Console.WriteLine(result); return result.ToString(); } catch (Exception ex) { Console.WriteLine($"An exception occurred while invoking method: '{methodName}' on app-id: '{appId}'"); Console.WriteLine(ex.ToString()); } } return "Error!"; } } }
访问http://http://localhost:5002/swagger/页面运行如下就成功了