栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.Net 简单使用 CAP + RabbitMQ 完成事件的发布与订阅

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.Net 简单使用 CAP + RabbitMQ 完成事件的发布与订阅

简介

CAP 是一个EventBus,同时也是一个在微服务或者SOA系统中解决分布式事务问题的一个框架【官网】

使用
  • 第一步:创建发布者(Angel.Cap.Publisher)与订阅者(Angel.Cap.Subscriber)两个应用程序,在Nuget上引用主要依赖:DotNetCore.CAP、DotNetCore.CAP.RabbitMQ;用的是Sql Server,还要引用后面三个引用
  • 第二步:搭建发布者 Angel.Cap.Publisher
  1. 添加数据库连接字符串
 "ConnectionStrings": { //连接字符串
    "AngelDBContext": "data source=.;initial catalog=AngelCapDB;User ID=sa;Password=sa;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
  }
  1. 添加DBContext
 public class PubDBContext : DbContext
 {

     public PubDBContext()
     {

     }
     public PubDBContext(DbContextOptions options) : base(options)
     {

     }
     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
     {
         base.OnConfiguring(optionsBuilder);

     }
 }
  1. Configure和ConfigureServices使用
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    //注入数据库
    services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:AngelDBContext"]));

    //注册cap事件
    services.AddCap(x =>
    {
        x.UseEntityFramework();
        x.UseRabbitMQ(rb =>
        {
            rb.HostName = "localhost";
            rb.UserName = "admin";
            rb.Password = "admin";
            rb.Port = 5672;
            rb.VirtualHost = "Angel2022";
            rb.ExchangeName = "AngelCapExchange";
            rb.QueueMessageExpires = 24 * 3600 * 10; 
        });

    });

}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PubDBContext efCoreApp)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    efCoreApp.Database.EnsureCreated();//数据库不存在自动创建

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
  1. 创建发布接口
[Route("api/[controller]/[action]")]
[ApiController]
public class PubController : ControllerBase
{

    private ICapPublisher _capBus;

    public PubController(ICapPublisher capBus)
    {
        this._capBus = capBus;
    }

    [HttpGet]
    public IActionResult SendMsg()
    {
        for (var i = 0; i < 1000; i++)
        {
            DateTime date = DateTime.Now;
            _capBus.Publish("angel", $"******发布者,发布的内容为: {date},i:{i}*****");
        }

        return Content("发送成功");
    }
}

第三步:搭建订阅者Angel.Cap.Subscriber

  1. 添加数据库连接字符串,与发布者一样
  2. 添加DBContext
public class SubDBContext : DbContext
{

    public SubDBContext()
    {

    }
    public SubDBContext(DbContextOptions options) : base(options)
    {

    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

    }
}
  1. Configure和ConfigureServices使用
public void ConfigureServices(IServiceCollection services)
{
   services.AddControllersWithViews();


   //注入数据库
   services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:AngelDBContext"]));


   //注册cap事件
   services.AddCap(x =>
   {
       x.UseEntityFramework();
       x.UseRabbitMQ(rb =>
       {
           rb.HostName = "localhost";
           rb.UserName = "admin";
           rb.Password = "admin";
           rb.Port = 5672;
           rb.VirtualHost = "Angel2022";
           rb.ExchangeName = "AngelCapExchange";
           rb.QueueMessageExpires = 24 * 3600 * 10;  //队列中消息自动删除时间(默认10天)
       });
   });

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SubDBContext efCoreApp)
{
   if (env.IsDevelopment())
   {
       app.UseDeveloperExceptionPage();
   }
   else
   {
       app.UseExceptionHandler("/Home/Error");
       // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
       app.UseHsts();
   }
   app.UseHttpsRedirection();
   app.UseStaticFiles();

   app.UseRouting();

   efCoreApp.Database.EnsureCreated();//数据库不存在自动创建

   app.UseAuthorization();

   app.UseEndpoints(endpoints =>
   {
       endpoints.MapControllerRoute(
           name: "default",
           pattern: "{controller=Home}/{action=Index}/{id?}");
   });
}
  1. 创建订阅者接口
[Route("api/[controller]/[action]")]
[ApiController]
public class SubController : ControllerBase
{
    private ILogger _log;
    public SubController(ILogger log)
    {
        this._log = log;
    }

    /// 
    /// 订阅者的方法
    /// 
    /// 
    [NonAction]
    [CapSubscribe("angel")]
    public void ReceiveMsg(string str)
    {
    	_log.LogInformation($"我是订阅者,收到的内容为:{str}");
    }
}
Cap 面板

在Angel.Cap.Subscriber上使用面板

  1. 在ConfigureServices的AddCap上调用UseDashboard()
 //注册cap事件
services.AddCap(x =>
{
    x.UseEntityFramework();
    x.UseRabbitMQ(rb =>
    {
        rb.HostName = "localhost";
        rb.UserName = "admin";
        rb.Password = "admin";
        rb.Port = 5672;
        rb.VirtualHost = "Angel2022";
        rb.ExchangeName = "Angel_RabbMQ_Exchange";
        rb.QueueMessageExpires = 24 * 3600 * 10;  
    });
    x.UseDashboard();//使用Cap可视化面板
});
  1. 浏览器打开,域名后面加上cap
    https://localhost:44368/cap
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979847.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号