コード例 #1
0
ファイル: Global.asax.cs プロジェクト: bmegias/RabbitMQSample
 static RabbitUtils()
 {
     var serviceName = typeof(RabbitUtils).FullName;
     var cfg = new[] { new HandlerConfig<HelloResponse>(null) };
     _subscriber = new RabbitSubscriber(RabbitCfg.XCHG, serviceName, RabbitCfg.HOST, cfg);
     _publisher = new RabbitPublisher(RabbitCfg.XCHG, RabbitCfg.HOST, _subscriber);
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: bmegias/RabbitMQSample
        static void Main(string[] args)
        {
            var names = new[]
            {
                "Brau", "Raul", "Oriol", "Xavi", "Rocio", "Juanjo"
            };

            Console.WriteLine("***** RPC Client *****");
            var tot = 0;
            var serviceName = typeof(Program).Namespace.ToLowerInvariant();

            var cfg = new[] { new HandlerConfig<HelloResponse>(null) };
            var sub = new RabbitSubscriber(RabbitCfg.XCHG, serviceName, RabbitCfg.HOST, cfg);
            var pub = new RabbitPublisher(RabbitCfg.XCHG, RabbitCfg.HOST, sub);

            sub.StartAsyncMessageLoop();

            names
                .AsParallel()
                .ForAll(name =>
            {
                var corId = Guid.NewGuid().ToString();

                pub.PublishRequest<HelloRequest, HelloResponse>(
                    corId
                    , new HelloRequest() { Name = name }
                    , response =>
                    {
                        Console.WriteLine("Received CorrelationId: {0} Message: {1}"
                                               , corId
                                               , MessageBase.ToJson(response));
                    });
            });
        }
コード例 #3
0
        public async Task OneExchangePerService_NetworkConfiguration_AsExpected_Event()
        {
            try
            {
                bool eventReceived = false;
                var  networkInfos  = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.ExchangePerService);

                networkInfos.DistantExchangeDescriptions.Add(
                    new RabbitExchangeDescription(firstProducerEventExchangeName)
                    );

                var serviceQueue = networkInfos.ServiceQueueDescriptions[0];
                serviceQueue.Bindings.Add(new RabbitQueueBindingDescription(firstProducerEventExchangeName));

                var config = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = false,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.EventCustomCallback = (e) => eventReceived = e is RabbitEvent;
                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config,
                    scopeFactory);

                subscriber.Start();

                var enveloppeWithFirstEvent = GetEnveloppeDataForEvent(publisher: "pub1", content: "data");

                _channel.BasicPublish(
                    exchange: firstProducerEventExchangeName,
                    routingKey: "",
                    basicProperties: null,
                    body: enveloppeWithFirstEvent);

                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (eventReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }

                eventReceived.Should().BeTrue();
            }
            finally
            {
                DeleteData();
            }
        }
コード例 #4
0
        public void Subscriber()
        {
            ISubscriber <TestMessage> sub = new RabbitSubscriber <TestMessage>(Options);

            sub.ConsumeEvent += (sender, args) =>
            {
                Assert.NotNull(args.Message);
            };
            sub.Init();
        }
コード例 #5
0
        public async Task RabbitMQSubscriber_Should_Consider_AckStrategy_Ack_On_Receive_Fail_Should_Remove_MessageFromQueue_CallbackExc()
        {
            try
            {
                var networkInfos = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);

                var config = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = true,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    AckStrategy        = AckStrategy.AckOnReceive
                };
                config.EventCustomCallback += (_) => throw new InvalidOperationException();

                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config);

                subscriber.Start();

                var evt = new ExceptionEvent();

                _channel.BasicPublish(
                    Consts.CONST_CQE_EXCHANGE_NAME,
                    "",
                    body: Encoding.UTF8.GetBytes(
                        JsonConvert.SerializeObject(
                            new Enveloppe(
                                JsonConvert.SerializeObject(evt), typeof(ExceptionEvent), publisher1Name))));
                await Task.Delay(250);

                int            awaitedTime = 0;
                BasicGetResult result      = null;
                while (awaitedTime <= 750)
                {
                    result = _channel.BasicGet(Consts.CONST_DEAD_LETTER_QUEUE_NAME, true);
                    if (result != null)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }
                result.Should().BeNull();
            }
            finally
            {
                DeleteData();
            }
        }
