Пример #1
0
 public SingleTempAdapter(RedisClient topOwner, IRedisSocket redisSocket, Action dispose)
 {
     UseType      = UseType.SingleInside;
     TopOwner     = topOwner;
     _redisSocket = redisSocket;
     _dispose     = dispose;
 }
Пример #2
0
 public SingleTempAdapter(RedisClient cli, IRedisSocket redisSocket, Action dispose)
 {
     UseType      = UseType.SingleInside;
     _cli         = cli;
     _redisSocket = redisSocket;
     _dispose     = dispose;
 }
 public PoolRedisClient(IRedisSocket socket, EndPoint endpoint, int max = 100)
 {
     _socket    = socket;
     _endpoint  = endpoint;
     _pool      = new ConcurrentQueue <RedisClient>();
     _semaphore = new SemaphoreSlim(max, max);
 }
Пример #4
0
 internal static TempProxyRedisSocket CreateTempProxy(IRedisSocket rds, Action dispose)
 {
     if (rds is TempProxyRedisSocket proxy)
     {
         return(new TempProxyRedisSocket(proxy._owner, dispose));
     }
     return(new TempProxyRedisSocket(rds, dispose));
 }
Пример #5
0
        internal RedisClient(IRedisSocket socket, EndPoint endpoint, int asyncConcurrency, int asyncBufferSize)
        {
            _connector = new RedisConnector(endpoint, socket, asyncConcurrency, asyncBufferSize);
            //   _transaction = new RedisTransaction(_connector);
            //   _monitor = new MonitorListener(_connector);

            _connector.Connected += OnConnectionConnected;
        }
 public void TryMulti()
 {
     if (_redisSocket == null)
     {
         _redisSocket = _cli._adapter.GetRedisSocket(null);
         SelfCall("MULTI");
     }
 }
Пример #7
0
 public void TryMulti()
 {
     if (_redisSocket == null)
     {
         _redisSocket = TopOwner.Adapter.GetRedisSocket(null);
         SelfCall("MULTI");
     }
 }
Пример #8
0
 public AsyncRedisSocket(IRedisSocket rds, Action begin, Action <IRedisSocket, Exception> end, Func <bool> finish)
 {
     _rds          = rds;
     _begin        = begin;
     _end          = end;
     _finish       = finish;
     _writeCounter = 0;
 }
Пример #9
0
 public RedisConnector(EndPoint endPoint, IRedisSocket socket, int concurrency, int bufferSize)
 {
     _concurrency = concurrency;
     _bufferSize  = bufferSize;
     _endPoint    = endPoint;
     _redisSocket = socket;
     _io          = new RedisIO();
     //_autoPipeline = new AutoPipelineOption(_io);
 }
Пример #10
0
            public override void Refersh(IRedisSocket redisSocket)
            {
                var tmprds = redisSocket as DefaultRedisSocket.TempProxyRedisSocket;

                if (tmprds != null)
                {
                    _ib.Get(tmprds._poolkey);
                }
            }
Пример #11
0
 public RedisConnector(EndPoint endPoint, IRedisSocket socket, int concurrency, int bufferSize)
 {
     _concurrency    = concurrency;
     _bufferSize     = bufferSize;
     _endPoint       = endPoint;
     _redisSocket    = socket;
     _io             = new RedisIO();
     _asyncConnector = new Lazy <AsyncConnector>(AsyncConnectorFactory);
 }
        internal RedisSentinelClient(IRedisSocket socket, EndPoint endpoint, int concurrency, int bufferSize)
        {
            _connector    = new RedisConnector(endpoint, socket, concurrency, bufferSize);
            _subscription = new SubscriptionListener(_connector);

            _subscription.MessageReceived += OnSubscriptionReceived;
            _subscription.Changed         += OnSubscriptionChanged;
            _connector.Connected          += OnConnectionReconnected;
        }
