public async Task <ServiceRegistryEntity[]> Get(string serviceTag)
        {
            var serviceTagExists = await _db.KeyExistsAsync(serviceTag);

            if (!serviceTagExists)
            {
                return(null);
            }

            var serviceInstancesJson = await _db.StringGetAsync(serviceTag);

            var serviceInstances = JsonConvert.DeserializeObject <IList <ServiceRegistryEntity> >(serviceInstancesJson);

            return(serviceInstances.ToArray());
        }
 public async Task <RedisValue> GetValueAsync(string key)
 {
     if (await _redis.KeyExistsAsync(key))
     {
         await _redis.KeyExpireAsync(key, TimeSpan.FromSeconds(120));
     }
     return(await _redis.StringGetAsync(key));
 }
Пример #3
0
        public async Task <bool> IsCached(string key)
        {
            var cachedData = await db.KeyExistsAsync(key);

            if (!cachedData)
            {
                return(await Task.FromResult(false));
            }
            return(await Task.FromResult(true));
        }
Пример #4
0
        private static async Task SyncRedisKeyAsync(IDatabaseAsync srcDatabase, RedisKey redisKey, IDatabaseAsync destDatabase)
        {
            if (await destDatabase.KeyExistsAsync(redisKey))
            {
                await destDatabase.KeyDeleteAsync(redisKey);
            }
            var type = await srcDatabase.KeyTypeAsync(redisKey);

            switch (type)
            {
            case RedisType.String:
                var strVal = await srcDatabase.StringGetAsync(redisKey);

                await destDatabase.StringSetAsync(redisKey, strVal);

                break;

            case RedisType.List:
                var list = await srcDatabase.ListRangeAsync(redisKey);

                await destDatabase.ListRightPushAsync(redisKey, list);

                break;

            case RedisType.Set:
                var set = await srcDatabase.SetMembersAsync(redisKey);

                await destDatabase.SetAddAsync(redisKey, set);

                break;

            case RedisType.SortedSet:
                var zset = await srcDatabase.SortedSetRangeByRankWithScoresAsync(redisKey);

                await destDatabase.SortedSetAddAsync(redisKey, zset);

                break;

            case RedisType.Hash:
                var hash = await srcDatabase.HashGetAllAsync(redisKey);

                await destDatabase.HashSetAsync(redisKey, hash);

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public IObservable <T> GetRecords(IDatabaseAsync database, IDataKey dataKey, long fromRecord = 0, long toRecord = -1)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            if (dataKey == null)
            {
                throw new ArgumentNullException(nameof(dataKey));
            }

            var key = link.GetKey(dataKey);

            log.LogTrace("GetRecords: {0}", key);
            if (fromRecord != 0 &&
                toRecord != -1)
            {
                log.LogWarning("Selecting index is not supported for single item");
            }

            return(Observable.Create <T>(
                       async observer =>
            {
                var exist = await link.Resilience.AsyncRetryPolicy.ExecuteAsync(
                    async() => await database.KeyExistsAsync(key).ConfigureAwait(false))
                            .ConfigureAwait(false);
                if (!exist)
                {
                    log.LogWarning("Key doesn't exist: {0}", key);
                    observer.OnCompleted();
                    return;
                }

                var result = await link.Resilience.AsyncRetryPolicy.ExecuteAsync(
                    async() => await database.HashGetAllAsync(key).ConfigureAwait(false))
                             .ConfigureAwait(false);

                var actualValues = ConstructActualValues(result);
                foreach (var value in actualValues)
                {
                    observer.OnNext(value);
                }

                observer.OnCompleted();
            }));
        }
Пример #6
0
        public async Task <IActionResult> GetCurrentEventStatus(int siteId, string deviceId)
        {
            JArray result   = new JArray();
            string redisKey = $"SID{siteId}.EVENT.{deviceId}";

            if (await db.KeyExistsAsync(redisKey) == false)
            {
                return(BadRequest("잘못된 SiteId 또는 잘못된 DeviceName"));
            }
            var allhash = await db.HashGetAllAsync(redisKey);

            foreach (HashEntry en in allhash)
            {
                JObject row = new JObject();
                row.Add("code", en.Name.ToString().TrimStart('e'));
                row.Add("status", en.Value.ToString());
                result.Add(row);
            }
            return(Ok(result));
        }
Пример #7
0
        public static async Task <JObject> RetriveWeather(int siteid, IDatabaseAsync _redisDb)
        {
            JObject center_weather = new JObject();
            // Weather
            string targetcc_redis_key = $"weather.sid{siteid}";

            if (await _redisDb.KeyExistsAsync(targetcc_redis_key))
            {
                var entries = await _redisDb.HashGetAllAsync(targetcc_redis_key);

                foreach (var entry in entries)
                {
                    center_weather.Add(entry.Name, entry.Value.ToString());
                }
            }
            else
            {
                return(null);
            }
            return(center_weather);
        }
Пример #8
0
        public static Task <bool> ContainsRecord(this IRedisLink link, IDatabaseAsync database, IDataKey key)
        {
            if (link == null)
            {
                throw new ArgumentNullException(nameof(link));
            }

            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var actualKey = link.GetKey(key);

            return(database.KeyExistsAsync(actualKey));
        }
Пример #9
0
 public async Task <bool> ExistAsync(string key)
 {
     return(await _database.KeyExistsAsync(key));
 }
Пример #10
0
        private static TupleList <string, Task> RunStackExchangeAsync(string prefix, IDatabaseAsync db)
        {
            var tasks = new TupleList <string, Func <Task> >()
            {
                { "DebugObjectAsync", () => db.DebugObjectAsync($"{prefix}DebugObjectAsync") },
                { "ExecuteAsync", () => db.ExecuteAsync("DDCUSTOM", "COMMAND") },
                { "GeoAddAsync", () => db.GeoAddAsync($"{prefix}GeoAddAsync", new GeoEntry(1.5, 2.5, "member")) },
                { "GeoDistanceAsync", () => db.GeoDistanceAsync($"{prefix}GeoDistanceAsync", "member1", "member2") },
                { "GeoHashAsync", () => db.GeoHashAsync($"{prefix}GeoHashAsync", "member") },
                { "GeoPositionAsync", () => db.GeoPositionAsync($"{prefix}GeoPositionAsync", "member") },
                { "GeoRadiusAsync", () => db.GeoRadiusAsync($"{prefix}GeoRadiusAsync", "member", 2.3) },
                { "GeoRemoveAsync", () => db.GeoRemoveAsync($"{prefix}GeoRemoveAsync", "member") },
                { "HashDecrementAsync", () => db.HashDecrementAsync($"{prefix}HashDecrementAsync", "hashfield", 4.5) },
                { "HashDeleteAsync", () => db.HashDeleteAsync($"{prefix}HashDeleteAsync", "hashfield") },
                { "HashExistsAsync", () => db.HashExistsAsync($"{prefix}HashExistsAsync", "hashfield") },
                { "HashGetAllAsync", () => db.HashGetAllAsync($"{prefix}HashGetAllAsync") },
                { "HashIncrementAsync", () => db.HashIncrementAsync($"{prefix}HashIncrementAsync", "hashfield", 1.5) },
                { "HashKeysAsync", () => db.HashKeysAsync($"{prefix}HashKeysAsync") },
                { "HashLengthAsync", () => db.HashLengthAsync($"{prefix}HashLengthAsync") },
                { "HashSetAsync", () => db.HashSetAsync($"{prefix}HashSetAsync", new HashEntry[] { new HashEntry("x", "y") }) },
                { "HashValuesAsync", () => db.HashValuesAsync($"{prefix}HashValuesAsync") },
                { "HyperLogLogAddAsync", () => db.HyperLogLogAddAsync($"{prefix}HyperLogLogAddAsync", "value") },
                { "HyperLogLogLengthAsync", () => db.HyperLogLogLengthAsync($"{prefix}HyperLogLogLengthAsync") },
                { "HyperLogLogMergeAsync", () => db.HyperLogLogMergeAsync($"{prefix}HyperLogLogMergeAsync", new RedisKey[] { "key1", "key2" }) },
                { "IdentifyEndpointAsync", () => db.IdentifyEndpointAsync() },
                { "KeyDeleteAsync", () => db.KeyDeleteAsync("key") },
                { "KeyDumpAsync", () => db.KeyDumpAsync("key") },
                { "KeyExistsAsync", () => db.KeyExistsAsync("key") },
                { "KeyExpireAsync", () => db.KeyExpireAsync("key", DateTime.Now) },
                // () => db.KeyMigrateAsync("key", ???)
                { "KeyMoveAsync", () => db.KeyMoveAsync("key", 1) },
                { "KeyPersistAsync", () => db.KeyPersistAsync("key") },
                { "KeyRandomAsync", () => db.KeyRandomAsync() },
                { "KeyRenameAsync", () => db.KeyRenameAsync("key1", "key2") },
                { "KeyRestoreAsync", () => db.KeyRestoreAsync("key", new byte[] { 0, 1, 2, 3, 4 }) },
                { "KeyTimeToLiveAsync", () => db.KeyTimeToLiveAsync("key") },
                { "KeyTypeAsync", () => db.KeyTypeAsync("key") },
                { "ListGetByIndexAsync", () => db.ListGetByIndexAsync("listkey", 0) },
                { "ListInsertAfterAsync", () => db.ListInsertAfterAsync("listkey", "value1", "value2") },
                { "ListInsertBeforeAsync", () => db.ListInsertBeforeAsync("listkey", "value1", "value2") },
                { "ListLeftPopAsync", () => db.ListLeftPopAsync("listkey") },
                { "ListLeftPushAsync", () => db.ListLeftPushAsync("listkey", new RedisValue[] { "value3", "value4" }) },
                { "ListLengthAsync", () => db.ListLengthAsync("listkey") },
                { "ListRangeAsync", () => db.ListRangeAsync("listkey") },
                { "ListRemoveAsync", () => db.ListRemoveAsync("listkey", "value3") },
                { "ListRightPopAsync", () => db.ListRightPopAsync("listkey") },
                { "ListRightPopLeftPushAsync", () => db.ListRightPopLeftPushAsync("listkey", "listkey2") },
                { "ListRightPushAsync", () => db.ListRightPushAsync("listkey", new RedisValue[] { "value5", "value6" }) },
                { "ListSetByIndexAsync", () => db.ListSetByIndexAsync("listkey", 0, "value7") },
                { "ListTrimAsync", () => db.ListTrimAsync("listkey", 0, 1) },
                { "LockExtendAsync", () => db.LockExtendAsync("listkey", "value7", new TimeSpan(0, 0, 10)) },
                { "LockQueryAsync", () => db.LockQueryAsync("listkey") },
                { "LockReleaseAsync", () => db.LockReleaseAsync("listkey", "value7") },
                { "LockTakeAsync", () => db.LockTakeAsync("listkey", "value8", new TimeSpan(0, 0, 10)) },
                { "PublishAsync", () => db.PublishAsync(new RedisChannel("channel", RedisChannel.PatternMode.Auto), "somemessage") },
                // { "ScriptEvaluateAsync", () => db.ScriptEvaluateAsync(}
                { "SetAddAsync", () => db.SetAddAsync("setkey", "value1") },
                { "SetCombineAndStoreAsync", () => db.SetCombineAndStoreAsync(SetOperation.Union, "setkey", new RedisKey[] { "value2" }) },
                { "SetCombineAsync", () => db.SetCombineAsync(SetOperation.Union, new RedisKey[] { "setkey1", "setkey2" }) },
                { "SetContainsAsync", () => db.SetContainsAsync("setkey", "value1") },
                { "SetLengthAsync", () => db.SetLengthAsync("setkey") },
                { "SetMembersAsync", () => db.SetMembersAsync("setkey") },
                { "SetMoveAsync", () => db.SetMoveAsync("setkey1", "setkey2", "value2") },
                { "SetPopAsync", () => db.SetPopAsync("setkey1") },
                { "SetRandomMemberAsync", () => db.SetRandomMemberAsync("setkey") },
                { "SetRandomMembersAsync", () => db.SetRandomMembersAsync("setkey", 2) },
                { "SetRemoveAsync", () => db.SetRemoveAsync("setkey", "value2") },
                { "SortAndStoreAsync", () => db.SortAndStoreAsync("setkey2", "setkey") },
                { "SortAsync", () => db.SortAsync("setkey") },
                { "SortedSetAddAsync", () => db.SortedSetAddAsync("ssetkey", new SortedSetEntry[] { new SortedSetEntry("value1", 1.5), new SortedSetEntry("value2", 2.5) }) },
                { "SortedSetCombineAndStoreAsync", () => db.SortedSetCombineAndStoreAsync(SetOperation.Union, "ssetkey1", "ssetkey2", "ssetkey3") },
                { "SortedSetDecrementAsync", () => db.SortedSetDecrementAsync("ssetkey", "value1", 1) },
                { "SortedSetIncrementAsync", () => db.SortedSetIncrementAsync("ssetkey", "value2", 1) },
                { "SortedSetLengthAsync", () => db.SortedSetLengthAsync("ssetkey") },
                { "SortedSetLengthByValueAsync", () => db.SortedSetLengthByValueAsync("ssetkey", "value1", "value2") },
                { "SortedSetRangeByRankAsync", () => db.SortedSetRangeByRankAsync("ssetkey") },
                { "SortedSetRangeByRankWithScoresAsync", () => db.SortedSetRangeByRankWithScoresAsync("ssetkey") },
                { "SortedSetRangeByScoreAsync", () => db.SortedSetRangeByScoreAsync("ssetkey") },
                { "SortedSetRangeByScoreWithScoresAsync", () => db.SortedSetRangeByScoreWithScoresAsync("ssetkey") },
                { "SortedSetRangeByValueAsync", () => db.SortedSetRangeByValueAsync("ssetkey") },
                { "SortedSetRankAsync", () => db.SortedSetRankAsync("ssetkey", "value1") },
                { "SortedSetRemoveAsync", () => db.SortedSetRemoveAsync("ssetkey", "value1") },
                { "SortedSetRemoveRangeByRankAsync", () => db.SortedSetRemoveRangeByRankAsync("ssetkey", 0, 1) },
                { "SortedSetRemoveRangeByScoreAsync", () => db.SortedSetRemoveRangeByScoreAsync("ssetkey", 0, 1) },
                { "SortedSetRemoveRangeByValueAsync", () => db.SortedSetRemoveRangeByValueAsync("ssetkey", "value1", "value2") },
                { "SortedSetScoreAsync", () => db.SortedSetScoreAsync("ssestkey", "value1") },
                { "StringAppendAsync", () => db.StringAppendAsync("ssetkey", "value1") },
                { "StringBitCountAsync", () => db.StringBitCountAsync("ssetkey") },
                { "StringBitOperationAsync", () => db.StringBitOperationAsync(Bitwise.And, "ssetkey1", new RedisKey[] { "ssetkey2", "ssetkey3" }) },
                { "StringBitPositionAsync", () => db.StringBitPositionAsync("ssetkey1", true) },
                { "StringDecrementAsync", () => db.StringDecrementAsync("key", 1.45) },
                { "StringGetAsync", () => db.StringGetAsync("key") },
                { "StringGetBitAsync", () => db.StringGetBitAsync("key", 3) },
                { "StringGetRangeAsync", () => db.StringGetRangeAsync("key", 0, 1) },
                { "StringGetSetAsync", () => db.StringGetSetAsync("key", "value") },
                { "StringGetWithExpiryAsync", () => db.StringGetWithExpiryAsync("key") },
                { "StringIncrementAsync", () => db.StringIncrementAsync("key", 1) },
                { "StringLengthAsync", () => db.StringLengthAsync("key") },
                { "StringSetAsync", () => db.StringSetAsync(new KeyValuePair <RedisKey, RedisValue>[] { new KeyValuePair <RedisKey, RedisValue>("key", "value") }) },
                { "StringSetBitAsync", () => db.StringSetBitAsync("key", 0, true) },
                { "StringSetRangeAsync", () => db.StringSetRangeAsync("key", 3, "value") },
            };

            var pending = new TupleList <string, Task>();

            foreach (var item in tasks)
            {
                try
                {
                    pending.Add(item.Item1, item.Item2());
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }
                    Console.WriteLine($"{e.Message}");
                }
            }

            return(pending);
        }
        //private async Task SendQueue(string topic, JObject msg_oridinary, CancellationToken token)
        //{
        //    foreach (var mqtt_proxy in mqtt_clients)
        //    {
        //        try
        //        {

        //            var msg = CreateMqttMessage(topic, msg_oridinary.ToString(), mqtt_proxy.Options.QosLevel);
        //            var mqtt_client = mqtt_proxy.MqttClient;

        //            if (mqtt_client.IsConnected == false)
        //                continue;
        //            await mqtt_client.PublishAsync(msg, token);
        //            Thread.Sleep(10);
        //            break;
        //        }
        //        catch (Exception ex)
        //        {
        //            logger.LogError(ex, ex.Message);
        //        }
        //    }
        //}

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                stoppingToken.ThrowIfCancellationRequested();
                try
                {
                    bool isConnected = modbusFactory.ReconnectWhenDisconnected(stoppingToken, 3);
                    if (isConnected == false)
                    {
                        logger.LogWarning("모드버스 접속에 실패했습니다. 5초후 재개");
                        await Task.Delay(5000, stoppingToken);

                        continue;
                    }



                    stoppingToken.ThrowIfCancellationRequested();
                    //var parallelResult = Parallel.ForEach<GroupPoint>(modbus.GroupPoints, (async x =>
                    foreach (var x in modbus.GroupDigitalPoints)
                    {
                        if (x.Disable == true)
                        {
                            continue;
                        }
                        List <DiMap> results = await modbusFactory.ReadModbusEvent(x);


                        foreach (DiMap map in results)
                        {
                            if (map.DocumentAddress == 40132)
                            {
                            }
                            if (map.Disable == true)
                            {
                                continue;
                            }



                            //cache.Get()
                            //datarow.Add(map.Name, map.Value);
                            string redis_key   = $"{modbus.DeviceName}.{map.DocumentAddress}";
                            ushort redis_value = 0;
                            if (await redis.KeyExistsAsync(redis_key))
                            {
                                string redis_str = await redis.StringGetAsync(redis_key);

                                redis_value = ushort.Parse(redis_str);
                            }

                            if (map.Value == redis_value)
                            {
                                continue;
                            }
                            else
                            {
                                await redis.StringSetAsync(redis_key, map.Value.ToString());
                            }



                            using (var session = dbAccess.SessionFactory.OpenSession())
                            {
                                using (var transaction = session.BeginTransaction())
                                {
                                    EventSummary summary = new EventSummary();
                                    summary.SiteId     = SiteId;
                                    summary.DeviceName = modbus.DeviceName;
                                    summary.GroupName  = map.Name;

                                    summary.SetTimestamp(DateTime.Now);
                                    foreach (DiFlag evt in map.Flags)
                                    {
                                        EventField ef = event_map.FirstOrDefault(Tx => Tx.Register == map.DocumentAddress && Tx.BitValue == evt.BitValue);


                                        bool IsActive = evt.IsActivate(map.Value);
                                        if (evt.EventCode.HasValue)
                                        {
                                            summary.ActiveEvents.Add(evt.EventCode.Value);
                                        }
                                        string redis_event_key = redis_key + "." + evt.No;

                                        if (await redis.KeyExistsAsync(redis_event_key) == false)
                                        {
                                            await redis.HashSetAsync(redis_event_key, CreateEventNode(map, evt));
                                        }
                                        else
                                        {
                                            await redis.HashSetAsync(redis_event_key, "Status", IsActive);
                                        }

                                        if (map.Disable == true || map.Level == 0)
                                        {
                                            continue;
                                        }

                                        string mysql_key_str = $"{modbus.DeviceName}{map.DocumentAddress}{evt.No}";

                                        string normalizeDeviceName = map.Source + DeviceIndex;
                                        //ActiveEvent existEvent = session.Get<ActiveEvent>(mysql_key_str);
                                        ActiveEvent existEvent = await GetLatestActiveEventAsync(session, mysql_key_str, stoppingToken);

                                        //if (existEvent == null)
                                        //    continue;
                                        switch (EventStatus(existEvent, IsActive, session))
                                        {
                                        case Hubbub.EventStatus.Already:
                                            mysql_key_str             = GetNextEventId(mysql_key_str, session);
                                            existEvent                = new ActiveEvent();
                                            existEvent.Description    = evt.BitName;
                                            existEvent.DeviceName     = modbus.DeviceName;
                                            existEvent.EventLevel     = map.Level;
                                            existEvent.EventName      = evt.BitName;
                                            existEvent.Source         = map.Source;
                                            existEvent.OccurTimestamp = DateTime.Now;
                                            existEvent.EventId        = mysql_key_str;
                                            await session.SaveAsync(existEvent, stoppingToken);

                                            break;

                                        case Hubbub.EventStatus.New:
                                            existEvent                = new ActiveEvent();
                                            existEvent.Description    = evt.BitName;
                                            existEvent.DeviceName     = modbus.DeviceName;
                                            existEvent.EventLevel     = map.Level;
                                            existEvent.EventName      = evt.BitName;
                                            existEvent.Source         = map.Source;
                                            existEvent.OccurTimestamp = DateTime.Now;
                                            existEvent.EventId        = mysql_key_str;
                                            await session.SaveAsync(existEvent, stoppingToken);

                                            if (evt.EventCode.HasValue)
                                            {
                                                summary.NewEvents.Add(evt.EventCode.Value);
                                            }
                                            if (ef != null)
                                            {
                                                await eventPublisherWorker.PublishEvent(SiteId, normalizeDeviceName, ef.Code, Events.Alarm.EventStatus.New, stoppingToken);
                                            }

                                            break;

                                        case Hubbub.EventStatus.Recover:
                                            if (evt.EventCode.HasValue)
                                            {
                                                summary.RecoverEvents.Add(evt.EventCode.Value);
                                            }
                                            RecoversEvent(existEvent.EventId, session);
                                            if (ef != null)
                                            {
                                                await eventPublisherWorker.PublishEvent(SiteId, normalizeDeviceName, ef.Code, Events.Alarm.EventStatus.Recovery, stoppingToken);
                                            }
                                            //existEvent.HasRecovered = true;
                                            //existEvent.RecoverTimestamp = DateTime.Now;
                                            //await session.SaveOrUpdateAsync(existEvent, stoppingToken);
                                            break;
                                        }
                                    }
                                    await transaction.CommitAsync(stoppingToken);

                                    //var msg = CreateMqttMessage(peiu_event_topic, summary.ToString(), 2);
                                    //await mqtt_clients.PeiuEventBrokerProxy.MqttClient.PublishAsync(msg, stoppingToken);
                                }
                            }
                        }
                    }
                }catch (Exception ex)
                {
                }

                //await SendQueue(peiu_event_topic, datarow, stoppingToken);
                await Task.Delay(UpdatePeriod.Milliseconds);

                //Thread.Sleep(UpdatePeriod);
            }
        }