コード例 #6
0
        public async Task RabbitSubscriber_Should_Consider_AckStrategy_Ack_On_Success_CallbackExc()
        {
            try
            {
                bool eventReceived = false;
                var  messages      = new List <object>();
                var  networkInfos  = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);

                var config = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = true,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.EventCustomCallback = (e) => { messages.Add(e); eventReceived = true; };

                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config);

                subscriber.Start();

                var evt = new AutoAckEvent();

                _channel.BasicPublish(
                    Consts.CONST_CQE_EXCHANGE_NAME,
                    "",
                    body: Encoding.UTF8.GetBytes(
                        JsonConvert.SerializeObject(
                            new Enveloppe(
                                JsonConvert.SerializeObject(evt), typeof(AutoAckEvent), publisher1Name))));
                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (eventReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }
                eventReceived.Should().BeTrue();
                var result = _channel.BasicGet(Consts.CONST_DEAD_LETTER_QUEUE_NAME, true);
                result.Should().BeNull();
            }
            finally
            {
                DeleteData();
            }
        }
コード例 #7
0
        public async Task Command_Should_Be_Send_AsDirect()
        {
            try
            {
                bool commandReceived = false;
                var  networkInfos    = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);
                var  serviceQueue    = networkInfos.ServiceQueueDescriptions[0];
                var  config          = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = false,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.CommandCustomCallback = (c) => commandReceived = c is RabbitCommand;

                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config,
                    scopeFactory);

                subscriber.Start();

                var enveloppeWithCommand = GetEnveloppeDataForCommand(publisher: "pub1", content: "data");

                _channel.BasicPublish(
                    exchange: "",
                    routingKey: serviceQueue.QueueName,
                    basicProperties: null,
                    body: enveloppeWithCommand);

                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (commandReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }

                commandReceived.Should().BeTrue();
            }
            finally
            {
                DeleteData();
            }
        }
