这篇文章主要为大家详细介绍了 redis 实现简单队列的相关资料, 具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Redis 是一个开源的使用 ANSI C 语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 数据库,并提供多种语言的 API。
在工作中,时常会有用到队列的场景,比较常见的用 rabbitMQ 这些专业的组件,官网地址是:http://www.rabbitmq.com,重要的是官方有. net 的客户端,但是如果对 rabbitMQ 不熟悉的话,建议使用第三方封装好的 EasyNetQ,rabbitMQ 比较适合对安全性,稳定性要求较高的地方,但有时我们也会有对这方面要求不是很高的场景,比如:文章阅读数,实时性要求不是很高的地方,所以我想到了用 redis 来做队列。
redis 的 List 结构本身就是一个链表 (双向链表),所以符合我们的队列先进先出的要求。
我用的是 StackExchange.Redis 这个组件来操作 redis,以前一直用 Service.Stack.Redis, 后来该类库升级后对个人使用有次数限制,需要付费使用才能没有调用限制.
操作 redis 简单封装如下:
- public static class RedisHelper
- {
- public static int i = 0;
- private static string redisConnectionString = ConfigurationManager.AppSettings["RedisConnectionString"].ToString();
- private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
- {
- i++;
- return ConnectionMultiplexer.Connect(redisConnectionString);
- });
- public static ConnectionMultiplexer Instance
- {
- get
- {
- return lazyConnection.Value;
- }
- }
- }
有了这个操作类后,我们就可以操作 redis 了,简单的对 list 的操作如下:
- /// <summary>
- /// 简单 redis 队列
- /// </summary>
- public class SimpleRedisQueue
- {
- public void LeftPush(string key, string value)
- {
- var redis = RedisHelper.Instance.GetDatabase();
- redis.ListLeftPush(key, value);
- }
- public string RightPop(string key)
- {
- var redis = RedisHelper.Instance.GetDatabase();
- return redis.ListRightPop(key);
- }
- }
测试代码如下:
首先需要一个生产数据的程序
- static void Main(string[] args)
- {
- System.Threading.Tasks.Task.Factory.StartNew(() =>
- {
- for (var i = 0; i < 99999999; i++)
- {
- new WLX.SimpleUtil.Redis.SimpleRedisQueue().LeftPush("test1", "a_" + i.ToString());
- }
- });
- System.Threading.Tasks.Task.Factory.StartNew(() =>
- {
- for (var i = 0; i < 99999999; i++)
- {
- new WLX.SimpleUtil.Redis.SimpleRedisQueue().LeftPush("test1", "b_" + i.ToString());
- }
- });
- System.Threading.Tasks.Task.Factory.StartNew(() =>
- {
- for (var i = 0; i < 9999; i++)
- {
- new WLX.SimpleUtil.Redis.SimpleRedisQueue().LeftPush("test1", "c_" + i.ToString());
- }
- });
- System.Threading.Tasks.Task.Factory.StartNew(() =>
- {
- for (var i = 0; i < 99999999; i++)
- {
- new WLX.SimpleUtil.Redis.SimpleRedisQueue().LeftPush("test1", "e_" + i.ToString());
- }
- });
- System.Threading.Tasks.Task.Factory.StartNew(() =>
- {
- for (var i = 0; i < 99999999; i++)
- {
- new WLX.SimpleUtil.Redis.SimpleRedisQueue().LeftPush("test1", "f_" + i.ToString());
- }
- });
- Console.ReadKey();
- }
然后有消费队列的程序:
- static void Main(string[] args)
- {
- var queue = new SimpleRedisQueue();
- while (true)
- {
- var v = queue.RightPop("test1");
- Console.WriteLine(v == null ? "空" : v);
- }
- }
测试结果截图
对可靠性和稳定性要求不高的应用场景,可以使用 redis 简单方便的实现。
来源: http://www.phperz.com/article/17/0318/302514.html