예제 #1
0
        /// <summary>
        /// 开始set
        /// </summary>
        private bool TrySetValue(Command command, string key, byte[] value, byte flag, TimeSpan expireTime)
        {
            if (expireTime < TimeSpan.Zero)
            {
                return(true);
            }

            if (key.IsNullOrWhiteSpace())
            {
                return(false);
            }

            var hv   = this.SumASCII(key);
            var sort = this.SortServer(hv, this.connectionPools.Length);

            foreach (var s in sort)
            {
                if (dodo(this.connectionPools[s]))
                {
                    return(true);
                }
            }

            return(false);

            //开始set
            bool dodo(ConnectionPool pool)
            {
                var request = BinaryConvert.AddRequest(command, key, value, flag, this.GetTotalSecond(expireTime));
                var item    = pool.Alloc();

                try
                {
                    item.Connection.Write(request);
                    item.Connection.Flush();
                    var @byte  = item.Connection.Read(24);
                    var status = BinaryConvert.ParseStatus(@byte);
                    switch ((BinaryProtocols.ResponseStatus)status)
                    {
                    case BinaryProtocols.ResponseStatus.NoError:
                    {
                        return(true);
                    }

                    case BinaryProtocols.ResponseStatus.KeyExists:
                    {
                        //主要是这里引出不同
                        return(command == Command.add ? false : true);
                    }

                    case BinaryProtocols.ResponseStatus.KeyNotFound:
                    {
                        if (this.LoggerBuilder == null)
                        {
                            return(false);
                        }

                        this.LoggerBuilder().Build(typeof(TextCached)).Info(string.Concat(command, "key", key, "not stored"));
                        return(false);
                    }

                    default:
                    {
                        if (this.LoggerBuilder != null)
                        {
                            this.LoggerBuilder().Build(typeof(TextCached)).Info(string.Concat(command, "key", key, "status:", status));
                        }

                        return(false);
                    }
                    }
                }
                catch (Exception)
                {
                    return(false);
                }
                finally
                {
                    pool.Recycle(item);
                }
            }
        }