本文首发于《ASP.NET Core 3.1使用Redis缓存数据库实现精准执行延迟任务的解决方案》。
前言
作为一名.NET开发者,你是否曾遇到过类似这样的需求:“在一个电商网站中,当一个订单超过30分钟仍未支付,则需使用任务将此订单设置为作废订单。”。
这是一个在开发过程中常见的定时任务(或者延迟任务)的典型案例,定时任务/延迟任务有非常多的场景,我们不能一一列举,那么,在程序开发中的实现方式又有哪些呢?
- 定时轮循数据库,即使用定时任务(比如30秒,1分钟,2分钟…)去定时检查数据库的订单数据,将超过30分钟仍未支付的订单状态修改为作废订单。
- 使用第三方组件,如:Quartz.NET, FluentScheduler,Hangfire等定时任务调度框架执行延迟任务。
- 使用Redis的键的过期时间(Keyspace Notifications)的回调来实现延迟执行任务。
- …
本文主要为大家分享的是第三种解决方案,即:在ASP.NET Core应用程序中使用Redis的键的过期时间的回调来实现延迟执行任务。
本文假定你已经准备好了Redis的运行环境,如无Redis环境,请查阅相关的Redis安装及配置教程自行解决。
配置redis.confg
Redis的notify-keyspace-events
选项默认是不启用,所以我们需要打开Redis的配置文件redis.config
并修改notify-keyspace-events
的值为:Ex
,重启生效。索引位i的库,每当有过期的元素被删除时,向keyspace@:expired频道发送通知。
E表示键事件通知,所有通知以__keyevent@__:expired为前缀;
x表示过期事件,每当有过期被删除时发送。
创建项目
打开Visual Studio 2019,新建两个项目,分别为:RedisCoreDemo.App,RedisCoreDemo.Api。
其中RedisCoreDemo.App是一个.NET Core的控制台应用程序,我们将使用这个项目来订阅Redis的回调并执行相应的回调操作。
RedisCoreDemo.Api是一个ASP.NET Core 3.1的Web应用程序,我们将使用这个项目来向Redis发送数据,解决方案结构如下图:
发布消息
接下来打开项目RedisCoreDemo.Api的包管理工具,并安装Redis
相应的工具包:
- Microsoft.Extensions.Caching.Redis
- Microsoft.Extensions.Caching.StackExchangeRedis
如下图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cT28O7r8-1620367452662)(https://statics.codedefault.com/uploads/u/2020/05/oc06kxqjph.png)]
再打开Startup.cs
启动文件,添加Redis的缓存服务,如下:
services.AddDistributedRedisCache(option =>
{
option.Configuration = Configuration["RedisCache:ConnectionString"];
});
打开appsettings.json
配置文件,添加Redis缓存的配置节点,如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"RedisCache": {
"ConnectionString": "localhost:6379"
}
}
最后,我们在Controllers
目录下创建一个名为DemoController
的控制器,并添加一个Set()
的操作,如下:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace RedisCoreDemo.Api.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class DemoController : ControllerBase
{
private readonly IDistributedCache _distributedCache;
public DemoController(ILogger<DemoController> logger, IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
[HttpGet("{id}")]
public async Task<IActionResult> Set(int id)
{
await _distributedCache.SetStringAsync($"order_{id}"
, id.ToString()
, new DistributedCacheEntryOptions
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(5)
});
return Ok("success");
}
}
}
其中,最核心的代码为:
await _distributedCache.SetStringAsync($"order_{id}"
, id.ToString()
, new DistributedCacheEntryOptions
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(5)
});
这一条语句是使用C#/.NET Core向Redis中写入缓存数据,Redis的键名为order_
+订单ID。当然,为了测试方便,这个订单ID是直接从URL参数指定的。SetStringAsync()
方法的第三个参数指定了一个DistributedCacheEntryOptions
实例对象,并设置了AbsoluteExpiration
属性为当前时间+5秒,这尤其重要,它表示设置当前的这条Redis缓存数据在写入5秒后过期。
后续测试的时候,我们通过调用这个api,我们便可向Redis中写入缓存数据。
到此,测试用的基于ASP.NET Core 3.1的Web API和Redis的消息发布项目就完成了。接下来,我们继续实现消息订阅客户端RedisCoreDemo.App。
订阅消息并处理回调
回到之前我们创建的控制台应该程序RedisCoreDemo.App,我们使用这个程序来订阅Redis的过期数据,接收并处理回调。
首先,在RedisCoreDemo.App中打开包管理工具并添加Redis工具包StackExchange.Redis
,如下图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YvU1XO5F-1620367452665)(https://statics.codedefault.com/uploads/u/2020/05/l52j2m7g5j.png)]
打开Program.cs
文件,编写Redis的订阅事件和回调方法,如下:
using StackExchange.Redis;
using System;
namespace RedisCoreDemo.App
{
class Program
{
public static void Main(string[] args)
{
var EXPIRED_KEYS_CHANNEL = "__keyevent@0__:expired";
var host = "23.83.252.113:6379,password=753951";
var connection = ConnectionMultiplexer.Connect(host);
ISubscriber subscriber = connection.GetSubscriber();
subscriber.Subscribe(EXPIRED_KEYS_CHANNEL, (channel, key) =>
{
Console.WriteLine($"EXPIRED: {key}");
}
);
Console.WriteLine("Listening for events...");
Console.ReadKey();
}
}
}
好了,到此我们的Redis订阅客户端测试项目也完成了,接下来就是见证奇迹的时刻,同时运行RedisCoreDemo.App,RedisCoreDemo.Api这两个项目。再打开浏览器,调用api地址:http://localhost:16892/demo/set/1 ,观察订阅客户端的回调效果。
运行效果如下图(大图!!!,为了直观展示效果,请耐心等待加载):
结论
本文主要为大家分享的是如何使用ASP.NET Core 3.1+Redis实现精确的延迟执行任务的解决方案,希望对你的.NET开发有所帮助。
如果你有什么问题,或者更好的建议、意见,欢迎在评论区留言,我们一起探讨。
本文源码托管地址请至原文《ASP.NET Core 3.1使用Redis缓存数据库实现精准执行延迟任务的解决方案》查看。