Exemplo n.º 1
0
        public override async Task OnConnectedAsync()
        {
            var user            = _claimsService.GetUserClaims();
            var userConnections = await _cacheService.Get <List <string> >(CachingHelpers.BuildKey("Notification", user.Id)) ?? new List <string>();

            userConnections.Add(Context.ConnectionId);
            await _cacheService.Set(CachingHelpers.BuildKey("Notification", user.Id), userConnections);

            var numOfNotifications = await _notificationService.GetUserNumberOfNotifications(user.Id);

            var unreadMessages = await _messageService.GetUnreadMessages(user.Id);

            await _pubSub.Publish(Channels.NotififcationMessageChannel, new NewNotificationMessageContract
            {
                ActionType          = NotificationActionType.UnreadMessage,
                ConnectionIds       = userConnections,
                TotalUnreadMessages = unreadMessages
            });

            await _pubSub.Publish(Channels.NotififcationMessageChannel, new NewNotificationMessageContract
            {
                ActionType          = NotificationActionType.NewNoti,
                ConnectionIds       = userConnections,
                TotalUnreadMessages = numOfNotifications
            });

            await base.OnConnectedAsync();
        }
Exemplo n.º 2
0
        public void Should_send_invalidation_message_when_added_and_flag_is_true()
        {
            sut.Add("Key", 1, TimeSpan.FromMinutes(1), true);

            A.CallTo(() => pubSub.Publish(A <object> ._))
            .MustHaveHappened();
        }
        public void Should_invalidate_if_key_is_not_a_string()
        {
            sut.Invalidate(123);

            A.CallTo(() => pubsub.Publish(A <InvalidateMessage> .That.Matches(x => x.CacheKey == "a-key"), true))
            .MustNotHaveHappened();
        }
Exemplo n.º 4
0
        public IActionResult Start(string name)
        {
            pubSub.Publish(new StartConsumerMessage {
                ConsumerName = name
            }, true);

            return(NoContent());
        }
 /// <summary>
 /// 发布
 /// </summary>
 /// <param name="channel">频道名称</param>
 /// <param name="value">消息内容</param>
 /// <returns></returns>
 public long Publish(string channel, string value)
 {
     if (pubsub.Publish(channel, value) == 0)
     {
         RepeatAction(channel, () =>
         {
             return(pubsub.Publish(channel, value) > 0);
         });
     }
     return(0);
 }
Exemplo n.º 6
0
 public long Publish(string channel, string value)
 {
     if (pubSub.Publish(channel, value) == 0)
     {
         //订阅者为0,或者订阅者出现异常,我们可以重试
         RepeatAction(channel, () =>
         {
             return(pubSub.Publish(channel, value) > 0);
         });
     }
     return(0);
 }
Exemplo n.º 7
0
        public void Should_start_correct_actor()
        {
            sut.Connect();

            pubSub.Publish(new StartConsumerMessage {
                ConsumerName = consumerName1
            }, true);

            A.CallTo(() => actor1.Start())
            .MustHaveHappened();

            A.CallTo(() => actor2.Start())
            .MustNotHaveHappened();
        }
Exemplo n.º 8
0
 public async Task Handle(CreateTodoCommand command)
 {
     await Task.Run(() =>
     {
         _pubSub.Publish("ChainedCreateTodoCommandHandler", "Chained handler just handled a task!");
     });
 }
Exemplo n.º 9
0
        public Task <T> GetSingleAsync <T, TKey>(TKey key) where T : IStatefulObject <TKey>
        {
            Guard.NotNull(key, nameof(key));

            lock (lockObject)
            {
                if (statesCache.TryGetValue <ObjectHolder <T, TKey> >(key, out var stateObj))
                {
                    return(stateObj.ActivateAsync());
                }

                var state = (T)services.GetService(typeof(T));

                var stateStore = new Store <T, TKey>(eventStore, eventDataFormatter, services, streamNameResolver,
                                                     () =>
                {
                    pubSub.Publish(new InvalidateMessage {
                        Key = key.ToString()
                    }, false);
                }, () =>
                {
                    statesCache.Remove(key);
                });

                stateObj = new ObjectHolder <T, TKey>(state, key, stateStore);

                statesCache.CreateEntry(key)
                .SetValue(stateObj)
                .SetAbsoluteExpiration(CacheDuration)
                .Dispose();

                return(stateObj.ActivateAsync());
            }
        }
