• DotNetCore.CAP 基础应用


    目录

    1.准备工作

    2.创建第一个项目   

    3.创建第二个项目

    4.运行


    1.准备工作

      1.1 rabbitmq

    username:admin

    password:admin

    port:5672

      1.2 mssql

    2.创建第一个项目

        2.1 创建webapi项目,起名为Cap.Step1.Service如图:

        2.2 选择项目位置

        2.3 选择框架,由于是windows上,所以不要docker

        2.4 添加引用,如图

    DotNetCore.CAP 6.1.0

    DotNetCore.CAP.Dashboard 3.1.2

    DotNetCore.CAP.RabbitMQ 6.1.0

    DotNetCore.CAP.SqlServer 5.2.0    

       

     2.5   添加Cap的配置文件,MsSqlConnection用于存储业务数据的MsSql数据库,配置如下:

    {
      "RabbitMQOptions": {
        "HostName": "192.168.2.8",
        "UserName": "admin",
        "Password": "admin",
        "Port": 5672
      }, 
     "MsSqlConnection": "Server=192.168.2.8;userid=sa;password=china_2020;Database=PtE"
    }

    2.6 添加服务端口号配置文件,配置如下:

    {
      "urls": "http://*:5001"
    }

    2.7 最后配置文件位置如图:

      2.8 在Startup中添加 cap的相关配置

    1. services.Configure(Configuration.GetSection("RabbitMQOptions"));
    2. string connection = this.Configuration.GetConnectionString("MsSqlConnection");
    3. services.AddCap(x =>
    4. {
    5. //存储消息数据
    6. x.UseSqlServer(configure => {
    7. configure.ConnectionString = connection;
    8. configure.UseSqlServer2008();
    9. });
    10. //连接RabbitMQ
    11. RabbitMQOptions rabbitMQ = this.Configuration.GetSection("RabbitMQOptions").Get();
    12. x.UseRabbitMQ((options) =>
    13. {
    14. options = rabbitMQ;
    15. });
    16. x.FailedRetryCount = 10; //失败后重试次数
    17. x.FailedRetryInterval = 60; //重试间隔
    18. x.FailedThresholdCallback = failed =>
    19. {
    20. var logger = failed.ServiceProvider.GetService>();
    21. logger.LogError($"MessageType{failed.MessageType} 失败,重试{x.FailedRetryCount}" +
    22. $"消息名称:{failed.Message.GetName()}");
    23. };
    24. });

        2.9 添加webapi 名为:Step1Controller 

    1. [Route("[controller]")]
    2. [ApiController]
    3. public class Step1Controller : ControllerBase
    4. {
    5. private readonly ICapPublisher capPublisher;
    6. private readonly IConfiguration configuration;
    7. private readonly ILogger logger;
    8. private string PublishName = "SHKF.Cap.Demo"; //下一步的消息队列Key
    9. public Step1Controller(ICapPublisher capPublisher,
    10. IConfiguration configuration,
    11. ILogger logger)
    12. {
    13. this.capPublisher = capPublisher;
    14. this.configuration = configuration;
    15. this.logger = logger;
    16. }
    17. [HttpGet()]
    18. public IActionResult Get()
    19. {
    20. //业务数据
    21. Dictionary<string, string> dicHeader = new Dictionary<string, string>();
    22. dicHeader.Add("Teacher", "WangPeng");
    23. dicHeader.Add("Student", "Seven");
    24. dicHeader.Add("Version", "1.2");
    25. using (var connection = new SqlConnection(this.configuration.GetConnectionString("MsSqlConnection")))
    26. {
    27. using (var tran = connection.BeginTransaction(this.capPublisher, false))
    28. {
    29. try
    30. {
    31. this.capPublisher.Publish(this.PublishName, dicHeader);
    32. }
    33. catch (Exception ex)
    34. {
    35. this.logger.LogWarning(ex.Message);
    36. tran.Rollback();
    37. }
    38. tran.Commit();
    39. }
    40. }
    41. this.logger.LogWarning($"This is AdoTransaction Invoke");
    42. return Ok();
    43. }
    44. }

        2.10 加载配置文件

    1. public static void Main(string[] args)
    2. {
    3. CreateHostBuilder(args)
    4. .ConfigureHostConfiguration((configBuilder) => {
    5. configBuilder.AddJsonFile("json/host.json", true);
    6. configBuilder.AddJsonFile("json/cap.json", true);
    7. })
    8. .Build().Run();
    9. }

        3.11 修改launchSettings文件,删除iis相关内容,同时启动不访问默认页

    1. {
    2. "profiles": {
    3. "Cap.Step1.Service": {
    4. "commandName": "Project",
    5. "launchBrowser": false,
    6. "launchUrl": "weatherforecast",
    7. "applicationUrl": "http://localhost:5001",
    8. "environmentVariables": {
    9. "ASPNETCORE_ENVIRONMENT": "Development"
    10. }
    11. }
    12. }

    3.创建第二个项目

        3.1 创建webapi项目

              项目引用, 配置文件, launchSettings文件和第一个项目相同,项目结构如下:

        3.2 由于不需要端口,所以把容器改成普通容器:如下图:

    1. public class Program
    2. {
    3. public static void Main(string[] args)
    4. {
    5. CreateHostBuilder(args)
    6. .ConfigureServices(ConfigureServices)
    7. .ConfigureHostConfiguration((configBuilder) => {
    8. configBuilder.AddJsonFile("json/host.json", true);
    9. configBuilder.AddJsonFile("json/cap.json", true);
    10. })
    11. .Build().Run();
    12. .Build().Run();
    13. }
    14. public static IHostBuilder CreateHostBuilder(string[] args) =>
    15. Host.CreateDefaultBuilder(args);
    16. private static void ConfigureServices(HostBuilderContext hostBuilder, IServiceCollection services)
    17. {
    18. IConfiguration Configuration = hostBuilder.Configuration;
    19. services.Configure(Configuration.GetSection("RabbitMQOptions"));
    20. services.AddControllers();
    21. string connection = Configuration.GetConnectionString("MsSqlConnection");
    22. services.AddCap(x =>
    23. {
    24. // If you are using ADO.NET, choose to add configuration you needed:
    25. x.UseSqlServer(configure => {
    26. configure.ConnectionString = connection;
    27. configure.UseSqlServer2008();
    28. });
    29. // CAP support RabbitMQ,Kafka,AzureService as the MQ, choose to add configuration you needed:
    30. RabbitMQOptions rabbitMQ = Configuration.GetSection("RabbitMQOptions").Get();
    31. x.UseRabbitMQ((options) =>
    32. {
    33. options = rabbitMQ;
    34. });
    35. x.FailedRetryCount = 10;
    36. x.FailedRetryInterval = 60;
    37. x.FailedThresholdCallback = failed =>
    38. {
    39. var logger = failed.ServiceProvider.GetService>();
    40. logger.LogError($"MessageType{failed.MessageType} 失败,重试{x.FailedRetryCount}" +
    41. $"消息名称:{failed.Message.GetName()}");
    42. };
    43. });
    44. }
    45. }

        3.4 添加Step2Controller

    4.运行

        4.1 运行Step1项目,Step2项目

        4.2 用postman发送请求 

    http://localhost:5001/step1

        4.3 此时rabbmitmq中会多出交换机,cap.default.router

        4.5 同时数据库中会增加两个表:Published,Received,表里会存储每一步的发送数据,和第二步的接收数据,这两个表是自动创建的

  • 相关阅读:
    一款针对中小学研发的智慧校园系统源码,智慧学校源码,Java+智慧安防+智慧互联+智慧电子班牌+小程序源码
    【Redis】redis基本数据类型详解(String、List、Hash、Set、ZSet)
    el-menu 有一级二级三级菜单
    Android学习笔记 2.4.3 实例——使用QuickContactBadge关联联系人 && 2.4.4 实例——可折叠的悬浮按钮
    自动化物流运输设备模组要选择哪种类型?
    基于蒙特卡洛的大规模电动汽车充电行为分析(Matlab代码实现)
    [附源码]计算机毕业设计在线项目管理Springboot程序
    一个完整的初学者指南Django-part2
    基于IDEA创建SpringBoot项目并进行入门分析
    java代理
  • 原文地址:https://blog.csdn.net/wang_peng/article/details/127570832