最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.net使用cap實現(xiàn)消息異步處理

 更新時間:2024年05月17日 10:05:15   作者:假裝我不帥  
CAP 是一個基于 .NET Standard 的 C# 庫,它是一種處理分布式事務(wù)的解決方案,同樣具有 EventBus 的功能,它具有輕量級、易使用、高性能等特點,本文給大家介紹了.net下使用cap實現(xiàn)消息異步處理,需要的朋友可以參考下

介紹

CAP 是一個基于 .NET Standard 的 C# 庫,它是一種處理分布式事務(wù)的解決方案,同樣具有 EventBus 的功能,它具有輕量級、易使用、高性能等特點。

新建項目

新建.net7web項目

安裝依賴包

安裝軟件

安裝redis和Sql Server

修改代碼

新建RedisConfigModel

namespace CAPStu01.Models;

public class RedisConfigModel
{
    /// <summary>
    /// 服務(wù)器地址
    /// </summary>
    public string Host { get; set; }

    /// <summary>
    /// 端口號
    /// </summary>
    public int Port { get; set; }

    /// <summary>
    /// 密碼
    /// </summary>
    public string Pwd { get; set; }
}

修改appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "SQlServer": "server=127.0.0.1;User ID=sa;Password=xxxx;database=capstu;Encrypt=True;TrustServerCertificate=True;connection timeout=600;"
  },
  "RedisConfig": {
    "Host": "127.0.0.1",
    "Port": 6379,
    "Pwd": ""
  }
}

修改Program.cs

using CAPStu01.Models;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var redisConfig = builder.Configuration.GetSection("RedisConfig").Get<RedisConfigModel>();
var connectionStr = builder.Configuration.GetConnectionString("SQlServer") ?? "";
builder.Services.AddCap(x =>
{
    x.UseRedis(options =>
    {
        if (options.Configuration != null && redisConfig != null)
        {
            options.Configuration.EndPoints.Add(redisConfig.Host, redisConfig.Port);
            options.Configuration.DefaultDatabase = 0;
            options.Configuration.Password = redisConfig?.Pwd ?? "";
        }
    });
    x.UseSqlServer(sqlServerOptions =>
    {
        sqlServerOptions.Schema = "dbo";
        sqlServerOptions.ConnectionString = connectionStr;
    });
    //開啟面板
    x.UseDashboard(d =>
    {
        //允許匿名訪問
        d.AllowAnonymousExplicit = true;
    });
});
var app = builder.Build();

app.UseRouting();
app.MapControllers();
app.Run();

新建HomeController

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

namespace CAPStu01.Controllers;

[ApiController]
public class HomeController:ControllerBase
{
    public HomeController()
    {
        
    }

    /// <summary>
    /// 發(fā)送消息
    /// </summary>
    /// <returns></returns>
    [HttpGet("/")]
    public IActionResult Index([FromServices]ICapPublisher capBus)
    {
        capBus.Publish("test.show.time","你好,CAP");
        return Content("發(fā)送消息成功");
    }
    
    /// <summary>
    /// 接受消息
    /// </summary>
    /// <param name="data"></param>
    [NonAction]
    [CapSubscribe("test.show.time")]
    public void ReceiveMessage(string data)
    {
        Console.WriteLine("message data is:" + data);
    }
}

結(jié)果

如果使用redis需要定期清理streams內(nèi)容

安裝freeredis,修改Program.cs

builder.Services.AddSingleton<IRedisClient>(new RedisClient($"{redisConfig.Host}:{redisConfig.Port},password={redisConfig.Pwd},defaultDatabase=0"));

新增清除方法

private readonly IRedisClient _redisClient;

public HomeController(IRedisClient redisClient)
{
    _redisClient = redisClient;
}

/// <summary>
/// 清除已處理的redis數(shù)據(jù)
/// </summary>
/// <returns></returns>
[HttpGet("/clear")]
public IActionResult ClearAckStream()
{
    var groups = _redisClient.XInfoGroups("test.show.time");
    var unreandMsgs = new List<string>();
    //獲取所有的未讀消息
    foreach (var group in groups)
    {
        if (group.pending > 0)
        {
            //有未讀消息
            var unReadList = _redisClient.XPending("test.show.time", group.name);
            if (unReadList.count > 0)
            {
                var groupInfo = _redisClient.XPending("test.show.time", group.name);
                var unreandList = _redisClient.XPending("test.show.time", group.name, groupInfo.minId, groupInfo.maxId,
                    groupInfo.count);
                foreach (var unre in unreandList)
                {
                    unreandMsgs.Add(unre.id);
                }
            }
        }
    }
    //獲取全部的消息
    var allMsgs = _redisClient.XRange("test.show.time", "-", "+");
    foreach (var msg in allMsgs)
    {
        if (unreandMsgs.Contains(msg.id))
        {
            //這個消息未讀則跳過
            continue;
        }
        //刪除已處理的消息
        _redisClient.XDel("test.show.time", msg.id);
    }

    return Content($"共處理未讀消息:{unreandMsgs.Count}個,已讀消息{allMsgs.Length}個");
}

以上就是.net使用cap實現(xiàn)消息異步處理的詳細(xì)內(nèi)容,更多關(guān)于.net cap消息處理的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

沐川县| 昆明市| 西安市| 远安县| 吉木乃县| 新化县| 商都县| 镇赉县| 北流市| 丁青县| 谢通门县| 龙门县| 渭南市| 灵石县| 当阳市| 榕江县| 宁都县| 辉县市| 桓仁| 梁山县| 石楼县| 博兴县| 同江市| 嘉峪关市| 志丹县| 洪泽县| 乐亭县| 保山市| 濮阳市| 江阴市| 德令哈市| 安岳县| 德保县| 安新县| 曲松县| 响水县| 隆德县| 荥经县| 巴彦县| 丁青县| 绥芬河市|