Exemplo n.º 10
0
        public async Task <IEnumerable <WeatherForecast> > Get()
        {
            await _cacheService.Set("foo", new List <string>() { "hello world" });

            var x = await _cacheService.Get <List <string> >("Chat_a5b5671c-7ce5-49f3-b400-27d490a5dbf7");

            // var value1 = await _cacheService.Get<List<string>>("OT_666f1370-9a66-45ab-a95e-cdc9e0a0764a");
            // var value2 = await _cacheService.Get<List<string>>("OT_be8d770c-af48-4392-b04d-a21ef9fd647f");

            var user = _httpContextAccessor.HttpContext.User;
            var rng  = new Random();

            // await _notificationHub.Clients.All.SendAsync("HasUnreadMessagesAsync", rng.Next(10, 60));
            await _pubSub.Publish(Channels.NotififcationMessageChannel, new NewNotificationMessageContract
            {
                ActionType          = NotificationActionType.UnreadMessage,
                ConnectionIds       = new List <string> {
                },
                TotalUnreadMessages = rng.Next(10, 60)
            });

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = "123"
            })
                   .ToArray());
        }
Exemplo n.º 11
0
        public Task <T> GetAsync <T, TState>(string key) where T : StatefulObject <TState>
        {
            Guard.NotNull(key, nameof(key));

            lock (lockObject)
            {
                if (statesCache.TryGetValue <ObjectHolder <T, TState> >(key, out var stateObj))
                {
                    return(stateObj.ActivateAsync());
                }

                var state = (T)services.GetService(typeof(T));

                var stateHolder = new StateHolder <TState>(key, () =>
                {
                    pubSub.Publish(new InvalidateMessage {
                        Key = key
                    }, false);
                }, store);

                stateObj = new ObjectHolder <T, TState>(state, stateHolder);

                statesCache.CreateEntry(key)
                .SetValue(stateObj)
                .SetAbsoluteExpiration(CacheDuration)
                .Dispose();

                return(stateObj.ActivateAsync());
            }
        }
Exemplo n.º 12
0
 public void Invalidate(object key)
 {
     if (key is string)
     {
         invalidator.Publish(ChannelName, key.ToString(), false);
     }
 }
Exemplo n.º 13
0
        public static async Task <TResponse> RequestAsync <TRequest, TResponse>(this IPubSub pubsub, TRequest message, TimeSpan timeout, bool self = true)
        {
            var request = new Request <TRequest> {
                Body = message, CorrelationId = Guid.NewGuid()
            };

            IDisposable subscription = null;

            try
            {
                var receiveTask = new TaskCompletionSource <TResponse>(TaskCreationOptions.RunContinuationsAsynchronously);

                subscription = pubsub.Subscribe <Response <TResponse> >(response =>
                {
                    if (response.CorrelationId == request.CorrelationId)
                    {
                        receiveTask.SetResult(response.Body);
                    }
                });

                Task.Run(() => pubsub.Publish(request, self));

                using (var cts = new CancellationTokenSource(timeout))
                {
                    return(await receiveTask.Task.WithCancellation(cts.Token));
                }
            }
            finally
            {
                subscription?.Dispose();
            }
        }
Exemplo n.º 14
0
        private async Task InvalidateCacheAsync()
        {
            pubSub.Publish(new InvalidateMessage {
                Key = key
            }, true);

            await Task.Delay(400);
        }
 public void Invalidate(object key)
 {
     if (key is string stringKey)
     {
         invalidator.Publish(new InvalidateMessage {
             CacheKey = stringKey
         }, true);
     }
 }
Exemplo n.º 16
0
        public static IDisposable ReceiveAsync <TRequest, TResponse>(this IPubSub pubsub, Func <TRequest, Task <TResponse> > callback, bool self = true)
        {
            return(pubsub.Subscribe <Request <TRequest> >(async x =>
            {
                var response = await callback(x.Body);

                pubsub.Publish(new Response <TResponse> {
                    CorrelationId = x.CorrelationId, Body = response
                }, true);
            }));
        }
Exemplo n.º 17
0
        private void Invalidate(string key)
        {
            if (!options.Enable)
            {
                return;
            }

            pubSub.Publish(new InvalidateMessage {
                Key = key, Source = instanceId
            });
        }
Exemplo n.º 18
0
        public Task Publish <T>(string actorInterface, string eventName, string actorId, T data)
        {
            var e = new ActorEvent <T>()
            {
                ActorId        = actorId,
                ActorInterface = actorInterface,
                EventData      = data,
                EventName      = eventName
            };

            return(_pubsub.Publish(ActorEventChannel(e.ActorInterface, e.EventName, e.ActorId), _serializer.Serialize <T>(data)));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Publishes a message with a topic
        /// </summary>
        /// <param name="pubSub">The pubSub instance</param>
        /// <param name="message">The message to publish</param>
        /// <param name="messageType">The message type</param>
        /// <param name="topic">The topic string</param>
        /// <param name="cancellationToken">The cancellation token</param>
        public static void Publish(
            this IPubSub pubSub,
            object message,
            Type messageType,
            string topic,
            CancellationToken cancellationToken = default
            )
        {
            Preconditions.CheckNotNull(pubSub, "pubSub");

            pubSub.Publish(message, messageType, c => c.WithTopic(topic), cancellationToken);
        }
Exemplo n.º 20
0
        public Task SendAsync(string recipient, object message)
        {
            Guard.NotNullOrEmpty(recipient, nameof(recipient));
            Guard.NotNull(message, nameof(message));

            var messageType = typeNameRegistry.GetName(message.GetType());
            var messageBody = WriteJson(message);

            var envelope = new Envelope {
                Recipient = recipient, Payload = messageBody, PayloadType = messageType
            };

            pubSub.Publish(ChannelName, JsonConvert.SerializeObject(envelope), true);

            return(TaskHelper.Done);
        }
Exemplo n.º 21
0
            private void PublishProgress()
            {
                var newProgress = _precentageCalculator.CalculatePrecentage(_reader.BaseStream.Position, _reader.BaseStream.Length);

                if (NoChange(newProgress, _prevProgress))
                {
                    return;
                }

                _pubSub.Publish(new FileReadProgressEvent
                {
                    FileName = _source,
                    Progress = newProgress
                });

                _prevProgress = newProgress;
            }
Exemplo n.º 22
0
        public void Invalidate(ICacheInvalidationKey dependency)
        {
            var topic = TransformDependency(dependency);

            try {
                pubSub.Publish(topic, filter.InstanceKey);
            } catch (Exception e) {
                AppInfo appInfo = null;
                try {
                    appInfo = AppInfo.GetAppInfo();
                } catch { }
                Log.ErrorLog.LogApplicationError(new InvalidOperationException("Error invalidating cache. Check the Cache Invalidation Service status in the Environment Health page.", e), appInfo?.OsContext, "Server Side Cache");
            } finally {
                // Sending a message to invalidate local cache, without sending to RabbitMQ Server
                // This way, current application will immediatly see its cache invalidated
                filter.OnMessageReceived(new PubSubMessage(topic, "local Invalidation"));
            }
        }
        public void SavePreferences(AppPreferences preferences)
        {
            if (!_propertiesRepository.GetValue <string>(Constants.AppProperties.TransactionCachePath).Equals(preferences.TransactionCacheLocation, System.StringComparison.InvariantCultureIgnoreCase))
            {
                _propertiesRepository.SetValue(Constants.AppProperties.TransactionCachePath, preferences.TransactionCacheLocation);
                _propertiesRepository.Save();
                _mainFormPresenter.InitializeTransactionCache();
            }

            if (_propertiesRepository.GetValue <bool>(Constants.AppProperties.UseDarkTheme) != preferences.UseDarkTheme)
            {
                _propertiesRepository.SetValue(Constants.AppProperties.UseDarkTheme, preferences.UseDarkTheme);
                _propertiesRepository.Save();
                _pubsub.Publish(this, new PubSubEventArgs {
                    Data = preferences.UseDarkTheme
                }, Constants.SubscriptionTypes.THEME_CHANGE);
                _view.RenderTheme();
            }
        }
Exemplo n.º 24
0
        public static async Task <TResponse> RequestAsync <TRequest, TResponse>(this IPubSub pubsub, TRequest message, TimeSpan timeout, bool self = true)
        {
            var request = new Request <TRequest> {
                Body = message, CorrelationId = Guid.NewGuid()
            };

            IDisposable subscription = null;

            try
            {
                var receiveTask = new TaskCompletionSource <TResponse>();

                subscription = pubsub.Subscribe <Response <TResponse> >(response =>
                {
                    if (response.CorrelationId == request.CorrelationId)
                    {
                        receiveTask.SetResult(response.Body);
                    }
                });

                Task.Run(() => pubsub.Publish(request, self));

                var firstTask = await Task.WhenAny(receiveTask.Task, Task.Delay(timeout));

                if (firstTask.Id != receiveTask.Task.Id)
                {
                    throw new TaskCanceledException();
                }
                else
                {
                    return(await receiveTask.Task);
                }
            }
            finally
            {
                subscription?.Dispose();
            }
        }
Exemplo n.º 25
0
        public async Task SendMessage(string message, string fileUrl, Guid contactUserId, Guid conversationId)
        {
            var identity = _claimsService.GetUserClaims();
            var payload  = new SendMessageRequestContract
            {
                SenderId       = identity.Id,
                ContactUserId  = contactUserId,
                Message        = message,
                MessageType    = string.IsNullOrEmpty(fileUrl) ? 0 : 1,
                AttachmentUrl  = fileUrl,
                ConversationId = conversationId
            };

            var messageId = await _messageService.CreateMessageAsync(payload);

            payload.MessageId = messageId;
            var userConnectionIds = await _cacheService.Get <List <string> >(CachingHelpers.BuildKey("Chat", identity.Id)) ?? new List <string>();

            var contactConnectionIds = await _cacheService.Get <List <string> >(CachingHelpers.BuildKey("Chat", contactUserId)) ?? new List <string>();

            var connectionIds = userConnectionIds.Union(contactConnectionIds).ToList();

            await _pubSub.Publish(Channels.PrivateMessageChannel,
                                  new
                                  PrivateMessageContract
            {
                ConnectionIds = connectionIds,
                NewMessage    = payload
            });

            var unreadMessages = await _messageService.GetUnreadMessages(contactUserId);

            await _pubSub.Publish(Channels.NotififcationMessageChannel, new NewNotificationMessageContract
            {
                ActionType          = NotificationActionType.UnreadMessage,
                ConnectionIds       = await _cacheService.Get <List <string> >(CachingHelpers.BuildKey("Notification", contactUserId)) ?? new List <string>(),
                TotalUnreadMessages = unreadMessages
            });
        }
Exemplo n.º 26
0
 public void NotifyEventsStored(string streamName)
 {
     pubsub.Publish(new EventNotification {
         StreamName = streamName
     }, true);
 }
 public ValuesController(IPubSub pubSub)
 {
     pubSub.Publish <EventBase>(new EventBase());
 }
        public void Should_invalidate_if_key_is_not_a_string()
        {
            sut.Invalidate(123);

            A.CallTo(() => pubsub.Publish("CacheInvalidations", A <string> .Ignored, true)).MustNotHaveHappened();
        }
Exemplo n.º 29
0
 public void Synchronize <T, TKey>(TKey key) where T : IStatefulObject <TKey>
 {
     pubSub.Publish(new InvalidateMessage {
         Key = key.ToString()
     }, false);
 }
Exemplo n.º 30
0
 public void NotifyEventsStored(string streamName)
 {
     pubsub.Publish(ChannelName, streamName, true);
 }