互联网上有非常多优秀成熟的开源项目,我们没必要重复造轮子,合理的使用这些框架为我们所用,达到快速高质的完成项目目标才是我们追求的,记住他山之石可以攻玉
1.场景介绍
电商业务里经常对某些商品做促销处理,为了查询性能,需要定时把促销商品的促销信息写入缓存
任务需求描述:
每隔2分钟将促销商品信息更新到Redis缓存中
2.实现方案
2.1 编写.netcore任务代码
新建一个.netcore控制台项目 PromoteProductCacheInfo
下面是模拟代码
static void Main(string[] args) { Console.WriteLine("开始写入商品促销信息:"); var sw = new Stopwatch(); sw.Start(); int successcount = 0; //商品数量 int procount = 5; for (int i = 0;i < procount; i++) { ProtoProductCacheInfo.ProductCacheInfo product = new ProtoProductCacheInfo.ProductCacheInfo(); product.Proid = i; product.Promotetitle = "限时特惠,8折促销"; product.Promoteprice = GetPromotePrice(100f); var isok = SaveData(product); successcount = isok ? successcount++ : successcount; Console.WriteLine("商品:" +i+ "写入缓存" + (isok?"成功":"失败")); } sw.Stop(); Console.WriteLine("共{0}个促销商品,写入成功{1}个,耗时:{1}", procount, successcount, sw.ElapsedMilliseconds); } /// <summary> /// 获取促销价格 /// </summary> /// <param name="price"></param> /// <returns></returns> static float GetPromotePrice(float price) { return price * 0.8f; } /// <summary> /// 写入Redis缓存 /// </summary> /// <param name="product"></param> /// <returns></returns> static bool SaveData(ProductCacheInfo product) { string cachekey = CacheKeyprefix + product.Proid; return CodisCache.Set(cachekey, product.ToByteArray(), CacheExpireIn); }
2.2 发布上传
我们选择Release模式发布代码,生成好后将 \bin\Release\netcoreapp3.1下的代码上传到xxl-job执行器所在的所有服务器上, 我这里是 /data/xxl-job/jobs/PromoteProductCacheInfo 目录下
2.3 配置任务
在任务调度中心我们新建一个任务
任务描述:促销商品信息写入缓存
运行模式:GLUE(Shell) 。这里使用shell模式,这样我们就可以使用shell脚本来执行我们的.netcore程序了
Cron:0 /2 * * * ? 我们可以非常方便的编写cron表达式。
填写完任务信息后保存,这样我们就创建了一个定时执行的job,可以在任务管理看到我们的任务已经存在了。
2.4 编写shell脚本
我们在任务调度中心的任务管理中找到创建的任务,点击右边的GLUE按钮打开脚本编辑页面,写入如下代码
#!/bin/bash cd /data/xxl-job/jobs/PromoteProductCacheInfo dotnet PromoteProductCacheInfo.dll exit 0
保存后我们的定时任务就算创建成功了,并且我们在任务的执行日志里可以看到Console.WriteLine的输出日志
2020-09-15 10:48:34 [com.xxl.job.core.thread.JobThread#run]-[124]-[Thread-3134153] ----------- xxl-job job execute start ----------- ----------- Param: 2020-09-15 10:48:34 [com.xxl.job.core.handler.impl.ScriptJobHandler#execute]-[64]-[Thread-3134153] ----------- script file:/data/xxljob/executor/www/gluesource/459_1600073830000.sh ----------- 开始写入商品促销信息: 商品:1写入缓存成功 商品:2写入缓存成功 商品:3写入缓存成功 商品:4写入缓存成功 商品:5写入缓存成功 共5个促销商品,写入成功5个,耗时:11 2020-09-15 10:48:34 [com.xxl.job.core.thread.JobThread#run]-[129]-[Thread-3134153] ----------- xxl-job job execute end(finish) ----------- ----------- ReturnT:ReturnT [code=200, msg=null, content=null] 2020-09-15 10:48:34 [com.xxl.job.core.thread.TriggerCallbackThread#callbackLog]-[133]-[Thread-39] ----------- xxl-job callback success [Load Log Finish]
3. 总结
XXL-JOB是一个轻量级分布式任务调度平台,其核心设计目标是开发迅速、学习简单、轻量级、易扩展。具体参考 xxl-job。
.NET Core 主打的是跨平台、开源、强劲性能、多样化部署方案等,.netcore详细介绍可以去看善友老师的博客
缓存使用谷歌protobuf协议存储结构,方便跨平台跨语言调用