コード例 #8
0
        public async Task StartAsync_WhenSettingsIsInvalid_ShouldRaiseOnConnectionEventAsync()
        {
            //Arrange
            var eventTrigged = false;
            var settings     = Options.Create(new RabbitSettings());
            var sut          = new RabbitSubscriber(settings);

            sut.OnConnectionError += async(sender, @event) =>
            {
                eventTrigged = true;
                await Task.CompletedTask;
            };

            //Act
            await sut.StartAsync(default);
コード例 #9
0
        public async Task OneExchange_Network_Configuration_AsExpected_Event()
        {
            try
            {
                bool eventReceived = false;
                var  networkInfos  = RabbitNetworkInfos.GetConfigurationFor("sub1", RabbitMQExchangeStrategy.SingleExchange);
                var  config        = new RabbitSubscriberConfiguration
                {
                    UseDeadLetterQueue = false,
                    ConnectionInfos    = GetConnectionInfos(),
                    NetworkInfos       = networkInfos,
                    DispatchInMemory   = false
                };
                config.EventCustomCallback = (e) => eventReceived = e is RabbitEvent;
                var subscriber = new RabbitSubscriber(
                    _loggerFactory,
                    config,
                    scopeFactory);

                subscriber.Start();

                var enveloppeWithFirstEvent = GetEnveloppeDataForEvent(publisher: "pub1", content: "data");

                _channel.BasicPublish(
                    exchange: Consts.CONST_CQE_EXCHANGE_NAME,
                    routingKey: "",
                    basicProperties: null,
                    body: enveloppeWithFirstEvent);

                int awaitedTime = 0;
                while (awaitedTime <= 2000)
                {
                    if (eventReceived)
                    {
                        break;
                    }
                    await Task.Delay(10);

                    awaitedTime += 10;
                }

                eventReceived.Should().BeTrue();
            }
            finally
            {
                DeleteData();
            }
        }
コード例 #10
0
        public static void PublishMessageTest()
        {
            IRabbitPublisherConfiguration publishConfig = new RabbitPublisherConfiguration();
            RabbitPublisher <CommandArgs> publisher     = new RabbitPublisher <CommandArgs>(publishConfig);

            IRabbitSubscriberConfiguration subscriberConfig = new RabbitSubscriberConfiguration();
            SandboxConsumer consumer = new SandboxConsumer();

            RabbitSubscriber <SandboxConsumer> subscriber = new RabbitSubscriber <SandboxConsumer>(consumer, subscriberConfig);

            subscriber.Start();

            publisher.Publish(new CommandArgs {
                Value = "some data"
            });



            Console.ReadKey();
        }
コード例 #11
0
ファイル: Startup.cs プロジェクト: edmd/glimpse
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();

            services.AddDbContext <DataContext>(options =>
                                                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                                                .EnableSensitiveDataLogging());
            services.AddTransient <DbContext, DataContext>();

            services.AddHttpClient <RequestResponseClient>("RequestResponseClient", client => {
                client.Timeout = TimeSpan.FromSeconds(10);
            });

            services.AddTransient <IRequestResponseRepository>(ctx => {
                var context = ctx.GetRequiredService <DataContext>();
                var requestResponseRepository = new RequestResponseRepository(context);
                return(requestResponseRepository);
            });

            services.AddTransient <IHttpResponseEventRepository>(ctx => {
                var context = ctx.GetRequiredService <DataContext>();
                var httpResponseEventRepository = new HttpResponseEventRepository(context);
                return(httpResponseEventRepository);
            });

            services.AddTransient <IHttpClientInstance>(ctx => {
                var requestResponseClient = ctx.GetRequiredService <RequestResponseClient>().Client;
                var httpClientInstance    = new HttpClientInstance(requestResponseClient);
                return(httpClientInstance);
            });

            services.AddTransient <IConnectionFactory>(ctx => {
                var connStr     = this.Configuration["Rabbit"];
                var connFactory = new ConnectionFactory()
                {
                    Uri = new Uri(connStr),
                    DispatchConsumersAsync = true // This is mandatory to have Async Subscribers
                };
                return(connFactory);
            });

            services.AddTransient <IBusConnection>(ctx => {
                var connFactory          = ctx.GetRequiredService <IConnectionFactory>();
                var persistentConnection = new RabbitPersistentConnection(connFactory);
                return(persistentConnection);
            });


            services.AddTransient <IHttpEventManager>(ctx => {
                var requestRepo      = ctx.GetRequiredService <IRequestResponseRepository>();
                var connection       = ctx.GetRequiredService <IBusConnection>();
                var httpEventManager = new HttpEventManager(requestRepo, connection);
                return(httpEventManager);
            });

            services.AddTransient <ISubscriber>(ctx => {
                var busConn    = ctx.GetRequiredService <IBusConnection>();
                var subscriber = new RabbitSubscriber(busConn);
                return(subscriber);
            });

            var channel = System.Threading.Channels.Channel.CreateBounded <RequestResponse>(100);

            services.AddSingleton(channel);

            services.AddTransient <IProducer>(ctx =>
            {
                var channel     = ctx.GetRequiredService <System.Threading.Channels.Channel <RequestResponse> >();
                var logger      = ctx.GetRequiredService <ILogger <RequestResponseProducer> >();
                var instance    = ctx.GetRequiredService <IHttpClientInstance>();
                var requestRepo = ctx.GetRequiredService <IRequestResponseRepository>();
                var eventRepo   = ctx.GetRequiredService <IHttpResponseEventRepository>();
                var producer    = new RequestResponseProducer(channel.Writer, logger, instance, eventRepo);
                return(producer);
            });

            services.AddTransient <IConsumer>(ctx =>
            {
                var channel  = ctx.GetRequiredService <System.Threading.Channels.Channel <RequestResponse> >();
                var logger   = ctx.GetRequiredService <ILogger <RequestResponseConsumer> >();
                var consumer = new RequestResponseConsumer(channel.Reader, logger, 1);
                return(consumer);
            });

            // DI'ing these as an IHostedService to automatically call the Start and Stop methods
            services.AddSingleton <IHostedService>(ctx =>
            {
                var logger                    = ctx.GetRequiredService <ILogger <BackgroundPublisherWorker> >();
                var httpEventManager          = ctx.GetRequiredService <IHttpEventManager>();
                var backgroundPublisherWorker = new BackgroundPublisherWorker(httpEventManager, logger);
                return(backgroundPublisherWorker);
            });

            services.AddSingleton <IHostedService>(ctx =>
            {
                var subscriber = ctx.GetRequiredService <ISubscriber>();
                var producer   = ctx.GetRequiredService <IProducer>();
                var consumer   = ctx.GetRequiredService <IConsumer>();
                var logger     = ctx.GetRequiredService <ILogger <BackgroundSubscriberWorker> >();
                var backgroundSubscriberWorker = new BackgroundSubscriberWorker(
                    subscriber, producer, new List <IConsumer>()
                {
                    consumer
                }, logger);
                return(backgroundSubscriberWorker);
            });

            //services.AddHostedService<BackgroundSubscriberWorker>(ctx =>
            //{
            //    var subscriber = ctx.GetRequiredService<ISubscriber>();
            //    var producer = ctx.GetRequiredService<IProducer>();
            //    var consumer = ctx.GetRequiredService<IConsumer>();
            //    var logger = ctx.GetRequiredService<ILogger<BackgroundSubscriberWorker>>();
            //    var backgroundSubscriberWorker = new BackgroundSubscriberWorker(
            //        subscriber, producer, new List<IConsumer>() { consumer }, logger);
            //    return backgroundSubscriberWorker;
            //});
        }