Пример #13
0
            bool SentinelBackgroundGetMasterHost(IRedisSocket rds)
            {
                if (rds == null)
                {
                    return(false);
                }
                //if (rds._host != _masterHost) return false;

                var ing = false;

                if (SentinelBackgroundGetMasterHostIng == false)
                {
                    lock (SentinelBackgroundGetMasterHostIngLock)
                    {
                        if (SentinelBackgroundGetMasterHostIng == false)
                        {
                            SentinelBackgroundGetMasterHostIng = ing = true;
                        }
                    }
                }

                if (ing)
                {
                    new Thread(() =>
                    {
                        while (true)
                        {
                            Thread.CurrentThread.Join(1000);
                            try
                            {
                                ResetSentinel();

                                if (_ib.Get(_masterHost).CheckAvailable())
                                {
                                    var bgcolor             = Console.BackgroundColor;
                                    var forecolor           = Console.ForegroundColor;
                                    Console.BackgroundColor = ConsoleColor.DarkGreen;
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.Write($"Redis Sentinel Pool 已切换至 {_masterHost}");
                                    Console.BackgroundColor = bgcolor;
                                    Console.ForegroundColor = forecolor;
                                    Console.WriteLine();

                                    SentinelBackgroundGetMasterHostIng = false;
                                    return;
                                }
                            }
                            catch (Exception ex21)
                            {
                                Console.WriteLine($"Redis Sentinel: {ex21.Message}");
                            }
                        }
                    }).Start();
                }
                return(ing);
            }
 public SingleInsideAdapter(RedisClient cli, string host, bool ssl, TimeSpan connectTimeout, TimeSpan receiveTimeout, TimeSpan sendTimeout, Action <RedisClient> connected)
 {
     UseType                     = UseType.SingleInside;
     _cli                        = cli;
     _redisSocket                = new DefaultRedisSocket(host, ssl);
     _redisSocket.Connected     += (s, e) => connected(cli);
     _redisSocket.ConnectTimeout = connectTimeout;
     _redisSocket.ReceiveTimeout = receiveTimeout;
     _redisSocket.SendTimeout    = sendTimeout;
 }
Пример #15
0
 public SingleInsideAdapter(RedisClient topOwner, RedisClient owner, string host, bool ssl, TimeSpan connectTimeout, TimeSpan receiveTimeout, TimeSpan sendTimeout, Action <RedisClient> connected)
 {
     UseType                     = UseType.SingleInside;
     TopOwner                    = topOwner;
     _redisSocket                = new DefaultRedisSocket(host, ssl);
     _redisSocket.Connected     += (s, e) => connected?.Invoke(owner);
     _redisSocket.ConnectTimeout = connectTimeout;
     _redisSocket.ReceiveTimeout = receiveTimeout;
     _redisSocket.SendTimeout    = sendTimeout;
 }
Пример #16
0
            static void EndPipe(IRedisSocket rds, IEnumerable <PipelineCommand> cmds)
            {
                var err = new List <PipelineCommand>();
                var ms  = new MemoryStream();

                try
                {
                    var respWriter = new RespHelper.Resp3Writer(ms, rds.Encoding, rds.Protocol);
                    foreach (var cmd in cmds)
                    {
                        respWriter.WriteCommand(cmd.Command);
                    }

                    if (rds.IsConnected == false)
                    {
                        rds.Connect();
                    }
                    ms.Position = 0;
                    ms.CopyTo(rds.Stream);

                    foreach (var pc in cmds)
                    {
                        pc.RedisResult = rds.Read(pc.IsBytes);
                        pc.Result      = pc.Parse(pc.RedisResult);
                        if (pc.RedisResult.IsError)
                        {
                            err.Add(pc);
                        }
#if net40
#else
                        pc.TrySetResult(pc.Result, pc.RedisResult.IsError ? new RedisServerException(pc.RedisResult.SimpleError) : null);
#endif
                    }
                }
                finally
                {
                    ms.Close();
                    ms.Dispose();
                }

                if (err.Any())
                {
                    var sb = new StringBuilder();
                    for (var a = 0; a < err.Count; a++)
                    {
                        var cmd = err[a].Command;
                        if (a > 0)
                        {
                            sb.Append("\r\n");
                        }
                        sb.Append(err[a].RedisResult.SimpleError).Append(" {").Append(cmd.ToString()).Append("}");
                    }
                    throw new RedisServerException(sb.ToString());
                }
            }
Пример #17
0
 public AsyncRedisSocket(IRedisSocket rds)
 {
     _rds = rds;
     _oldReceiveTimeout  = _rds.ReceiveTimeout;
     _rds.ReceiveTimeout = TimeSpan.Zero;
     if (rds.IsConnected == false)
     {
         rds.Connect();
     }
     StartRead();
 }
Пример #18
0
 public void Discard()
 {
     if (_redisSocket == null)
     {
         return;
     }
     SelfCall("DISCARD");
     _commands.Clear();
     _redisSocket?.Dispose();
     _redisSocket = null;
 }
        public RedisClient(IRedisSocket socket, EndPoint endpoint, int asyncConcurrency, int asyncBufferSize)
        {
            _connector    = new RedisConnector(endpoint, socket, asyncConcurrency, asyncBufferSize);
            _transaction  = new RedisTransaction(_connector);
            _subscription = new SubscriptionListener(_connector);
            _monitor      = new MonitorListener(_connector);

            _subscription.MessageReceived  += OnSubscriptionReceived;
            _subscription.Changed          += OnSubscriptionChanged;
            _monitor.MonitorReceived       += OnMonitorReceived;
            _connector.Connected           += OnConnectionConnected;
            _transaction.TransactionQueued += OnTransactionQueued;
        }
