C# Redis发布订阅无法正常工作

C# Redis发布订阅无法正常工作,c#,publish-subscribe,stackexchange.redis,C#,Publish Subscribe,Stackexchange.redis,我无法从pub/sub StackExchange.Redis功能中获得优势。 这是我的密码 控制台应用程序 using StackExchange.Redis; using System; using System.Data; namespace RedisHashSets { class Program { static void Main(string[] args) { #region Prepare Data

我无法从pub/sub StackExchange.Redis功能中获得优势。 这是我的密码

控制台应用程序

using StackExchange.Redis;
using System;
using System.Data;

namespace RedisHashSets
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Prepare Data

            var exampleData = new DataTable();
            exampleData.Columns.Add("session_guid", typeof(String));
            exampleData.Columns.Add("status_code", typeof(String));
            exampleData.Columns.Add("date_open", typeof(DateTime));
            exampleData.Columns.Add("date_expiry", typeof(DateTime));
            exampleData.Columns.Add("extra_id", typeof(long));
            exampleData.Columns.Add("current_real_balance", typeof(Decimal));

            DataRow row = exampleData.NewRow();
            row[0] = Guid.NewGuid();
            row[1] = 1;
            row[2] = DateTime.Now;
            row[3] = DateTime.Now.AddMinutes(30);
            row[4] = 44567;
            row[5] = 10.34;

            exampleData.Rows.Add(row);

            #endregion

            var redisClient = RedisProvider.Instance;
            string guid = Guid.NewGuid().ToString();

            // Add an Entry
            redisClient.Set(guid, RedisDataMapper.GetHashSet(exampleData)[0]);

            // Modify an Entry
            HashEntry entry = new HashEntry("exrta_id", 338349);
            redisClient.Set(guid, entry);

            // Get an Entry
            HashSet val = redisClient.Get(guid);

            //Invalidate the key
            redisClient.redisPubSub.Publish("InvalidateBalances", guid);
        }
    }
}
Redis单音客户端

namespace RedisHashSets
{
    /// <summary>
    /// Provide access to the Redis capabilites used to store sesion. Used as a Singleton
    /// </summary>
    public class RedisProvider
    {
        #region Private Fields

        private readonly static Lazy<RedisProvider> lazyObj = new Lazy<RedisProvider>(() => new RedisProvider());
        private ConnectionMultiplexer redisClient;
        private IDatabase redisDatabase;
        private IServer currentServer;
        private EndPoint[] endPoints;

        #endregion  Private Fields

        #region Public Fields

        public static RedisProvider Instance { get { return lazyObj.Value; } }
        public ISubscriber redisPubSub;

        public bool IsRedisEnableByConfig { get; set; }

        #endregion Public Fields

        #region Public Methods

        private RedisProvider()
        {
            if (!lazyObj.IsValueCreated)
            {
                var conf = RedisConfig.GetConfiguration();
                if (conf is null)
                {
                    IsRedisEnableByConfig = false;
                }
                else
                {
                    IsRedisEnableByConfig = true;
                    redisClient = ConnectionMultiplexer.Connect(conf);
                    redisDatabase = redisClient.GetDatabase(0);
                    endPoints = redisClient.GetEndPoints();
                    currentServer = redisClient.GetServer(endPoints.First());

                    ManageSubscriber();
                }
            }
        }

        private void ManageSubscriber()
        {
            redisPubSub = redisClient.GetSubscriber();
            redisPubSub.Subscribe(new RedisChannel("InvalidateBalances", RedisChannel.PatternMode.Pattern), (channel, message) => MessageAction(message));
        }

        private void MessageAction(RedisValue message)
        {
            HashEntry updatedEntry = new HashEntry(HashSet.IsUpdatedFlag, false);
            Set(message, updatedEntry);
        }

        public void Set(string key, HashSet value)
        {
            redisDatabase.HashSet(key, value.Entries);
            Set(key, value.IsUpdated);
        }