コード例 #12
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddDbContext <MentifiContext>(options =>
                                           options.UseSqlServer(Configuration.GetConnectionString("Hub3cConnection"))).AddUnitOfWork <MentifiContext>();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = Configuration["AuthUrl"];
                options.RequireHttpsMetadata = false;
            });

            services.AddScoped <IDeserializer, JsonDeserializer>();
            services.AddScoped <IUserProfileService, UserProfileService>();
            services.AddScoped <IApiClient, ApiClient>();
            services.AddScoped <IConnectionService, ConnectionService>();
            services.AddScoped <ILookupService, LookupService>();
            services.AddScoped <ISystemUserDeviceService, SystemUserDeviceService>();
            services.AddScoped <IHub3cFirebaseApi, Hub3CFirebaseApi>();
            services.AddScoped <IDashboardService, DashboardService>();
            services.AddScoped <INotificationService, NotificationService>();
            services.AddScoped <IEmailApi, EmailApi>();
            services.AddScoped <IBulletinService, BulletinService>();
            services.AddScoped <IDocumentService, DocumentService>();
            services.AddScoped <IBusInstance, BusInstance>();
            services.AddScoped <IGoalService, GoalService>();
            services.AddScoped <IGoalProgressService, GoalProgressService>();
            services.AddScoped <ITaskService, TaskService>();
            services.AddScoped <IMessageBoardService, MessageBoardService>();
            services.AddScoped <IMessageService, MessageService>();
            services.AddScoped <IProjectService, ProjectService>();
            services.AddScoped <IProjectTeamService, ProjectTeamService>();
            services.AddScoped <IAdminInvitationService, AdminInvitationService>();
            services.AddScoped <IInvitationLinkService, InvitationLinkService>();
            services.AddScoped <IExperienceService, ExperienceService>();
            services.AddScoped <IInformalExperienceService, InformalExperienceService>();
            services.AddScoped <ISubjectExperienceService, SubjectExperienceService>();
            services.AddScoped <ISubjectPreferenceService, SubjectPreferenceService>();
            services.AddScoped <IAdditionalActivityService, AdditionalActivityService>();
            services.AddScoped <IUserAddressService, UserAddressService>();
            services.AddScoped <IEducationService, EducationService>();

            var mongoOpt = Configuration.GetSection("MongoDbConfig");

            services.AddSingleton <IMongoClient>(new MongoClient(mongoOpt.GetSection("Host").Value));
            services.AddSingleton <IMongoRepository <Resource>, MongoRepository <Resource> >();

            // For Rabbit Subscriber
            var rabbitUsername = Configuration.GetSection("MessagingConfig")["RabbitUsername"];
            var rabbitPassword = Configuration.GetSection("MessagingConfig")["RabbitPassword"];
            var rabbitHost     = Configuration.GetSection("MessagingConfig")["RabbitServer"];
            var rabbitVHost    = Configuration.GetSection("MessagingConfig")["RabbitVHost"];

            var subscriber  = new RabbitSubscriber(rabbitUsername, rabbitPassword, rabbitHost, rabbitVHost);
            var rabbitBus   = new RabbitBus(rabbitHost, rabbitUsername, rabbitPassword, rabbitVHost);
            var busInstance = new BusInstance(rabbitBus);

            services.AddSingleton(subscriber);
            services.AddSingleton(rabbitBus);
            services.AddSingleton(busInstance);
            services.AddMvc(op =>
            {
                op.Filters.Add(new ValidateModelStateAttribute());
            });

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Mentify API", Version = "v1"
                });
                c.SwaggerDoc("v2", new Info {
                    Title = "Mentify API", Version = "v2"
                });

                c.DocInclusionPredicate((version, apiDesc) =>
                {
                    var versions = apiDesc.ControllerAttributes()
                                   .OfType <ApiVersionAttribute>()
                                   .SelectMany(attr => attr.Versions);

                    var values = apiDesc.RelativePath
                                 .Split('/');
                    values[1]            = version;
                    apiDesc.RelativePath = string.Join("/", values);

                    var versionParameter = apiDesc.ParameterDescriptions
                                           .SingleOrDefault(p => p.Name == "version");

                    if (versionParameter != null)
                    {
                        apiDesc.ParameterDescriptions.Remove(versionParameter);
                    }

                    //return true;

                    return(versions.Any(v => $"v{v.ToString()}" == version));
                });
                c.AddSecurityDefinition("Bearer",
                                        new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please insert JWT with Bearer into field",
                    Name        = "Authorization",
                    Type        = "apiKey",
                });

                c.IncludeXmlComments(GetXmlCommentsPath());
                c.DescribeAllEnumsAsStrings();
                c.DescribeAllParametersInCamelCase();
            });
            services.AddCors();
            services.AddApiVersioning(
                o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(new DateTime(2018, 2, 6), 1, 0);
            });
        }