其他分享
首页 > 其他分享> > .net core cap

.net core cap

作者:互联网

先回顾一下分布式系统的数据一致性的几个核心概念(术语):CAP、2PC、TCC、Base、Saga
CAP:一致性(Consistency)、可用性(Availability)、分区容错性(Partition tolerance)
Base:Basically Available(基本可用)、Soft state(软状态)和Eventually consistent(最终一致性)

看到github上.net core社区的CAP解决方案,这里记录一下使用过程。先使用in-memory storage和in-memory queue来模拟,步骤如下:
新建Web Api项目

安装依赖DotNetCore.CAP

安装依赖:DotNetCore.CAP.InMemoryStorage
安装依赖:Savorboard.CAP.InMemoryMessageQueue

如果是.net core 6以上版本,找到program.cs, 加入:

using Savorboard.CAP.InMemoryMessageQueue;

builder.Services.AddCap(x =>
{
    x.UseInMemoryStorage();
    x.UseInMemoryMessageQueue();
});

添加PublishController

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using DotNetCore.CAP;

namespace cap.demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PublishController : ControllerBase
    {
        [Route("~/send")]
        [HttpGet]
        public IActionResult SendMessage([FromServices] ICapPublisher capBus)
        {
            var header = new Dictionary<string, string>()
            {
                ["my.header.first"] = "first",
                ["my.header.second"] = "second"
            };

            capBus.Publish("test.show.time", DateTime.Now, header);
            //capBus.Publish("test.show.time", DateTime.Now);

            return Ok();
        }
    }
}

添加ConsumerController

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using DotNetCore.CAP;

namespace cap.demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ConsumerController : ControllerBase
    {
        [NonAction]
        [CapSubscribe("test.show.time")]
        public void ReceiveMessage(DateTime time, [FromCap] CapHeader header)
        {
            Console.WriteLine("message time is:" + time);
            Console.WriteLine("message firset header :" + header["my.header.first"]);
            Console.WriteLine("message second header :" + header["my.header.second"]);
        }
    }
}

运行项目,在Swagger中找到对应方法并执行

安装注册Dashboard

DotNetCore.CAP.Dashboard

builder.Services.AddCap(x =>
{
    x.UseInMemoryStorage();
    x.UseInMemoryMessageQueue();
    x.UseDashboard();
});

访问Dashboard
https://localhost:7092/cap

参考:
https://github.com/yang-xiaodong/Savorboard.CAP.InMemoryMessageQueue/blob/master/samples/InMemorySample/Startup.cs
https://github.com/dotnetcore/CAP/tree/master/samples
https://cap.dotnetcore.xyz/user-guide/en/getting-started/quick-start/

标签:core,CAP,cap,header,DotNetCore,time,using,net
来源: https://www.cnblogs.com/Andy1982/p/16442306.html