Пример #12
0
 public async Task <long> GetCount(string key)
 {
     return(await redisDb.KeyExistsAsync(key).ConfigureAwait(false) ? 1 : 0);
 }
        /// <summary>
        /// Creates the consumer group if not exists asynchronous.
        /// </summary>
        /// <param name="db">The database.</param>
        /// <param name="eventSourceKey">The event source key.</param>
        /// <param name="consumerGroup">The consumer group.</param>
        /// <param name="logger">The logger.</param>
        /// <returns></returns>
        public static async Task CreateConsumerGroupIfNotExistsAsync(
            this IDatabaseAsync db,
            string eventSourceKey,
            string consumerGroup,
            ILogger logger)
        {
            StreamGroupInfo[] groupsInfo = Array.Empty <StreamGroupInfo>();

            int  delay     = 0;
            bool exists    = false;
            int  tryNumber = 0;

            while (groupsInfo.Length == 0)
            {
                tryNumber++;
                try
                {
                    #region delay on retry

                    if (delay == 0)
                    {
                        delay = 4;
                    }
                    else
                    {
                        delay = Math.Min(delay * 2, 15_000);
                        await Task.Delay(delay);

                        if (tryNumber % 10 == 0)
                        {
                            logger.LogWarning($"{nameof(CreateConsumerGroupIfNotExistsAsync)} still waiting");
                        }
                    }

                    #endregion // delay on retry

                    groupsInfo = await db.StreamGroupInfoAsync(
                        eventSourceKey,
                        flags : CommandFlags.DemandMaster);

                    exists = groupsInfo.Any(m => m.Name == consumerGroup);
                }
                #region Exception Handling

                catch (RedisServerException ex)
                {
                    if (!await db.KeyExistsAsync(eventSourceKey,
                                                 flags: CommandFlags.DemandMaster))
                    {
                        logger.LogDebug(ex, $"{nameof(CreateConsumerGroupIfNotExistsAsync)} [GroupInfo]: Key not exists");
                    }
                    else
                    {
                        logger.LogWarning(ex, $"{nameof(CreateConsumerGroupIfNotExistsAsync)} [GroupInfo]: failed");
                    }
                }
                catch (Exception ex)
                {
                    logger.LogWarning(ex, $"{nameof(CreateConsumerGroupIfNotExistsAsync)} [GroupInfo]: unexpected failure");
                }

                #endregion // Exception Handling
                if (!exists)
                {
                    try
                    {
                        await db.StreamCreateConsumerGroupAsync(eventSourceKey,
                                                                consumerGroup,
                                                                StreamPosition.Beginning,
                                                                flags : CommandFlags.DemandMaster);
                    }
                    #region Exception Handling

                    catch (RedisServerException ex)
                    {
                        logger.LogWarning(ex, $"{nameof(CreateConsumerGroupIfNotExistsAsync)}: failed & still waiting");
                    }
                    catch (Exception ex)
                    {
                        logger.LogWarning(ex, $"{nameof(CreateConsumerGroupIfNotExistsAsync)}: unexpected failure");
                    }

                    #endregion // Exception Handling
                }
            }
        }
Пример #14
0
        public IObservable <T> GetRecords(IDatabaseAsync database, IDataKey dataKey, long fromRecord = 0, long toRecord = -1)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            if (dataKey == null)
            {
                throw new ArgumentNullException(nameof(dataKey));
            }

            var key = link.GetKey(dataKey);

            logger.LogDebug("GetRecords: {0} {1}:{2}", key, fromRecord, toRecord);
            return(Observable.Create <T>(
                       async observer =>
            {
                if (!columnsCache.TryGetValue(typeof(T), out RedisValue[] columns))
                {
                    var subKey = link.GetKey("object");
                    columns = objectSerialization.GetColumns()
                              .Select(item => (RedisValue)($"{subKey}:*->" + item))
                              .ToArray();
                    columnsCache[typeof(T)] = columns;
                }

                var exist = await link.Resilience.AsyncRetryPolicy.ExecuteAsync(
                    async() =>
                    await database.KeyExistsAsync(key).ConfigureAwait(false)).ConfigureAwait(false);

                if (!exist)
                {
                    logger.LogDebug("Key doesn't exist: {0}", key);
                    observer.OnCompleted();
                    return;
                }

                var result = await link.Resilience.AsyncRetryPolicy.ExecuteAsync(
                    async() => await
                    database.SortAsync(
                        key,
                        fromRecord,
                        toRecord,
                        Order.Ascending,
                        SortType.Numeric,
                        "nosort",
                        columns).ConfigureAwait(false))
                             .ConfigureAwait(false);
                if (result.Length % columns.Length != 0)
                {
                    logger.LogError(
                        "Result {0} mismatched with requested number of columns {1}",
                        result.Length,
                        columns.Length);
                    observer.OnCompleted();
                    return;
                }

                var values = objectSerialization.GetInstances(result);
                foreach (var value in values)
                {
                    observer.OnNext(value);
                }

                observer.OnCompleted();
            }));
Пример #15
0
 /// <summary>
 /// Returns if key exists.
 /// </summary>
 /// <returns>1 if the key exists. 0 if the key does not exist.</returns>
 /// <remarks>https://redis.io/commands/exists</remarks>
 public Task <bool> ExistsAsync()
 {
     return(RedisDb.KeyExistsAsync(KeyName));
 }