Пример #20
0
            static void EndPipe(IRedisSocket rds, IEnumerable <PipelineCommand> cmds)
            {
                var err = new List <PipelineCommand>();
                var ms  = new MemoryStream();

                try
                {
                    foreach (var cmd in cmds)
                    {
                        RespHelper.Write(ms, rds.Encoding, cmd.Command, rds.Protocol);
                    }

                    if (rds.IsConnected == false)
                    {
                        rds.Connect();
                    }
                    ms.Position = 0;
                    ms.CopyTo(rds.Stream);

                    foreach (var pc in cmds)
                    {
                        pc.Command._redisSocket = rds;
                        pc.Result = pc.Parse(pc);
                        if (pc.Command.ReadResult.IsError)
                        {
                            err.Add(pc);
                        }
                    }
                }
                finally
                {
                    ms.Close();
                    ms.Dispose();
                    rds?.Dispose();
                }

                if (err.Any())
                {
                    var sb = new StringBuilder();
                    for (var a = 0; a < err.Count; a++)
                    {
                        var cmd = err[a].Command;
                        if (a > 0)
                        {
                            sb.Append("\r\n");
                        }
                        sb.Append(cmd.ReadResult.SimpleError).Append(" {").Append(cmd.ToString()).Append("}");
                    }
                    throw new RedisException(sb.ToString());
                }
            }
Пример #21
0
            void TryReset()
            {
                if (_redisSocket == null)
                {
                    return;
                }
#if isasync
                for (var a = 0; a < _commands.Count; a++)
                {
                    _commands[a].TrySetCanceled();
                }
#endif
                _commands.Clear();
                _redisSocket?.Dispose();
                _redisSocket = null;
            }
Пример #22
0
        internal RedisClient(IRedisSocket socket, EndPoint endpoint, int asyncConcurrency, int asyncBufferSize)
        {
            // use invariant culture - we have to set it explicitly for every thread we create to
            // prevent any floating-point problems (mostly because of number formats in non en-US cultures).
            //CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; 这行会影响 string.Compare 结果

            _connector    = new RedisConnector(endpoint, socket, asyncConcurrency, asyncBufferSize);
            _transaction  = new RedisTransaction(_connector);
            _subscription = new SubscriptionListener(_connector);
            _monitor      = new MonitorListener(_connector);

            _subscription.MessageReceived  += OnSubscriptionReceived;
            _subscription.Changed          += OnSubscriptionChanged;
            _monitor.MonitorReceived       += OnMonitorReceived;
            _connector.Connected           += OnConnectionConnected;
            _transaction.TransactionQueued += OnTransactionQueued;
        }
Пример #23
0
 public AsyncConnector(IRedisSocket socket, EndPoint endpoint, RedisIO io, int concurrency, int bufferSize)
 {
     _redisSocket                  = socket;
     _io                           = io;
     _concurrency                  = concurrency;
     _bufferSize                   = bufferSize;
     _asyncTransferPool            = new SocketAsyncPool(concurrency, bufferSize);
     _asyncTransferPool.Completed += OnSocketCompleted;
     _asyncReadQueue               = new ConcurrentQueue <IRedisAsyncCommandToken>();
     _asyncWriteQueue              = new ConcurrentQueue <IRedisAsyncCommandToken>();
     _readLock                     = new object();
     _writeLock                    = new object();
     _asyncConnectArgs             = new SocketAsyncEventArgs {
         RemoteEndPoint = endpoint
     };
     _asyncConnectArgs.Completed += OnSocketCompleted;
     _connectionTaskSource        = new ConcurrentQueue <TaskCompletionSource <bool> >();
 }
Пример #24
0
 public RedisSentinelClient(ConnectionStringBuilder connectionString)
 {
     _redisSocket = new DefaultRedisSocket(connectionString.Host, connectionString.Ssl);
     _redisSocket.ReceiveTimeout = connectionString.ReceiveTimeout;
     _redisSocket.SendTimeout    = connectionString.SendTimeout;
     _redisSocket.Encoding       = connectionString.Encoding;
     _redisSocket.Connected     += (_, __) =>
     {
         if (!string.IsNullOrEmpty(connectionString.User) && !string.IsNullOrEmpty(connectionString.Password))
         {
             this.Auth(connectionString.User, connectionString.Password);
         }
         else if (!string.IsNullOrEmpty(connectionString.Password))
         {
             this.Auth(connectionString.Password);
         }
     };
 }
