c#开发 利用redis作为消息队列(简单测试版)

  • 1.安装开发包

  • 2 创建类

创建接口IRedisCache.cs和RedisCache.cs

using H.Emos.Common.Helper;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace H.Emos.Common.Redis
{
    public class RedisCache : IRedisCache
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private  readonly string ConnectionString;
        /// <summary>
        /// redis 连接对象
        /// </summary>
        private volatile IConnectionMultiplexer redisConnection;
      
        /// <summary>
        /// 锁
        /// </summary>
        private  readonly object redisConnectLock = new object();
        public RedisCache()
        {
            this.ConnectionString = "127.0.0.1:6379,allowadmin=true,password=123456";
            this.redisConnection = getConnection();
        }

        private IConnectionMultiplexer getConnection()
        {
            if(this.redisConnection!=null&&this.redisConnection.IsConnected)
            {
                return this.redisConnection;
            }
            lock(redisConnectLock)
            {
                if(this.redisConnection != null)
                {
                    this.redisConnection.Dispose();
                }
                try
                {
                    this.redisConnection = ConnectionMultiplexer.Connect(this.ConnectionString);
                }
                catch (Exception)
                {

                    throw new Exception("redis 服务未启动") ;
                }
                return this.redisConnection;
                
            }
        }
        public void Clear()
        {
            foreach (var endPoint in this.getConnection().GetEndPoints())
            {
                var server = this.getConnection().GetServer(endPoint);
                foreach (var key in server.Keys())
                {
                    redisConnection.GetDatabase().KeyDelete(key);
                }
            }
        }

        public long publish<T>(string topic, T message)
        {
           var  subscriber= redisConnection.GetSubscriber();
            return subscriber.Publish(topic,SerializeHelper.SerializeString(message));
        }
        public string  subscriber(string topic)
        {
            var msg = string.Empty;
            var subscriber = redisConnection.GetSubscriber();
            subscriber.Subscribe(topic,(channel,message)=> {

                 msg=message;
            });
            return msg;
        }

        public string stringGet(string key)
        {
            return redisConnection.GetDatabase().StringGet(key);
        }

        public bool stringSet(string key, string keyValue,TimeSpan time)
        {
            return redisConnection.GetDatabase().StringSet(key,keyValue,time);
        }

        public bool stringSet<T>(string key, T keyValue,TimeSpan time)
        {
            return redisConnection.GetDatabase().StringSet(key, SerializeHelper.Serialize(keyValue),time);
        }

        public async Task<bool> taskStringSet(string key, string keyValue)
        {
            return await redisConnection.GetDatabase().StringSetAsync(key, keyValue);
        }
    }
}
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace H.Emos.Common.Redis
{
     public interface IRedisCache
    {
        bool stringSet(string key, string keyValue,TimeSpan time);
        string stringGet(string key);
        bool stringSet<T>(string key, T keyVale,TimeSpan time);

        Task<bool> taskStringSet(string key, string keyValue);
        long publish<T>(string topic,T message);
        string subscriber(string topic);
    }
}
  • 3. 依赖注入

在Startup.cs中进行注入

 services.AddSingleton<IRedisCache, RedisCache>();
  • 4.测试

在WeatherForestcastController中构造函数注入,然后测试

  [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
         //   _redisCache.stringSet("test01","test01",TimeSpan.FromHours(5));

            WeatherForecast weatherForecast = new WeatherForecast();
            weatherForecast.Date = DateTime.Now;
            weatherForecast.TemperatureC = rng.Next(-20, 55);
            weatherForecast.Summary = Summaries[rng.Next(2)];
            var value=_redisCache.publish("redisChat",weatherForecast);
          
            var tt= Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();

            return tt;

        }

启动redis客户端,进行订阅。

调用接口:

看控制台输出:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值