南通颐猩文化传播有限公司

當前位置:首頁 >  站長 >  編程技術 >  正文

Asp.net core中RedisMQ的簡單應用實現(xiàn)

 2020-12-31 16:57  來源: 腳本之家   我來投稿 撤稿糾錯

  域名預訂/競價,好“米”不錯過

這篇文章主要介紹了Asp.net core中RedisMQ的簡單應用實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

最近一個外部的項目,使用到了消息隊列,本來是用rabbitmq實現(xiàn)的,但是由于是部署到別人家的服務器上,想盡量簡化一些,項目中本來也要接入了redis緩存,就嘗試使用redis來實現(xiàn)簡單的消息隊列。

使用redis做消息隊列有兩種方法,一種是使用pub/sub,另一種是使用list結構,配合brpop來消費。這兩種方式各有特點,這里簡述一下:

pub/sub模式,支持多客戶端消費,但是不支持持久化,這就意味著客戶端斷開的時間內(nèi)發(fā)布的消息將會全部舍棄掉。

list配合brpop,默認不支持多客戶端消費,支持持久化。這種模式的多客戶端消費可以變相實現(xiàn),比如下面的偽代碼:

#第一步push消息到隊列
lpush listA msg
#第二步,一個專門的分發(fā)客戶端取出消息,push到各個子隊列
var msg=brpop listA
lpush listA1 msg
lpush listA2 msg
......
#第三步,多個客戶端從對應的隊列消費消息
var client1_msg= brpop listA1
var client2_msg= brpop listA2
......

消息丟失不太可取,所以我選擇了list ,下一步需要選擇一個合適的客戶端。

Stackexchange.redis 算是一個老牌的客戶端了,但是由于其采用多路復用的模式,沒法支持Redis的blocking pops特性。所以我采用了國人寫的CSRedisCore。

首先需要在appsettings.json中添加redis的連接字符串:

{
"ConnectionStrings": {
"redis": "{ip}:{port},password=123456,prefix=my_"
}
}

具體配置請參考github上的文檔:https://github.com/2881099/csredis

然后在startup.cs的ConfigureServices中配置redis:

public void ConfigureServices(IServiceCollection services)
{
//redis配置
RedisHelper.Initialization(new CSRedis.CSRedisClient(Configuration.GetConnectionString("redis")));
}

當然也可以采用依賴注入的方式添加CSRedisClient實例,這個不糾結。

在項目中有好幾處使用到了隊列,所以先封裝一個消費服務:

public abstract class RedisMQConsumer : BackgroundService
{
protected abstract string CacheKey { get; }

protected ILogger<RedisMQConsumer> logger;

public RedisMQConsumer(ILogger<RedisMQConsumer> logger)
{
this.logger = logger;
}

protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
return Task.Run( async() =>
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
var msg = RedisHelper.BRPop(5, CacheKey);
try
{
if (string.IsNullOrEmpty(msg)) continue;
if (!Process(msg))
{
//加入錯誤處理隊列,可以在后臺寫功能手動處理
RedisHelper.LPush(CacheKey + "_err", msg);
}
}
catch (Exception exp)
{
//加入錯誤處理隊列,可以在后臺寫功能手動處理
RedisHelper.LPush(CacheKey + "_err", msg);
logger.LogError(exp, "RedisMQConsumer Execute error");
}
}
catch
{
//網(wǎng)絡可能中斷
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}

}
}, stoppingToken);
}

protected abstract bool Process(string message);
}

然后就可以繼承RedisMQConsumer,編寫實際邏輯:

public class AddOrderMQConsumer : RedisMQConsumer
{
public AddOrderMQConsumer(ILogger<RedisMQConsumer> logger) : base(logger)
{
}
protected override string CacheKey => "addOrder";
protected override bool Process(string message)
{
var order = JsonSerializer.Deserialize<Order>(message);
//處理邏輯
return true;
}
}

發(fā)布消息只是往隊列中添加項:

RedisHelper.LPush("addOrder", order);

最后把消費服務添加到startup.cs中:

public void ConfigureServices(IServiceCollection services)
{
//redis配置
RedisHelper.Initialization(new CSRedis.CSRedisClient(Configuration.GetConnectionString("redis")));

//redis消息隊列消費服務,放在redis配置下方
services.AddHostedService<AddOrderMQConsumer>();
}

經(jīng)測試,還算穩(wěn)定,小并發(fā)項目可以使用。

到此這篇關于Asp.net core中RedisMQ的簡單應用實現(xiàn)的文章就介紹到這了,更多相關Asp.net core RedisMQ內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

來源:腳本之家

鏈接:https://www.jb51.net/article/201718.htm

申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

相關文章

熱門排行

信息推薦