        public void Set(string key, HashEntry value)
        {
            redisDatabase.HashSet(key, value.Name, value.Value);
        }

        /// <summary>
        /// Get a value from Redis.
        /// </summary>
        /// <param name="key">The key of the vaule to retrive</param>
        /// <returns>Cast the value and retrurn a strongly typed object</returns>
        public HashSet Get(string key)
        {
            HashEntry[] value = redisDatabase.HashGetAll(key);
            return new HashSet(value.Length) { Entries = value };
        }

        /// <summary>
        /// Check if a value is in stored or not expired. Time consuming. Use onky if necessary.
        /// </summary>
        /// <param name="key">The key of the value</param>
        public bool IsInCache(string key)
        {
            return redisDatabase.KeyExists(key);
        }

        /// <summary>
        /// Remove a value from the cache.
        /// </summary>
        /// <param name="key">The key to remove</param>
        public bool Remove(string key)
        {
            return redisDatabase.KeyDelete(key);
        }

        /// <summary>
        /// Return the number of active keys stored inside the redis databaase.
        /// </summary>
        public int GetKeysNumber()
        {
            var retVal = 0;
            retVal = currentServer.Keys().Count();
            return retVal;
        }

        /// <summary>
        /// Return an enumerable of all the Keys.
        /// </summary>
        public IEnumerable<string> GetKeys()
        {
            return currentServer.Keys().Select(k => k.ToString());
        }

        #endregion
    }
}
命名空间重新散列集
{
/// 
///提供对用于存储sesion的Redis功能的访问。用作单例
/// 
公共类再贴现提供者
{
#区域专用字段
private readonly static Lazy lazyObj=new Lazy(()=>new RedisProvider());
专用连接多路复用器客户端;
私有IDatabase数据库;
专用服务器;
私有端点[]端点;
#端域专用字段
#区域公共领域
公共静态RedisProvider实例{get{return lazyObj.Value;}}
公共ISubscriber redisPubSub;
公共bool是可编辑的ByConfig{get;set;}
#端域公共字段
#区域公共方法
私人再贴现提供者()
{
如果(!lazyObj.IsValueCreated)
{
var conf=RedisConfig.GetConfiguration();
if(conf为空)
{
IsRedisEnableByConfig=false;
}
其他的
{
IsRedisEnableByConfig=true;
redisClient=ConnectionMultiplexer.Connect(conf);
redisDatabase=redisClient.GetDatabase(0);
endPoints=redisClient.GetEndPoints();
currentServer=redisClient.GetServer(endPoints.First());
ManageSubscriber();
}
}
}
私有void ManageSubscriber()
{
redisPubSub=redisClient.GetSubscriber();
redisPubSub.Subscribe(新的RedisChannel(“InvalidateBalances”,RedisChannel.PatternMode.Pattern),(通道,消息)=>MessageAction(消息));
}
私有void消息操作(RedisValue消息)
{
HashEntry updatedEntry=新的HashEntry(HashSet.IsUpdatedFlag,false);
设置(消息、更新尝试);
}
公共无效集(字符串键、哈希集值)
{
redisDatabase.HashSet(key、value.Entries);
Set(key,value.IsUpdated);
}
公共无效集(字符串键、HashEntry值)
{
redisDatabase.HashSet(key、value.Name、value.value);
}
/// 
///从Redis获取一个值。
/// 
///价值的关键在于检索
///强制转换值并重新生成强类型对象
公共HashSet Get(字符串键)
{
HashEntry[]值=redisDatabase.HashGetAll(键);
返回新的HashSet(value.Length){Entries=value};
}
/// 
///检查值是否已存储或未过期。耗时。如有必要,请使用onky。
/// 
///价值的关键
公共布尔码IsInCache(字符串键)
{
返回redisDatabase.KeyExists(key);
}
/// 
///从缓存中删除值。
/// 
///要移除的关键
公共布尔删除(字符串键)
{
返回redisDatabase.KeyDelete(key);
}
/// 
///返回存储在redis databaase中的活动密钥数。
/// 
public int GetKeysNumber()
{
var-retVal=0;
retVal=currentServer.Keys().Count();
返回返回;
}
/// 
///返回所有键的可枚举项。
/// 
公共IEnumerable GetKeys()
{
返回currentServer.Keys().Select(k=>k.ToString());
}
#端区
}
}
当我发布消息时,订阅者不会捕获它。 你能帮我吗?

试试看。 您的代码使用“localhost”作为连接字符串,即

 redisClient = ConnectionMultiplexer.Connect("localhost");
这是在控制台应用程序中为我工作的代码的最低版本

using StackExchange.Redis;
using System;
using System.Linq;
using System.Net;

namespace RedisHashSets
{
    class Program
    {
        static void Main(string[] args)
        {
            var redisClient = RedisProvider.Instance;
            for (int i = 0; i < 10; i++)
            {
                //Thread.Sleep(100);
                redisClient.redisPubSub.Publish("InvalidateBalances", Guid.NewGuid().ToString());
            }
            Console.ReadLine();
        }
    }


    public class RedisProvider
    {
        #region Private Fields

        private static readonly Lazy<RedisProvider> lazyObj = new Lazy<RedisProvider>(() => new RedisProvider());
        private ConnectionMultiplexer redisClient;
        private IDatabase redisDatabase;
        private IServer currentServer;
        private EndPoint[] endPoints;


        public static RedisProvider Instance => lazyObj.Value;
        public ISubscriber redisPubSub;

        public bool IsRedisEnableByConfig { get; set; }

        private RedisProvider()
        {
            if (!lazyObj.IsValueCreated)
            {
                IsRedisEnableByConfig = true;
                redisClient = ConnectionMultiplexer.Connect("localhost");
                endPoints = redisClient.GetEndPoints();

                currentServer = redisClient.GetServer(endPoints.First());
                ManageSubscriber();
            } 
        }

        private void ManageSubscriber()
        {
            redisPubSub = redisClient.GetSubscriber();
            redisPubSub.Subscribe(new RedisChannel("InvalidateBalances", RedisChannel.PatternMode.Pattern), (channel, message) => MessageAction(message));
        }

        private void MessageAction(RedisValue message)
        {
            Console.WriteLine("msg arrived: " + message);
        }

        #endregion
    }
}
使用StackExchange.Redis;
使用制度;
使用System.Linq;
Net系统;
命名空间重新散列集
{
班级计划
{
静态void Main(字符串[]参数)
{
var redisClient=RedisProvider.Instance;
对于(int i=0;i<10;i++)
{
//睡眠(100);
redisClient.redisPubSub.Publish(“InvalidateBalances”,Guid.NewGuid().ToString());
}
Console.ReadLine();
}
}
公共类再贴现提供者
{
#区域专用字段
private static readonly Lazy lazyObj=new Lazy(()=>new RedisProvider());
专用连接多路复用器客户端;
私有IDatabase数据库;
专用服务器;
私有端点[]端点;
公共静态RedisProvider实例=>lazyObj.Value;
公共ISubscriber redisPubSub;
公共bool是可编辑的ByConfig{get;set;}
私人再贴现提供者()
{
如果(!lazyObj.IsValueCreated)
{
IsRedisEnableByConfig=true;
redisClient=ConnectionMultiplexer.Connect(“localhost”);
endPoints=redisClient.GetEndPoints();
currentServer=redisClient.GetServer(endPoints.First());
ManageSubscriber();
} 
}
私有void ManageSubscriber()
{
redisPubSub=redisClient.GetSubscriber();
redisPubSub.Subscribe(新的RedisChannel(“InvalidateBalances”,RedisChannel.PatternMode.Pattern),(通道,消息)=>MessageAction(消息));
}
私有void消息操作(RedisValue消息)
{
Console.WriteLine(“消息到达:+消息”);
}
#端区
}
}
另外,请保留您的代码示例

尝试检查您。 你的鳕鱼