コード例 #1
0
        /// <summary>
        /// 获取DB
        /// </summary>
        /// <param name="dbIndex"></param>
        /// <returns></returns>
        public IRedisDataBase GetDatabase(int dbIndex = 0)
        {
            if (redisClient == null)
            {
                throw new CtSharpRedisException("redis 未连接,请先执行 Connect方法");
            }

            var client = RedisClientFactory.GetDatabaseRedisClient(RedisClientFactory.ClientType.Common, options, "", dbIndex, EventNotify);

            return(new RedisDataBase(client, serializeSettings));
        }
コード例 #2
0
        /// <summary>
        /// 订阅
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="action"></param>
        public void Subscribe(string channelName, Action <string, string> action)
        {
            Task.Run(() =>
            {
                RedisClient client = RedisClientFactory.GetDatabaseRedisClient(RedisClientFactory.ClientType.Sub, options, channelName, -1, EventNotify);
                if (!client.IsConnected)
                {
                    throw new CtSharpRedisException("redis 未连接,请先执行 Connect方法");
                }

                client.SubscriptionReceived += (sender, eventArg) =>
                {
                    if (eventArg == null || eventArg.Message == null)
                    {
                        return;
                    }

                    var message  = eventArg.Message;
                    string cname = message.Channel;
                    string msg   = message.Body;
                    try
                    {
                        // 模糊匹配
                        if (cname.Contains("*"))
                        {
                            action(cname, msg);
                        }
                        else
                        {
                            if (cname.Equals(channelName, StringComparison.CurrentCultureIgnoreCase))
                            {
                                action(cname, msg);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        EventNotify($"Subscribe channel {cname} error", e);
                    }
                };
                if (channelName.Contains("*"))
                {
                    client.PSubscribe(channelName);
                }
                else
                {
                    client.Subscribe(channelName);
                }
            });
        }