Exemplo n.º 1
0
        public void Send(IRedisCommand cmd)
        {
            if (cmd == null)
            {
                throw new RedisFatalException(new ArgumentNullException("cmd"), RedisErrorCode.MissingParameter);
            }

            ValidateNotDisposed();
            ValidateRole(cmd.Role);

            var socket = Connect();

            if (socket == null)
            {
                SetLastError((long)SocketError.NotConnected);
                SetState((long)RedisConnectionState.Failed);

                throw new RedisFatalException(new SocketException((int)SocketError.NotConnected), RedisErrorCode.ConnectionError);
            }

            try
            {
                cmd.WriteTo(socket);
            }
            catch (Exception e)
            {
                if (e.IsSocketError())
                {
                    FreeAndNilSocket();
                }
                throw;
            }
        }
        public override RedisRawResponse SendReceive(IRedisCommand cmd)
        {
            if (cmd == null)
            {
                throw new RedisFatalException(new ArgumentNullException("cmd"), RedisErrorCode.MissingParameter);
            }

            ValidateNotDisposed();
            ValidateRole(cmd.Role);

            var socket = Connect();

            if (socket == null)
            {
                SetLastError((long)SocketError.NotConnected);
                SetState((long)RedisConnectionState.Failed);

                throw new SocketException((int)SocketError.NotConnected);
            }

            try
            {
                cmd.WriteTo(socket);
                using (var reader = new RedisSingleResponseReader(Settings))
                    return(reader.Execute(socket));
            }
            catch (Exception e)
            {
                if (e.IsSocketError())
                {
                    FreeAndNilSocket();
                }
                throw;
            }
        }
        public T Cache <T>(IRedisCommand <T> command, Func <T> miss)
        {
            if (!factory.IsEnabled)
            {
                return(miss());
            }

            using (var connection = factory.Open())
            {
                if (connection.IsPassThrough)
                {
                    return(miss());
                }

                if (command.Get(connection, out T item))
                {
                    return(item);
                }

                item = miss();
                command.Set(connection, item);

                return(item);
            }
        }
Exemplo n.º 4
0
 public BacklogItem(IRedisCommand redisCommand, CancellationToken cancellationToken, TaskCompletionSource <T> taskCompletionSource, IResultProcessor <T> resultProcessor)
 {
     RedisCommand         = redisCommand;
     CancellationToken    = cancellationToken;
     TaskCompletionSource = taskCompletionSource;
     ResultProcessor      = resultProcessor;
 }
Exemplo n.º 5
0
        public Task SendAsync(IRedisCommand cmd)
        {
            if (cmd == null)
            {
                throw new RedisFatalException(new ArgumentNullException("cmd"), RedisErrorCode.MissingParameter);
            }

            ValidateNotDisposed();
            ValidateRole(cmd.Role);

            var socket = Connect();

            if (socket == null)
            {
                SetLastError((long)SocketError.NotConnected);
                SetState((long)RedisConnectionState.Failed);

                throw new RedisFatalException(new SocketException((int)SocketError.NotConnected));
            }

            var task = cmd.WriteToAsync(socket);

            task.ContinueWith((asyncTask) =>
            {
                if (asyncTask.IsFaulted && asyncTask.Exception.IsSocketError())
                {
                    FreeAndNilSocket();
                }
            });
            return(task);
        }
Exemplo n.º 6
0
 public BacklogItem(IRedisCommand redisCommand, CancellationToken cancellationToken, TaskCompletionSource <T> taskCompletionSource, AbstractResultProcessor <T> abstractResultProcessor, Client.RedisClient redisClient, PipeReader pipe)
 {
     RedisCommand            = redisCommand;
     CancellationToken       = cancellationToken;
     TaskCompletionSource    = taskCompletionSource;
     AbstractResultProcessor = abstractResultProcessor;
     RedisClient             = redisClient;
     PipeReader = pipe;
 }
Exemplo n.º 7
0
 public IRedisReader Execute(IRedisCommand cmd)
 {
     if (cmd == null) throw new ArgumentNullException("cmd");
     if (cmd.Command == Command.UNKNOWN) throw new ArgumentException("'UNKNOWN' command cannot execute", "cmd");
     if (!mSocket.Connected) mSocket.Connect(mEndPoint);
     byte[] data = cmd.ToBytes();
     int sended = mSocket.Send(data);
     if (sended != data.Length) throw new Exception("send fail");
     return new RedisReader(SocketHelper.ReadAsBytes(mSocket));
 }
