예제 #1
0
        public void Add(params KeyValuePair <TKey, TValue>[] pairs)
        {
            var entities = pairs.Select(t => new HashEntry(RedisValue.Unbox(t.Key), Serializer.Serialize(t.Value)))
                           .ToArray();

            Database.HashSet(SetKey, entities);
        }
예제 #2
0
        public void Add(params Tuple <TKey, TValue>[] tuples)
        {
            var entities = tuples.Select(t => new HashEntry(RedisValue.Unbox(t.Item1), Serializer.Serialize(t.Item2)))
                           .ToArray();

            Database.HashSet(SetKey, entities);
        }
예제 #3
0
        /// <summary>
        /// 删除全部标记
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public virtual bool RemoveAllTags(string entityId)
        {
            var tags = this.GetTags(entityId).Select(t => RedisValue.Unbox(t)).ToArray();

            _indexSet.Remove(entityId, tags);
            return(Remove(entityId));
        }
예제 #4
0
        /// <summary>
        /// 删除集合时 同时从索引中迁移键值到 过期索引中 的批处理方法
        /// </summary>
        /// <param name="batch"></param>
        /// <param name="key"></param>
        /// <param name="expiry"></param>
        /// <returns></returns>
        protected Task <bool> ExpireBatch(IBatch batch, TKey key, TimeSpan?expiry)
        {
            var setKey = GetEntryKey(key);

            batch.SetMoveAsync(_indexSet.SetKey, _expireIndexSet.SetKey, RedisValue.Unbox(key));
            return(batch.KeyExpireAsync(setKey, expiry));
        }
예제 #5
0
        public async Task PublishTests(object value)
        {
            var connection = ConfigurationHelper.GetNewConnection();
            var library    = new MemoScriptLibrary(connection);
            var db         = connection.GetDatabase();

            var root       = Guid.NewGuid().ToString().Substring(0, 8);
            var key        = new MemoKey(root, "key", TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
            var parameters = new MemoSetValueParameters(key, RedisValue.Unbox(value));

            try
            {
                await ResetKeys(db, parameters);

                var message = RedisValue.Null;
                await connection.GetSubscriber().SubscribeAsync(parameters.MemoChannelKey, (c, v) => message = v);

                await library.PublishAsync(parameters);

                await Task.Delay(500);

                var expectedValue = value == null ? RedisValue.EmptyString : RedisValue.Unbox(value);
                Assert.Equal(expectedValue, message);
                Assert.Equal(expectedValue, await db.StringGetAsync(parameters.MemoKey));
            }
            finally
            {
                await ResetKeys(db, parameters);
            }
        }
예제 #6
0
        private void MessageRecevied(object sender, MessageEventArgs args)
        {
            Channel = new RedisChannel(args.TopicName, RedisChannel.PatternMode.Auto);
            var channelMessage = new ChannelMessage(null, Channel, RedisValue.Unbox(args.Message.Payload));

            _handler.Invoke(channelMessage);
        }
예제 #7
0
        /// <summary>
        /// 删除全部标记
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public virtual async Task <bool> RemoveAllTagsAsync(string entityId)
        {
            var tags = this.GetTags(entityId).Select(t => RedisValue.Unbox(t)).ToArray();
            await _indexSet.RemoveAsync(entityId, tags);

            return(await RemoveAsync(entityId));
        }
        public NameValueEntry[] ToNameValueEntries()
        {
            //var jobData = this;
            //var nameValues = new NameValueEntry[] {
            //     new NameValueEntry(nameof( JobData.JobId),jobData.JobId?? ""),
            //     new NameValueEntry(nameof( JobData.Topic),jobData.Topic ?? ""),
            //new NameValueEntry(nameof(JobData.RouteKey), jobData.RouteKey ?? ""),
            //     new NameValueEntry(nameof( JobData.Data),jobData.Data ?? new byte[0]),
            //     new NameValueEntry(nameof( JobData.ErrorCount),jobData.ErrorCount),
            //     new NameValueEntry(nameof( JobData.ErrorGroup),jobData.ErrorGroup ?? ""),
            //    };

            var list = new List <NameValueEntry>();

            foreach (var item in GetType().GetProperties())
            {
                var value = item.GetValue(this);
                if (value == null)
                {
                    if (item.PropertyType == typeof(string))
                    {
                        value = RedisValue.EmptyString;
                    }
                    else if (item.PropertyType == typeof(byte[]))
                    {
                        value = new byte[0];
                    }
                }
                list.Add(new NameValueEntry(item.Name, value != null ? RedisValue.Unbox(value) : RedisValue.Null));
            }

            return(list.ToArray());
        }
예제 #9
0
        public void RoundTripRedisValue(RedisValue value)
        {
            var boxed   = value.Box();
            var unboxed = RedisValue.Unbox(boxed);

            AssertEqualGiveOrTakeNaN(value, unboxed);
        }
예제 #10
0
 public override async Task SetAsync(Channel entry, [CanBeNull] string?parent = null)
 {
     if (parent != null)
     {
         await Database.StringSetAsync(FormatKeyName(parent), RedisValue.Unbox(entry.Id));
     }
     await Database.HashSetAsync(Prefix, new[] { new HashEntry(entry.Id, SerializeValue(entry)) });
 }
예제 #11
0
        public void ReturnInternedBoxesForCommonValues(RedisValue value, bool expectSameReference)
        {
            object x = value.Box(), y = value.Box();

            Assert.Equal(expectSameReference, ReferenceEquals(x, y));
            // check we got the right values!
            AssertEqualGiveOrTakeNaN(value, RedisValue.Unbox(x));
            AssertEqualGiveOrTakeNaN(value, RedisValue.Unbox(y));
        }
예제 #12
0
 /// <summary>
 /// 根据键值批量返回数据
 /// </summary>
 /// <param name="keys"></param>
 /// <returns></returns>
 public IEnumerable <TValue> GetValues(params TKey[] keys)
 {
     if (keys == null || keys.Length == 0)
     {
         return(new TValue[0]);
     }
     return(Database.HashGet(SetKey, keys.Select(k => RedisValue.Unbox(k)).ToArray())
            .Select(v => v.HasValue ? ConvertValue(v) : default(TValue)));
 }
예제 #13
0
        /// <summary>
        /// 批量删除全部标记
        /// </summary>
        /// <param name="batch"></param>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public virtual Task BatchAllRemoveTags(IBatch batch, string entityId)
        {
            var setKey = GetSubKey(entityId);
            var values = this.GetTags(entityId).Select(t => RedisValue.Unbox(t)).ToArray();

            batch.SetRemoveAsync(setKey, values);
            _indexSet.BatchRemove(batch, entityId, values);
            return(Task.CompletedTask);
        }
예제 #14
0
        /// <summary>
        /// 批量增加索引
        /// </summary>
        /// <param name="batch"></param>
        /// <param name="id"></param>
        /// <param name="values"></param>
        public void BatchAdd(IBatch batch, T id, params RedisValue[] values)
        {
            var subKeys  = values.Select(v => base.GetSubKey(v));
            var keyValue = RedisValue.Unbox(id);

            foreach (var subKey in subKeys)
            {
                batch.SetAddAsync(subKey, keyValue);
            }
        }
예제 #15
0
        public async Task RemoveAsync(T id, params RedisValue[] values)
        {
            var subKeys  = values.Select(v => base.GetSubKey(v));
            var keyValue = RedisValue.Unbox(id);

            foreach (var subKey in subKeys)
            {
                await Database.SetRemoveAsync(subKey, keyValue);
            }
        }
예제 #16
0
        public void Remove(T id, params RedisValue[] values)
        {
            var subKeys  = values.Select(v => base.GetSubKey(v));
            var keyValue = RedisValue.Unbox(id);

            foreach (var subKey in subKeys)
            {
                Database.SetRemove(subKey, keyValue);
            }
        }
예제 #17
0
        /// <summary>
        /// 根据键值批量返回数据的异步方法
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public async Task <IEnumerable <TValue> > GetValuesAsync(params TKey[] keys)
        {
            if (keys == null || keys.Length == 0)
            {
                return(new TValue[0]);
            }
            var result = await Database.HashGetAsync(SetKey, keys.Select (k => RedisValue.Unbox(k)).ToArray());

            return(result.Select(v => v.HasValue ? ConvertValue(v) : default(TValue)));
        }
예제 #18
0
        /// <summary>
        /// 根据键值批量返回数据
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public async Task <IEnumerable <KeyValuePair <TKey, TValue> > > GetPairsAsync(params TKey[] keys)
        {
            if (keys == null || keys.Length == 0)
            {
                return(new KeyValuePair <TKey, TValue> [0]);
            }
            var values = await Database.HashGetAsync(SetKey, keys.Select (k => RedisValue.Unbox(k)).ToArray());

            return(values.Select((v, i) => new KeyValuePair <TKey, TValue> (keys[i], ConvertValue(v))));
        }
예제 #19
0
        public void TestUnbox()
        {
            object     obj   = null;
            RedisValue value = RedisValue.Null;

            Assert.Equal(value, RedisValue.Unbox(obj));

            obj   = DayOfWeek.Friday;
            value = 5;
            Assert.Equal(value, RedisValue.Unbox(obj));
        }
예제 #20
0
        Task IBatchHashSet <TKey, TValue> .BatchAdd(IBatch batch, params KeyValuePair <TKey, TValue>[] pairs)
        {
            if (pairs == null || pairs.Length == 0)
            {
                return(Task.CompletedTask);
            }

            var entities = pairs.Select(t => new HashEntry(RedisValue.Unbox(t.Key), Serializer.Serialize(t.Value)))
                           .ToArray();

            return(batch.HashSetAsync(SetKey, entities));
        }
예제 #21
0
        Task IBatchHashSet <TKey, TValue> .BatchAdd(IBatch batch, params Tuple <TKey, TValue>[] tuples)
        {
            if (tuples == null || tuples.Length == 0)
            {
                return(Task.CompletedTask);
            }

            var entities = tuples.Select(t => new HashEntry(RedisValue.Unbox(t.Item1), Serializer.Serialize(t.Item2)))
                           .ToArray();

            return(batch.HashSetAsync(SetKey, entities));
        }
예제 #22
0
        /// <summary>Gets the value that is associated with the specified key.</summary>
        /// <param name="key">The key to locate.</param>
        /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
        /// <returns>true if the object that implements the <see cref="T:System.Collections.Generic.IReadOnlyDictionary`2"></see> interface contains an element that has the specified key; otherwise, false.</returns>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="key">key</paramref> is null.</exception>
        public bool TryGetValue(TKey key, out TValue value)
        {
            var result = Database.HashGet(SetKey, RedisValue.Unbox(key));

            if (result.HasValue)
            {
                value = ConvertValue(result);
                return(true);
            }

            value = default(TValue);
            return(false);
        }
예제 #23
0
        public static bool DeleteGroupUsers(string groupGuid, params int[] userIds)
        {
            if (string.IsNullOrEmpty(groupGuid) || userIds == null || userIds.Length <= 0)
            {
                return(false);
            }

            return(RedisUtils.DefaultInstance.Exec(AppConfigManager.GROUP_USER_SET_DB, db =>
            {
                RedisValue[] array = userIds.Select(u => RedisValue.Unbox(u)).ToArray();
                return db.SetRemove(groupGuid, array) > 0;
            }));
        }
예제 #24
0
        public override async Task SetAsync(IEnumerable <Channel> entries, string?parent = null)
        {
            var channels = entries as Channel[] ?? entries.ToArray();

            if (parent != null)
            {
                var unboxedIds = channels.Select(entry => RedisValue.Unbox(entry.Id));
                await Database.SetAddAsync(FormatKeyName(parent), unboxedIds.ToArray());
            }

            await Database.HashSetAsync(Prefix,
                                        channels.Select(entry => new HashEntry(entry.Id, SerializeValue(entry))).ToArray());
        }
예제 #25
0
        public async Task TestGeoshSetInBoundAsync()
        {
            var geos = new GeoHashSet(_factory.Database, "ShipTrack:GeoHash");

            Assert.NotEmpty(geos.Keys());
            var Bounds = new Bounds(118.2, 38.678, 118.96, 39.18);
            // geos.GetRedius
            var keys = await geos.KeysAsync();

            var poses = geos.Position(keys.Select(k => RedisValue.Unbox(k)).ToArray());

            Assert.NotEmpty(poses);
            var count = poses.Count(p => Bounds.InBounds(p.Value.Longitude, p.Value.Latitude));

            Assert.True(count < keys.Count());
        }
예제 #26
0
        public async Task <bool> SetAsync <T>(string key, T value, TimeSpan?expiry = null)
        {
            string redisValue = string.Empty;

            if (IsBasicType(typeof(T)))
            {
                redisValue = RedisValue.Unbox(value);
            }
            else
            {
                redisValue = value.ToJson();
            }

            //when expiry is null that imply permanent
            return(await DB.StringSetAsync(key, redisValue, expiry, When.Always));
        }
예제 #27
0
        public (bool sent, bool clients) TrySendMessage(string parentPipeName, string childPipeName, object body, int maxListLength = int.MaxValue, TimeSpan?expiry = null)
        {
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }
            //will throw ArgumentException is body is not a supported type
            var redisValue = RedisValue.Unbox(body);

            var db             = _redis.GetDatabase();
            var parentInfoPath = CreateParentChildSetPath(parentPipeName);
            var childPipePath  = PipeInfo.Create(parentPipeName, childPipeName);
            var trans          = db.CreateTransaction();
            {
                if (maxListLength < int.MaxValue)
                {
                    trans.AddCondition(Condition.ListLengthLessThan(childPipePath.PipePath, maxListLength));
                }

                //ensure the name of the new pipe exists for the pipe monitor (before checking list length)
                db.SetAdd(RedisTaskMultiplexorConstants.PipeNameSetKey, parentPipeName);

                //add the child to the parents hash set (and update the expiry time on it)
                db.HashSet(parentInfoPath, childPipeName, DateConverters.ExpiryToTimeString(expiry ?? TimeSpan.FromDays(7)));

                //add the message to the left of the list, and is later popped from the right.
                db.ListLeftPush(childPipePath.PipePath, redisValue);
            }
            var executed = trans.Execute();

            if (!executed)
            {
                return(false, false);
            }

            var sub       = _redis.GetSubscriber();
            var listeners = sub.Publish(childPipePath.BroadcastPath, $"{{\"type\":\"new\",\"parent\":\"{parentPipeName}\",\"child\":\"{childPipeName}\"}}");

            return(true, listeners > 0);
        }
예제 #28
0
        /// <summary>
        /// 设置过期时间
        /// 如果<c>expiry</c>为空为清除超期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="expiry"></param>
        /// <returns></returns>
        protected bool SetExpire(TKey key, TimeSpan?expiry)
        {
            var setKey = GetEntryKey(key);

            if (!Database.KeyExists(setKey))
            {
                //Key 不存在
                return(false);
            }
            if (expiry.HasValue)
            {
                //移动setKey 到超期索引
                Database.SetMove(_indexSet.SetKey, _expireIndexSet.SetKey, RedisValue.Unbox(key));
                return(Database.KeyExpire(setKey, expiry));
            }
            else
            {
                //清除过期时间
                //移动setKey 到SetKey 索引
                Database.SetMove(_expireIndexSet.SetKey, _indexSet.SetKey, RedisValue.Unbox(key));
                return(Database.KeyExpire(setKey, expiry));
            }
        }
        public HashEntry[] ToHashEntries()
        {
            //var jobData = this;
            //var nameValues = new HashEntry[] {
            //     new HashEntry(nameof( JobData.JobId),jobData.JobId),
            //     new HashEntry(nameof( JobData.Topic),jobData.Topic),
            //     new HashEntry(nameof(JobData.RouteKey), jobData.RouteKey),
            //     new HashEntry(nameof( JobData.Data),jobData.Data),
            //     new HashEntry(nameof( JobData.ErrorCount),jobData.ErrorCount),
            //    };

            //return nameValues;

            var list = new List <HashEntry>();

            foreach (var item in GetType().GetProperties())
            {
                var value = item.GetValue(this);
                list.Add(new HashEntry(item.Name, value != null ? RedisValue.Unbox(value) : RedisValue.EmptyString));
            }

            return(list.ToArray());
        }
        private async Task SetCacheObjectInternalAsync <T>(string key, T obj, TimeSpan?expiry) where T : class
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            else if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            string str     = SerializeObject(obj);
            bool   success = await ExecuteRedisCommandAsync(() =>
            {
                IDatabase db = GetRedisDatabase();
                return(db.StringSetAsync(key, RedisValue.Unbox(str), expiry));
            });

            if (success == false)
            {
                throw new InvalidOperationException($"Failed to set cache entry for '{key}'");
            }
        }