.net使用cap實(shí)現(xiàn)消息異步處理
介紹
CAP 是一個(gè)基于 .NET Standard 的 C# 庫(kù),它是一種處理分布式事務(wù)的解決方案,同樣具有 EventBus 的功能,它具有輕量級(jí)、易使用、高性能等特點(diǎn)。
新建項(xiàng)目
新建.net7web項(xiàng)目

安裝依賴包

安裝軟件
安裝redis和Sql Server
修改代碼
新建RedisConfigModel
namespace CAPStu01.Models;
public class RedisConfigModel
{
/// <summary>
/// 服務(wù)器地址
/// </summary>
public string Host { get; set; }
/// <summary>
/// 端口號(hào)
/// </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))
{
//這個(gè)消息未讀則跳過
continue;
}
//刪除已處理的消息
_redisClient.XDel("test.show.time", msg.id);
}
return Content($"共處理未讀消息:{unreandMsgs.Count}個(gè),已讀消息{allMsgs.Length}個(gè)");
}

以上就是.net使用cap實(shí)現(xiàn)消息異步處理的詳細(xì)內(nèi)容,更多關(guān)于.net cap消息處理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
完成OSS.Http底層HttpClient重構(gòu)封裝 支持標(biāo)準(zhǔn)庫(kù)
OSS.Http項(xiàng)目對(duì)于.Net Standard標(biāo)準(zhǔn)庫(kù)的支持已經(jīng)遷移完畢,OSS開源系列兩個(gè)最底層的類庫(kù)已經(jīng)具備跨運(yùn)行時(shí)支持的能力。本篇文章主要包含 1. HttpClient的介紹,2. 重構(gòu)的思路, 3. 容易遇到的問題。具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-02-02
C#使用CefSharp實(shí)現(xiàn)內(nèi)嵌網(wǎng)頁(yè)詳解
這篇文章主要介紹了C# WPF里怎么使用CefSharp嵌入一個(gè)網(wǎng)頁(yè),并給出一個(gè)簡(jiǎn)單示例演示C#和網(wǎng)頁(yè)(JS)的交互實(shí)現(xiàn),感興趣的小伙伴可以了解一下2023-04-04
C#調(diào)用Win32的API函數(shù)--User32.dll
這篇文章主要介紹了C#調(diào)用Win32_的API函數(shù)--User32.dll,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
C#定時(shí)器Timer實(shí)現(xiàn)精確到1-2毫秒以內(nèi)
最近在排查項(xiàng)目OTA的一個(gè)問題,觸發(fā)了一毫秒或者2毫秒執(zhí)行一次進(jìn)程間通信的,導(dǎo)致通信阻塞的問題,這樣就需要用到模擬觸發(fā)1ms或者2ms觸發(fā)事件,所以本文給大家介紹了C#?定時(shí)器?Timer?如何精確到?1-2?毫秒以內(nèi),需要的朋友可以參考下2024-12-12
C#實(shí)現(xiàn)啟用與禁用本地網(wǎng)絡(luò)的方式小結(jié)【3種方式】
這篇文章主要介紹了C#實(shí)現(xiàn)啟用與禁用本地網(wǎng)絡(luò)的方式,結(jié)合實(shí)例形式總結(jié)分析了使用Hnetcfg.dll、Shell32.dll及setupapi.dll三種啟用與禁用本地網(wǎng)絡(luò)的操作方法,需要的朋友可以參考下2016-07-07

