环境:
dapr 1.0
dotnet 5.0
docker
一、创建WebApi项目 Dapr.WebApi.Sample
添加引用 Dapr.AspNetCore
修改Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddDapr();
...
}
WeatherForecastController:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Dapr.WebApi.Sample.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("Get")]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
Dapr运行:
说明:--app-id 为发布的Dapr应用ID,--app-port 5000 对应 launchSettings.json 中的端口,--dapr-http-port 为该Dapr应用的端口号
dapr run --app-id dotnet-webapi --app-port 5000 --dapr-http-port 3525 dotnet run
二、客户端调用WebApi
创建DaprClient 控制台项目,通过Dapr方式调用WeatherForecastController
添加引用 Dapr.Client
Program.cs:每隔5秒调用一次WeatherForecastController的Get方法,并打印出来
using Dapr.Client;
using Dapr.Client.Autogen.Grpc.v1;
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
static async Task Main(string[] args)
{
var jsonOptions = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
};
var client = new DaprClientBuilder()
.UseJsonSerializationOptions(jsonOptions)
.Build();
while (true)
{
//dotnet-webapi 为Dapr发布Id
//最后参数,可以看做path
var result = await client.InvokeMethodAsync<dynamic>(HttpMethod.Get, "dotnet-webapi", "WeatherForecast/Get");
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(result));
await Task.Delay(5 * 1000);
}
}
Dapr运行:
dapr run --app-id dapr-client dotnet run
输出: