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

  • 1.安装开发包

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
    {
        /// 
        /// 连接字符串
        /// 
        private  readonly string ConnectionString;
        /// 
        /// redis 连接对象
        /// 
        private volatile IConnectionMultiplexer redisConnection;
      
        /// 
        /// 锁
        /// 
        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(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(string key, T keyValue,TimeSpan time)
        {
            return redisConnection.GetDatabase().StringSet(key, SerializeHelper.Serialize(keyValue),time);
        }

        public async Task 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(string key, T keyVale,TimeSpan time);

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

在Startup.cs中进行注入

 services.AddSingleton();
  • 4.测试

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

  [HttpGet]
        public IEnumerable 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客户端,进行订阅。

c#开发 利用redis作为消息队列(简单测试版)_第2张图片

调用接口:

c#开发 利用redis作为消息队列(简单测试版)_第3张图片

看控制台输出:

c#开发 利用redis作为消息队列(简单测试版)_第4张图片

你可能感兴趣的:(.net,core,开发,redis,队列)