Пример #25
0
            public object[] Exec()
            {
                if (_redisSocket == null)
                {
                    return(new object[0]);
                }
                try
                {
                    var ret = SelfCall("EXEC") as object[];

                    for (var a = 0; a < ret.Length; a++)
                    {
                        _commands[a].Result = _commands[a].Parse(ret[a]);
                    }
                    return(_commands.Select(a => a.Result).ToArray());
                }
                finally
                {
                    _commands.Clear();
                    _redisSocket?.Dispose();
                    _redisSocket = null;
                }
            }
Пример #26
0
            internal IDisposable Subscribe(bool psub, string[] channels, Action <string, string, object> handler)
            {
                if (_stoped)
                {
                    return(new PubSubSubscribeDisposable(this, null));
                }
                channels = channels?.Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray(); //In case of external modification
                if (channels?.Any() != true)
                {
                    return(new PubSubSubscribeDisposable(this, null));
                }

                var id      = Guid.NewGuid();
                var time    = DateTime.Now;
                var regkeys = channels.Select(a => psub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();

                for (var a = 0; a < regkeys.Length; a++)
                {
                    ConcurrentDictionary <Guid, RegisterInfo> dict = null;
                    lock (_lock) dict = _registers.GetOrAdd(regkeys[a], k1 => new ConcurrentDictionary <Guid, RegisterInfo>());
                    dict.TryAdd(id, new RegisterInfo(id, handler, time));
                }
                lock (_lock)
                    _cancels.TryAdd(id, regkeys);
                var isnew = false;

                if (IsSubscribed == false)
                {
                    lock (_lock)
                    {
                        if (IsSubscribed == false)
                        {
                            _redisSocket = _topOwner.Adapter.GetRedisSocket(null);
                            IsSubscribed = isnew = true;
                        }
                    }
                }
                if (isnew)
                {
                    new Thread(() =>
                    {
                        _redisSocketReceiveTimeoutOld = _redisSocket.ReceiveTimeout;
                        _redisSocket.ReceiveTimeout   = TimeSpan.Zero;
                        var timer = new Timer(state =>
                        {
                            _topOwner.Adapter.Refersh(_redisSocket); //防止 IdleBus 超时回收
                            try { _redisSocket.Write("PING"); } catch { }
                        }, null, 10000, 10000);
                        var readCmd = "PubSubRead".SubCommand(null).FlagReadbytes(false);
                        while (_stoped == false)
                        {
                            RedisResult rt = null;
                            try
                            {
                                rt = _redisSocket.Read(readCmd);
                            }
                            catch
                            {
                                Thread.CurrentThread.Join(100);
                                if (_cancels.Any())
                                {
                                    continue;
                                }
                                break;
                            }
                            var val = rt.Value as object[];
                            if (val == null)
                            {
                                continue;              //special case
                            }
                            var val1 = val[0].ConvertTo <string>();
                            switch (val1)
                            {
                            case "pong":
                            case "punsubscribe":
                            case "unsubscribe":
                                continue;

                            case "pmessage":
                                OnData(val[1].ConvertTo <string>(), val[2].ConvertTo <string>(), val[3]);
                                continue;

                            case "message":
                                OnData(null, val[1].ConvertTo <string>(), val[2]);
                                continue;
                            }
                        }
                        timer.Dispose();
                        lock (_lock)
                        {
                            IsSubscribed = false;
                            _redisSocket.ReceiveTimeout = _redisSocketReceiveTimeoutOld;
                            _redisSocket.ReleaseSocket();
                            _redisSocket.Dispose();
                            _redisSocket = null;
                        }
                    }).Start();
                }
                Call((psub ? "PSUBSCRIBE" : "SUBSCRIBE").Input(channels));
                return(new PubSubSubscribeDisposable(this, () => Cancel(id)));
            }
Пример #27
0
 internal RedisClient(IRedisSocket socket, EndPoint endpoint)
     : this(socket, endpoint, DefaultConcurrency, DefaultBufferSize)
 {
 }
Пример #28
0
 internal RedisSentinelClient(IRedisSocket socket, EndPoint endpoint)
     : this(socket, endpoint, DefaultConcurrency, DefaultBufferSize)
 { }
Пример #29
0
        internal RedisSentinelClient(IRedisSocket socket, EndPoint endpoint, int concurrency, int bufferSize)
        {
            _connector = new RedisConnector(endpoint, socket, concurrency, bufferSize);
            _subscription = new SubscriptionListener(_connector);

            _subscription.MessageReceived += OnSubscriptionReceived;
            _subscription.Changed += OnSubscriptionChanged;
            _connector.Connected += OnConnectionReconnected;
        }
Пример #30
0
 public TempProxyRedisSocket(IRedisSocket owner, Action dispose)
 {
     _owner   = owner;
     _dispose = dispose;
 }
Пример #31
0
 public override void Refersh(IRedisSocket redisSocket)
 {
 }
Пример #32
0
 public abstract void Refersh(IRedisSocket redisSocket);