public static IServiceCollection AddMessaging( this IServiceCollection serviceCollection, Action <MessagingConfiguration> messagingBuilder, Func <IServiceCollection, IServiceCollection> registerHandlersBuilder) { var messagingConfiguration = new MessagingConfiguration(serviceCollection); messagingBuilder(messagingConfiguration); if (!serviceCollection.Any(sd => typeof(TaskFactory).IsAssignableFrom(sd.ServiceType))) { serviceCollection.AddSingleton(new TaskFactory()); } if (!serviceCollection.Any(sd => typeof(IServiceCollection).IsAssignableFrom(sd.ServiceType))) { serviceCollection.AddSingleton <IServiceCollection>(serviceCollection); } if (!serviceCollection.Any(sd => typeof(IMessageHandlersRegistry).IsAssignableFrom(sd.ServiceType))) { serviceCollection.AddSingleton <IMessageHandlersRegistry, MessageHandlersRegistryIoC>(); } if (!serviceCollection.Any(sd => typeof(IMessageRouter).IsAssignableFrom(sd.ServiceType))) { serviceCollection.AddSingleton <IMessageRouter, DefaultMessageRouter>(); } return(registerHandlersBuilder(serviceCollection)); }
public void Publish(IEnumerable <Payload> payloads, MessagingConfiguration messagingConfiguration) { using (var connection = _connectionFactory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(messagingConfiguration.ExchangeName, messagingConfiguration.Type, messagingConfiguration.Durable, messagingConfiguration.AutoDelete, null); foreach (var payload in payloads) { var properties = channel.CreateBasicProperties(); properties.CorrelationId = payload.CorrelationId ?? ""; properties.ReplyTo = payload.ReplyTo ?? ""; var bodyBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload.Body)); try { channel.BasicPublish(messagingConfiguration.ExchangeName, messagingConfiguration.RoutingKey, true, properties, bodyBytes); } catch (Exception ex) { //Log exception } } } }
/// <summary> /// Initializes a new instance of the <see cref="T:RestBus.RabbitMQ.RestBusClient" /> class. /// </summary> /// <param name="messageMapper">The <see cref="IMessageMapper" /> the client uses to route messages.</param> /// <param name="settings">Client settings.</param> public RestBusClient(IMessageMapper messageMapper, ClientSettings settings) : base(new HttpClientHandler(), true) { //Set default HttpClient related fields timeout = TimeSpan.FromSeconds(100); MaxResponseContentBufferSize = int.MaxValue; //TODO: Setup cancellation token here. //Ensure messageMapper server uris are valid AmqpConnectionInfo.EnsureValid(messageMapper.ServerUris, "messageMapper.ServerUris"); //Configure RestBus fields/properties this.messageMapper = messageMapper; this.messagingConfig = messageMapper.MessagingConfig; //Fetched only once. if (messagingConfig == null) { throw new ArgumentException("messageMapper.MessagingConfig returned null"); } //Set ClientSettings this.Settings = settings ?? new ClientSettings(); // Always have a default instance, if it wasn't passed in. this.Settings.Client = this; //Indicate that the settings is owned by this client. //Instantiate connection manager and RPC strategies; connectionMgr = new ConnectionManager(messageMapper.ServerUris); directStrategy = new DirectReplyToRPCStrategy(); callbackStrategy = new CallbackQueueRPCStrategy(this.Settings, messageMapper.GetServiceName(null)); }
public void Get(MessagingConfiguration messagingConfiguration, IRabbitMessageHandler messageHandler) { using (var messageConsumer = new TSubscriber()) { messageConsumer.Get(messagingConfiguration, messageHandler); } }
/// <summary> /// Initislizes a new instance of the <see cref="RestBusSubscriber"/> /// </summary> /// <param name="messageMapper">The <see cref="IMessageMapper"/> used by the subscriber.</param> /// <param name="settings">The subscriber settings</param> public RestBusSubscriber(IMessageMapper messageMapper, SubscriberSettings settings) { this.messageMapper = messageMapper; messagingConfig = messageMapper.MessagingConfig; //Fetched only once if (messagingConfig == null) { throw new ArgumentException("messageMapper.MessagingConfig returned null", "messageMapper"); } if (messageMapper.SupportedExchangeKinds == default(ExchangeKind)) { throw new ArgumentException("messageMapper.SupportedExchangeKinds is not set up.", "messageMapper"); } serviceName = (messageMapper.GetServiceName(null) ?? String.Empty).Trim(); subscriberIdHeader = new string[] { AmqpUtils.GetNewExclusiveQueueId() }; this.connectionFactory = new ConnectionFactory(); connectionFactory.Uri = new Uri(messageMapper.ServerUris[0].Uri); ConnectionNames = messageMapper.ServerUris.Select(u => u.FriendlyName ?? String.Empty).ToArray(); connectionFactory.RequestedHeartbeat = Client.RPCStrategyHelpers.HEART_BEAT; this.Settings = settings ?? new SubscriberSettings(); //Make sure a default value is set, if not supplied by user. this.Settings.Subscriber = this; //Indicate that the subcriber settings is owned by this subscriber. }
/// <summary> /// The <see cref="CommandProcessor"/> wants to support <see cref="CommandProcessor.Post{T}(T)"/> or <see cref="CommandProcessor.Repost"/> using Task Queues. /// You need to provide a policy to specify how QoS issues, specifically <see cref="CommandProcessor.RETRYPOLICY "/> or <see cref="CommandProcessor.CIRCUITBREAKER "/> /// are handled by adding appropriate <see cref="Policies"/> when choosing this option. /// /// </summary> /// <param name="configuration">The Task Queues configuration.</param> /// <returns>INeedARequestContext.</returns> public INeedARequestContext TaskQueues(MessagingConfiguration configuration) { messageStore = configuration.MessageStore; messagingGateway = configuration.MessagingGateway; messageMapperRegistry = configuration.MessageMapperRegistry; return(this); }
protected override byte PacketProperty => 0x08; // LiteNetLib.PacketProperty.UnconnectedMessage public MasterServerMessageSource( MessagingConfiguration configuration, IMessageReader messageReader, IEncryptedMessageReader encryptedMessageReader) : base(configuration, messageReader, encryptedMessageReader) { }
/// <summary> /// Creates a new connection instance. /// </summary> /// <param name="messagingSettings">Qbes messaging configuration /// node</param> /// <param name="connection">NetConnection object</param> /// <param name="callback">Callback for completed received multipart /// messages</param> public Connection(MessagingConfiguration messagingSettings, NetConnection connection, CompletedReceivedMultipartMessage callback) { _MaxMessageSize = messagingSettings.MaxMessageSize; _Connection = connection; _RemoteEndPoint = connection.RemoteEndPoint; _CompletedReceivedMultipartCallback = callback; }
internal MessageTrackExpression(JasperSettings settings, MessagingConfiguration bus, RoutingScope routingScope, string match) { _settings = settings; _bus = bus; _routingScope = routingScope; _match = match; }
public ConsumerHostedService(IMessagingFactory messagingFactory, IMessagingService <PingPongExample> messagingService, ILogger <ConsumerHostedService> logger, IOptions <MessagingConfiguration> messagingConfiguration) { _messagingFactory = messagingFactory; _messagingService = messagingService; _logger = logger; _messagingConfiguration = messagingConfiguration.Value; }
public DirectChannelConfiguration(EndpointAddress address, MessagingConfiguration messagingConfiguration) { Contract.Requires(messagingConfiguration != null); Contract.Requires(address != null); this.messagingConfiguration = messagingConfiguration; this.address = address; }
protected override byte PacketProperty => 0x08; // LiteNetLib.PacketProperty.UnconnectedMessage public MasterServerMessageDispatcher( MessagingConfiguration configuration, MasterServerMessageSource messageSource, IMessageWriter messageWriter, IEncryptedMessageWriter encryptedMessageWriter) : base(configuration, messageSource, messageWriter, encryptedMessageWriter) { }
private void SetupChannel(MessagingConfiguration messagingConfiguration) { _connection = _connectionFactory.CreateConnection(); _channel = _connection.CreateModel(); _channel.ExchangeDeclare(messagingConfiguration.ExchangeName, messagingConfiguration.Type, messagingConfiguration.Durable, messagingConfiguration.AutoDelete); _channel.QueueDeclare(messagingConfiguration.QueueName, messagingConfiguration.Durable, false, messagingConfiguration.AutoDelete, null); _channel.QueueBind(messagingConfiguration.QueueName, messagingConfiguration.ExchangeName, messagingConfiguration.RoutingKey); }
public void Configure(MessagingConfiguration toConfigureAgainst, MessageServerConfiguration serverToConfigureAgainst) { var catalog = new DirectoryCatalog(GetPath(), "*.ExternalConfiguration.dll"); var container = new CompositionContainer(catalog); container.ComposeParts(this); this.Sources.ForEach(s => s.Configure(toConfigureAgainst, serverToConfigureAgainst)); }
/// <summary> /// Creates a default configuration instance. /// </summary> public NetworkConfiguration() { AutoConnect = DefaultAutoConnect; IpAddress = DefaultIpAddress; Messaging = new MessagingConfiguration(); PlayerName = Environment.UserName; PortUdp = DefaultPortUdp; PortTcp = DefaultPortTcp; }
public PublisherConfiguration(EndpointAddress address, MessagingConfiguration messagingConfiguration) : base(messagingConfiguration) { schema = new PublisherChannelSchema { FromAddress = address, MessageFilterStrategy = new PassThroughMessageFilterStategy() }; }
private void RegisterCommandProcessor() { //create handler var subscriberRegistry = new SubscriberRegistry(); RegisterBrighterHandlersFromAssembly( typeof(IHandleRequestsAsync <>), new Assembly[] { typeof(NewShipRegistrationHandlerAsync).Assembly }, typeof(IHandleRequestsAsync <>).GetTypeInfo().Assembly, subscriberRegistry); //create policies var retryPolicy = Policy.Handle <Exception>().WaitAndRetry(new[] { TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150) }); var circuitBreakerPolicy = Policy.Handle <Exception>().CircuitBreaker(1, TimeSpan.FromMilliseconds(500)); var retryPolicyAsync = Policy.Handle <Exception>().WaitAndRetryAsync(new[] { TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(150) }); var circuitBreakerPolicyAsync = Policy.Handle <Exception>().CircuitBreakerAsync(1, TimeSpan.FromMilliseconds(500)); var policyRegistry = new Paramore.Brighter.PolicyRegistry() { { CommandProcessor.RETRYPOLICY, retryPolicy }, { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }, { CommandProcessor.RETRYPOLICYASYNC, retryPolicyAsync }, { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicyAsync } }; var servicesHandlerFactory = new ServicesHandlerFactoryAsync(_container); var messagingGatewayConfiguration = RmqGatewayBuilder.With.Uri(new Uri(Configuration["Broker:Uri"])) .Exchange(Configuration["Broker:Exchange"]) .DefaultQueues(); var gateway = new RmqMessageProducer(messagingGatewayConfiguration); var sqlMessageStore = new MySqlMessageStore(new MySqlMessageStoreConfiguration(Configuration["Database:MessageStore"], Configuration["Database:MessageTableName"])); var messageMapperFactory = new MessageMapperFactory(_container); var messageMapperRegistry = new MessageMapperRegistry(messageMapperFactory); RegisterMessageMappersFromAssembly( new Assembly[] { typeof(LineNameUpdatedEventMessageMapper).Assembly }, typeof(IAmAMessageMapper <>).GetTypeInfo().Assembly, messageMapperRegistry); var messagingConfiguration = new MessagingConfiguration( messageStore: sqlMessageStore, messageProducer: gateway, messageMapperRegistry: messageMapperRegistry); var commandProcessor = CommandProcessorBuilder.With() .Handlers(new Paramore.Brighter.HandlerConfiguration(subscriberRegistry, servicesHandlerFactory)) .Policies(policyRegistry) .TaskQueues(messagingConfiguration) .RequestContextFactory(new Paramore.Brighter.InMemoryRequestContextFactory()) .Build(); _container.RegisterInstance <IAmACommandProcessor>(commandProcessor); }
/// <summary> /// Creates an instance with default settings. /// </summary> public NetworkConfiguration() { InitialMSPerKBSendTimeout = DefaultInitialMSPerKBSendTimeout; MaxConnections = DefaultMaxConnections; MaxTerrainBatchSize = DefaultMaxTerrainBatchSize; Messaging = new MessagingConfiguration(); PortUdp = DefaultPortUdp; PortTcp = DefaultPortTcp; Web = new WebConfiguration(); }
public void Setup() { _messagingConfig = new MessagingConfiguration(); _adapter = new Mock <IMessageAdapter>(); _callContextFactory = new Mock <ICallContextFactory>(); _callContextFactory.Setup(x => x.Create()) .Returns(new EmptyCallContext()); _queueConfiguration = new Mock <QueueConfigurationBase>(); }
public static MessagingConfiguration UseInMemory(this MessagingConfiguration messagingConfiguration) { messagingConfiguration .Services .AddSingleton <BlockingCollection <(Type, object)>, BlockingCollection <(Type, object)> >() .AddSingleton <IMessageReceiver, InMemoryMessageReceiver>() .AddSingleton <IMessagePublisher, InMemoryMessagePublisher>(); return(messagingConfiguration); }
public MultipartMessageService( MessagingConfiguration messagingConfiguration, IMessageReader messageReader) { _messagingConfiguration = messagingConfiguration; _messageReader = messageReader; _logger = Log.ForContext <MultipartMessageService>(); _multipartMessageWaiters = new ConcurrentDictionary <uint, MultipartMessageWaiter>(); }
public Guid Subscribe(MessagingConfiguration messagingConfiguration, IRabbitMessageHandler messageHandler) { var consumer = new TSubscriber(); var consumerId = Guid.NewGuid(); _consumers.TryAdd(consumerId, consumer); consumer.Consume(messagingConfiguration, messageHandler); return(consumerId); }
public void Get(MessagingConfiguration messagingConfiguration, IRabbitMessageHandler messageHandler) { SetupChannel(messagingConfiguration); var result = _channel.BasicGet(messagingConfiguration.QueueName, true); while (result != null) { messageHandler.Handle(result); result = _channel.BasicGet(messagingConfiguration.QueueName, true); } }
/// <summary> /// The <see cref="CommandProcessor"/> wants to support <see cref="CommandProcessor.Post{T}(T)"/> or <see cref="CommandProcessor.Repost"/> using Task Queues. /// You need to provide a policy to specify how QoS issues, specifically <see cref="CommandProcessor.RETRYPOLICY "/> or <see cref="CommandProcessor.CIRCUITBREAKER "/> /// are handled by adding appropriate <see cref="Policies"/> when choosing this option. /// /// </summary> /// <param name="configuration">The Task Queues configuration.</param> /// <returns>INeedARequestContext.</returns> public INeedARequestContext TaskQueues(MessagingConfiguration configuration) { _useTaskQueues = true; _messageStore = configuration.MessageStore; _asyncMessageStore = configuration.AsyncMessageStore; _messagingGateway = configuration.MessageProducer; _asyncMessagingGateway = configuration.AsyncMessageProducer; _messageMapperRegistry = configuration.MessageMapperRegistry; _messageStoreWriteTimeout = configuration.MessageStoreWriteTimeout; _messagingGatewaySendTimeout = configuration.MessagingGatewaySendTimeout; return(this); }
internal void Start(MessagingConfiguration messagingSettings, IPEndPoint remoteEndPoint) { NetworkComms.AppendGlobalIncomingPacketHandler <byte[]>(Connection.TcpByteMessageName, ReceivedMessageTcpBytes); NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", ReceivedMessageTcpString); ConnectionInfo connectionInfo = new ConnectionInfo(ClientWorldManager.Instance.Configuration.Network.IpAddress, ClientWorldManager.Instance.Configuration.Network.PortTcp); _ClientTcp = TCPConnection.GetConnection(connectionInfo, true); _Client.Start(); _Connection = new Connection(messagingSettings, _Client.Connect(remoteEndPoint), MultiPlayerProvider.ServerToClientProvider.ProcessReceivedMessage); _Connection.TcpConnection = _ClientTcp; }
/// <summary> /// Инициализирует компонент ссылками на <see cref="IConfiguration" />, /// <see cref="IMessageAdapterFactory" />, /// коллекции элементов <see cref="IMessageSerializer" /> и <see cref="IMessageDeserializer" />> /// </summary> /// <param name="configuration">Провайдер конфигурации</param> /// <param name="adapterFactory">Фабрика адаптеров для очередей</param> /// <param name="serializers">Коллекция сериализаторов</param> /// <param name="deserializers">Коллекция десериализаторов</param> public MessagingComponentFactory( IConfiguration configuration, IMessageAdapterFactory adapterFactory, IReadOnlyCollection <IMessageSerializer> serializers, IReadOnlyCollection <IMessageDeserializer> deserializers, ICallContextFactory callContextFactory) { _adapterFactory = adapterFactory.ThrowIfNull(nameof(adapterFactory)); _serializers = serializers.ThrowIfNull(nameof(serializers)); _deserializers = deserializers.ThrowIfNull(nameof(deserializers)); _callContextFactory = callContextFactory.ThrowIfNull(nameof(callContextFactory)); _connectionOptions = configuration.ThrowIfNull(nameof(configuration)) .GetSection("messaging") .Get <MessagingConfiguration>(); }
public MessageDispatcher( MessagingConfiguration messagingConfiguration, IMessageWriter messageWriter, IEncryptedMessageWriter encryptedMessageWriter) { _messagingConfiguration = messagingConfiguration; _messageWriter = messageWriter; _encryptedMessageWriter = encryptedMessageWriter; _logger = Log.ForContext <MessageDispatcher>(); _requestAcknowledgementWaiters = new ConcurrentDictionary <uint, RequestAcknowledgementWaiter>(); }
public void WithSerializerShouldRegisterSerializer() { // Arrange. var config = new MessagingConfiguration<ICommandBusConfiguration>(); var serializer = A.Fake<ISerializer>(); // Act. config.WithSerializer(serializer); // Assert. Assert.Equal(serializer, config.Serializer); }
public void WithSerializerShouldRegisterSerializer() { // Arrange. var config = new MessagingConfiguration <ICommandBusConfiguration>(); var serializer = A.Fake <ISerializer>(); // Act. config.WithSerializer(serializer); // Assert. Assert.Equal(serializer, config.Serializer); }
public MessagingFactory(IOptions <MessagingConfiguration> messaging, ILogger <MessagingFactory> logger) { _messaging = messaging.Value; _logger = logger; _connectionFactory = new ConnectionFactory { Uri = new Uri(_messaging.ConnectionString), AutomaticRecoveryEnabled = true, RequestedHeartbeat = 200, DispatchConsumersAsync = true }; }
public BaseMessageSource( MessagingConfiguration configuration, IMessageReader messageReader, IEncryptedMessageReader encryptedMessageReader) { _configuration = configuration; _messageReader = messageReader; _encryptedMessageReader = encryptedMessageReader; _logger = Log.ForContext <BaseMessageSource>(); _multipartMessageWaiters = new ConcurrentDictionary <uint, MultipartMessageWaiter>(); _responseWaiters = new ConcurrentDictionary <uint, ResponseWaiter>(); _messageHandlers = new List <MessageHandler>(); _genericMessageHandlers = new Dictionary <Type, List <MessageHandler> >(); }
public BaseMessageDispatcher( MessagingConfiguration configuration, IMessageSource messageSource, IMessageWriter messageWriter, IEncryptedMessageWriter encryptedMessageWriter) { _configuration = configuration; _messageSource = messageSource; _messageWriter = messageWriter; _encryptedMessageWriter = encryptedMessageWriter; _logger = Log.ForContext <BaseMessageDispatcher>(); _acknowledgementWaiters = new ConcurrentDictionary <uint, AcknowledgementWaiter>(); _messageDispatchHandlers = new List <MessageDispatchHandler>(); }
public void WithSerializationFilterShouldRegisterFilter() { // Arrange. var config = new MessagingConfiguration <ICommandBusConfiguration>(); var filter = A.Fake <IMessageFilter>(); // Act. config.WithSerializationFilter(filter); config.MessageFilterInvoker.BeforeDeserialization(new Envelope <CreateOrderCommand>(new CreateOrderCommand()), new byte[0]) .Wait(); // Assert. A.CallTo(() => filter.BeforeDeserialization(A <Envelope <CreateOrderCommand> > .Ignored, A <byte[]> .Ignored)) .MustHaveHappened(Repeated.Exactly.Once); }
public void WithSerializationFilterShouldRegisterFilter() { // Arrange. var config = new MessagingConfiguration<ICommandBusConfiguration>(); var filter = A.Fake<IMessageFilter>(); // Act. config.WithSerializationFilter(filter); config.MessageFilterInvoker.BeforeDeserialization(new Envelope<CreateOrderCommand>(new CreateOrderCommand()), new byte[0]) .Wait(); // Assert. A.CallTo(() => filter.BeforeDeserialization(A<Envelope<CreateOrderCommand>>.Ignored, A<byte[]>.Ignored)) .MustHaveHappened(Repeated.Exactly.Once); }
public static MessagingConfiguration UseRabbitMQ( this MessagingConfiguration messagingConfiguration, Action <IConnectionFactory> connectionFactoryBuilder) { var connectionFactory = new ConnectionFactory(); connectionFactoryBuilder(connectionFactory); messagingConfiguration .Services .AddSingleton <IConnectionFactory>(connectionFactory) .AddSingleton <IMessageReceiver, RabbitMQMessageReceiver>() .AddSingleton <IMessagePublisher, RabbitMQMessagePublisher>(); return(messagingConfiguration); }
public DirectRequestReplyReceiverConfiguration(MessagingConfiguration messagingConfiguration, EndpointAddress address) : base(messagingConfiguration) { Contract.Requires(messagingConfiguration != null); Contract.Requires(address != null); receiveSchema = new RequestReceiverSchema { Address = address, FilterStrategy = new PassThroughMessageFilterStategy() }; sendSchema = new ReplySenderSchema() { Address = address }; }
public PointToPointSenderConfiguration( EndpointAddress fromAddress, EndpointAddress toAddress, MessagingConfiguration messagingConfiguration, ISystemTime systemTime) : base(messagingConfiguration) { this.systemTime = systemTime; sendSchema = new PointToPointSendChannelSchema { ExpiryStrategy = new PassthroughMessageExpiryStrategy(), ExpiryAction = () => { }, FilteringStrategy = new PassThroughMessageFilterStategy(), ReceiverAddress = toAddress, FromAddress = fromAddress }; RepeatMessages().WithDefaultEscalationStrategy(); }