.net core cap-rabbitmq使用

安装nuget包:

bash 复制代码
 <PackageReference Include="DotNetCore.CAP" Version="6.0.0" />
 <PackageReference Include="DotNetCore.CAP.Dashboard" Version="6.0.0" />
 <PackageReference Include="DotNetCore.CAP.InMemoryStorage" Version="6.0.0" />
 <PackageReference Include="DotNetCore.CAP.RabbitMQ" Version="6.0.0" />
 <PackageReference Include="DotNetCore.CAP.SqlServer" Version="6.0.0" />
 <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />

配置program:

csharp 复制代码
 // CAP配置
 builder.Services.AddCap(x =>
 {
     x.UseSqlServer("Server=.;Database=Blogging;Integrated Security=True"); // 生产环境应选择例如SQL Server, MySQL, MongoDB等
     x.UseDashboard();//仪表板
     // 添加事件总线cap

     // 使用RabbitMQ进行事件中心处理
     x.UseRabbitMQ(rb =>
     {
         rb.HostName = "localhost";
         rb.UserName = "guest";
         rb.Password = "guest";
         rb.Port = 5672;
         rb.VirtualHost = "/";
     });
 });

controller代码

csharp 复制代码
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ICapPublisher _capPublisher;

        public WeatherForecastController(ICapPublisher capPublisher)
        {
            _capPublisher = capPublisher;
        }

        [HttpPost]
        public async Task<IActionResult> CreateUser([FromBody] User user)
        {
            // 创建用户逻辑...

            var userCreatedEvent = new UserCreatedEvent
            {
                UserId = user.Id,
                Name = user.Name
            };

            await _capPublisher.PublishAsync("user.created", userCreatedEvent);

            return Ok();
        }

       
        [CapSubscribe("user.created")]
        [NonAction]
        public void OnUserCreated(UserCreatedEvent e)
        {
            // 处理用户创建事件,例如记录日志、发送邮件等
            Console.WriteLine($"New user created: {e.UserId}, Name: {e.Name}");
        }
    }

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
相关推荐
2501_9418204921 小时前
面向零信任安全与最小权限模型的互联网系统防护设计思路与多语言工程实践分享
开发语言·leetcode·rabbitmq
ZePingPingZe21 小时前
@TransactionalEventListener:事务事件监听的艺术
分布式·spring·rabbitmq
2501_9418752821 小时前
分布式系统中的安全权限与审计工程实践方法论经验总结与多语言示例解析分享
开发语言·rabbitmq
回家路上绕了弯1 天前
日志输出优化实战:从“能用”到“好用”的全攻略
分布式·后端
十月南城1 天前
分布式事务方法论——2PC/TCC/SAGA与基于消息的最终一致性对照
分布式
2501_941879811 天前
多语言微服务架构下的微服务消息幂等性与重试机制实践
rabbitmq
2501_941804321 天前
从单机缓存到分布式缓存高可用与一致性体系落地的互联网系统工程实践随笔与多语言语法思考
rabbitmq·memcached
笃行客从不躺平1 天前
分布式中的CAP 复习
分布式
记得开心一点嘛1 天前
分布式ID生成器
分布式
bkspiderx1 天前
RabbitMQ 全面技术指南
分布式·消息队列·rabbitmq