Exemplo n.º 8
0
        internal async ValueTask <T> SendAndReceive_Impl <T>(IRedisCommand command, IResultProcessor <T> resultProcessor,
                                                             CancellationToken cancellationToken, bool isReconnectionAttempt)
        {
            IsBusy = true;

            Log.Debug($"Executing Command: {command}");
            LastCommand = command;

            Interlocked.Increment(ref _operationsPerformed);

            try
            {
                if (!isReconnectionAttempt)
                {
                    await _sendAndReceiveSemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);

                    if (!IsConnected)
                    {
                        await TryConnectAsync(cancellationToken).ConfigureAwait(false);
                    }
                }

                await Write(command);

                LastAction = "Reading Bytes Async";

                return(await resultProcessor.Start(this, _pipe));
            }
            catch (Exception innerException)
            {
                if (innerException.IsSameOrSubclassOf(typeof(RedisException)) ||
                    innerException.IsSameOrSubclassOf(typeof(OperationCanceledException)))
                {
                    throw;
                }

                DisposeNetwork();
                IsConnected = false;
                throw new RedisConnectionException(innerException);
            }
            finally
            {
                Interlocked.Decrement(ref _outStandingOperations);
                if (!isReconnectionAttempt)
                {
                    _sendAndReceiveSemaphoreSlim.Release();
                }

                IsBusy = false;
            }
        }
Exemplo n.º 9
0
        private ValueTask <T> QueueToBacklog <T>(IRedisCommand command, IResultProcessor <T> resultProcessor,
                                                 CancellationToken cancellationToken)
        {
            var taskCompletionSource = new TaskCompletionSource <T>();

            var backlogQueueCount = _backlog.Count;

            _backlog.Enqueue(new BacklogItem <T>(command, cancellationToken, taskCompletionSource, resultProcessor));

            if (backlogQueueCount == 0)
            {
                StartBacklogProcessor();
            }

            return(new ValueTask <T>(taskCompletionSource.Task));
        }
        public void Execute(IRedisCommand command)
        {
            if (!factory.IsEnabled)
            {
                return;
            }

            using (var connection = factory.Open())
            {
                if (connection.IsPassThrough)
                {
                    return;
                }

                command.Execute(connection);
            }
        }
Exemplo n.º 11
0
        //[MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal ValueTask <T> SendAndReceiveAsync <T>(IRedisCommand command,
                                                       IResultProcessor <T> resultProcessor,
                                                       CancellationToken cancellationToken,
                                                       bool isReconnectionAttempt = false)
        {
            LastUsed = DateTime.Now;

            LastAction = "Throwing Cancelled Exception due to Cancelled Token";
            cancellationToken.ThrowIfCancellationRequested();

            Interlocked.Increment(ref _outStandingOperations);

            if (!isReconnectionAttempt && CanQueueToBacklog && IsBusy)
            {
                return(QueueToBacklog(command, resultProcessor, cancellationToken));
            }

            return(SendAndReceive_Impl(command, resultProcessor, cancellationToken, isReconnectionAttempt));
        }
Exemplo n.º 12
0
        internal ValueTask <FlushResult> Write(IRedisCommand command)
        {
            var encodedCommandList = command.EncodedCommandList;

            LastAction = "Writing Bytes";
            var pipeWriter = _pipe.Output;

#if NETCORE
            foreach (var encodedCommand in encodedCommandList)
            {
                var bytesSpan = pipeWriter.GetSpan(encodedCommand.Length);
                encodedCommand.CopyTo(bytesSpan);
                pipeWriter.Advance(encodedCommand.Length);
            }

            return(Flush());
#else
            return(pipeWriter.WriteAsync(encodedCommandList.SelectMany(x => x).ToArray().AsMemory()));
#endif
        }
Exemplo n.º 13
0
 public virtual RedisRawResponse SendReceive(IRedisCommand cmd)
 {
     ValidateNotDisposed();
     throw new RedisFatalException("SendAndReceive is not supported by base connection. Use Send method for sending command.", RedisErrorCode.NotSupported);
 }
 public ValueTask SendAsync(IRedisCommand message)
 {
     return(_writer.WriteAsync(_commandWriter, message));
 }
Exemplo n.º 15
0
 public IRedisReader Execute(IRedisCommand cmd)
 {
     return mDb.Execute(cmd);
 }
 public RedisFailedCommandException(string message, IRedisCommand lastCommand)
 {
     Message = $"{message}\nLast Command: {lastCommand.AsString}";
 }
Exemplo n.º 17
0
 /// <summary>
 /// execute redis command
 /// </summary>
 /// <param name="cmd">command</param>
 /// <returns>data reader</returns>
 public IRedisReader Execute(IRedisCommand cmd)
 {
     lock (LockThis)
     {
         return Client.Execute(cmd);
     }
 }
Exemplo n.º 18
0
 public override RedisRawResponse SendReceive(IRedisCommand cmd)
 {
     ValidateNotDisposed();
     throw new NotImplementedException("SendAndReceive is not supported by continuous reader connections. Use Send method for sending command.");
 }