
Dapr .NetCore 订阅与发布(下)
解决关于运行是报错问题
我们将为InvokeMethodServer
API项目做一些修改。
首先添加一些相关依赖
<ItemGroup>
<PackageReference Include="CloudNative.CloudEvents" Version="1.3.80" />
<PackageReference Include="CloudNative.CloudEvents.AspNetCore" Version="1.3.80" />
<PackageReference Include="Dapr.AspNetCore" Version="1.4.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
创建RequestController
控制器,设置/dapr/subscribe
订阅与发布的配置,这里我们添加一个NewSong方法并且将路径设置为/playlist/hello
.
[ApiController]
[Route("[controller]")]
public class RequestController : ControllerBase
{
private readonly ILogger<RequestController> _logger;
public RequestController(ILogger<RequestController> logger)
{
_logger = logger;
}
[HttpGet("/dapr/subscribe")]
public ActionResult<IEnumerable<string>> Get()
{
var topics = new [] {new { pubsubname="pubsub",topic = "songs", route = "playlist/hello"}};
return new OkObjectResult(topics);
}
[HttpPost("/playlist/hello")]
public async Task<IActionResult> NewSong(CloudEvent cloudEvent)
{
var song = JsonConvert.DeserializeObject<Song>(cloudEvent.Data.ToString());
_logger.LogInformation($"New song request: {song.Artist} – {song.Name}");
return new OkResult();
}
}
public class Song
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("artist")]
public string Artist { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
在 Startup 类中,为了帮助进行模型绑定,让我们为 CloudEvents添加一个输入格式化程序
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddDapr();
services.AddMvc(opts =>
{
opts.InputFormatters.Insert(0, new CloudNative.CloudEvents.CloudEventJsonInputFormatter());
});
}
// 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();
});
}
运行测试
dapr run --app-id myserer --app-port 5002 --dapr-http-port 3500 -- dotnet run
dapr cri调用
dapr publish --publish-app-id myserer --pubsub pubsub --topic songs --data '{"id":17,"name":"dapr_cli_mysongs","artist":"hhh"}'
bash调用
curl -X POST http://localhost:3500/v1.0/publish/pubsub/songs -H "Content-Type: application/json" -d '{"id":17,"name":"bash_mysongs","artist":"hhh"}'
从其他客户端dapr请求过来的也能响应到。
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
评价
排名
41
文章
14
粉丝
3
评论
3
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术