static void Main(string[] args) { using (bus = RabbitHutch.CreateBus("host=localhost;persistentMessages=false")) { Console.WriteLine("Retailer is running."); // Listen for order request messages from customers bus.SendReceive.Receive <OrderRequestMessage>("customerToRetailerQueue", message => HandleOrderRequest(message)); // Listen for order reply messages from warehouses (use a point-to-point channel). //SendRecieve.Recieve bus.SendReceive.Receive <OrderReplyMessage>("warehouseToRetailerQueue", message => HandleOrderReply(message)); // WRITE CODE HERE! // Block this thread so that the retailer program will not exit. Console.ReadLine(); } }
private void TryConnect() { if (IsConnected) { return; } var policy = Policy.Handle <EasyNetQException>() .Or <BrokerUnreachableException>() .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))); policy.Execute(() => { _bus = RabbitHutch.CreateBus(_connectionString); _advancedBus = _bus.Advanced; _advancedBus.Disconnected += OnDisconnect; }); }
public void Message_can_be_processed_but_not_ACKd() { var waitTime = TimeSpan.FromMinutes(2); var receivedEvent = new AutoResetEvent(false); var processedEvent = new AutoResetEvent(false); var bus = RabbitHutch.CreateBus("host=localhost"); const string queueName = "shutdown_test"; var message = Encoding.UTF8.GetBytes("Hello There!"); var queue = bus.Advanced.QueueDeclare(queueName); bus.Advanced.QueuePurge(queue); bus.Advanced.Consume(queue, (body, properties, info) => { // signal that message has been received (but not completed) receivedEvent.Set(); return(Task.Factory.StartNew(() => { Console.Out.WriteLine("Started processing."); Thread.Sleep(500); var receivedMessage = Encoding.UTF8.GetString(body); Console.Out.WriteLine("Completed: {0}", receivedMessage); processedEvent.Set(); })); }); bus.Advanced.Publish(Exchange.GetDefault(), queueName, false, new MessageProperties(), message); Console.Out.WriteLine("Published"); var signalReceived = receivedEvent.WaitOne(waitTime); Assert.True(signalReceived, $"Expected reset event within {waitTime.TotalSeconds} seconds"); Console.Out.WriteLine("Dispose Called"); bus.Dispose(); Console.Out.WriteLine("Disposed"); signalReceived = processedEvent.WaitOne(waitTime); Assert.True(signalReceived, $"Expected reset event within {waitTime.TotalSeconds} seconds"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton <ServiceLocator>(sp => { ServiceLocator locator = new ServiceLocator(); var redis = ConnectionMultiplexer.Connect("192.168.1.105:6379,name=venom"); var brandView = new OrderView(new RedisReadModelRepository <OrderDto>(redis.GetDatabase())); locator.BrandView = brandView; var eventMappings = new EventHandlerDiscovery() .Scan(brandView) .Handlers; var messageBusEndPoint = "Sales_readmodel"; var topicFilter = "Sales.Common.Events"; var b = RabbitHutch.CreateBus("host=192.168.1.105;username=test;password=test"); b.Subscribe <PublishedMessage>(messageBusEndPoint, m => { Aggregate handler; var messageType = Type.GetType(m.MessageTypeName); var handlerFound = eventMappings.TryGetValue(messageType, out handler); if (handlerFound) { var @event = JsonConvert.DeserializeObject(m.SerialisedMessage, messageType); handler.AsDynamic().ApplyEvent(@event, ((Event)@event).Version); } }, q => q.WithTopic(topicFilter)); var bus = new RabbitMqBus(b); locator.Bus = bus; return(locator); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
public void Listen() { using (IBus bus = RabbitHutch.CreateBus("host=localhost;persistentMessages=false")) { bus.Receive <ProductRequest>("customer_product_request", (message) => { Console.WriteLine(message.Product + " requested by " + message.Sender); OrderRequest requestMessage = getOrderRequest(message); bus.Send("warehouse_" + message.Country, requestMessage); bus.Receive <OrderResponse>(requestMessage.Sender, (response) => { if (response.Stock > 0) { ProductResponse responseMessage = getProductResponse(response); Console.WriteLine("Sending product info to " + message.Sender); bus.Send(message.Sender, responseMessage); } else { Console.WriteLine("No stock for " + message.Product); bus.Publish(requestMessage); } }); bool foundStock = false; bus.Receive <OrderResponse>("order_response", (response) => { if (!foundStock && response.Stock > 0) { Console.WriteLine("Received product with stock"); foundStock = true; ProductResponse product = getProductResponse(response); bus.Send(message.Sender, product); } }); }); Console.WriteLine("Waiting for customer order."); Console.ReadLine(); } }
/// <summary> /// 入口 /// </summary> /// <param name="args">参数</param> static void Main(string[] args) { var bus = RabbitHutch.CreateBus("host=localhost;username=dxq;password=dxq"); //接收简单消息 bus.Subscribe <MyTextMessage>("EasyNetMQ.Receiver.MyTextMessage", x => { Console.WriteLine($"接收了MyTextMessage消息:{x.Text}"); }); //接收Topic消息 bus.Subscribe <string>("EasyNetMQ.Receiver.TopicMyTextMessage", x => { var message = JsonConvert.DeserializeObject <MyTextMessage>(x); Console.WriteLine($"接收了Topic消息:{message.Text}"); }, o => { o.WithTopic(typeof(MyTextMessage).FullName); }); //接收高级消息 var queue = bus.Advanced.QueueDeclare("EasyNetMQ.Receiver.AdvanceMyTextMessage"); var exchange = bus.Advanced.ExchangeDeclare("EasyNetMQ.Exchange", ExchangeType.Topic); bus.Advanced.Bind(exchange, queue, routingKey: typeof(MyTextMessage).Name); bus.Advanced.Consume <string>(queue, (message, info) => { throw new Exception("处理消息时发送了错误"); //Console.WriteLine($"接收了高级消息:{message.Body}"); }); var errorqueue = new EasyNetQ.Topology.Queue("EasyNetQ_Default_Error_Queue", isExclusive: false); bus.Advanced.Consume <Error>(errorqueue, (message, info) => { Console.WriteLine($"接收了处理时发生异常的消息:{message.Body.Message}"); }); Console.WriteLine("按任意键退出"); Console.ReadKey(); bus.Dispose(); }
public async Task <IActionResult> Index() { //Notifications message = new Notifications(); using (var bus = RabbitHutch.CreateBus("host=localhost")) { bus.SubscribeAsync <CategoryGroups>("create_category_groups", groups => Task.Factory.StartNew(() => { var message = "Added Category Group: " + groups.Name; SubscriberViewModel.Notifications.Message = message; SubscriberViewModel.Notifications.NotificationType = "CategoryGroup"; })); bus.Subscribe <CategoryTypes>("create_category_types", categoryTypes => Task.Factory.StartNew(() => { var message = "Added Category Type: " + categoryTypes.Name; SubscriberViewModel.Notifications.Message = message; SubscriberViewModel.Notifications.NotificationType = "CategoryType"; })); //bus.Subscribe<Products>("create_product_by_admin", // categoryTypes => Task.Factory.StartNew(() => // { // var message = "Added Product by Admin: " + typeof(Products); // SubscriberViewModel.Notifications.Message = message; // SubscriberViewModel.Notifications.NotificationType = "ProductsByAdmin"; // })); } // persist if (SubscriberViewModel.Notifications.Message != null) { await _colibriDbContext.AddAsync(SubscriberViewModel.Notifications); await _colibriDbContext.SaveChangesAsync(); } return(View(SubscriberViewModel)); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("SQLite"), o => o.MigrationsAssembly(migrationsAssembly))); services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiScopes(Config.GetApiScopes()) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryClients(Config.GetClients()) .AddAspNetIdentity<IdentityUser>(); services.Configure<IdentityOptions>(options => { options.SignIn.RequireConfirmedAccount = false; options.SignIn.RequireConfirmedEmail = false; options.SignIn.RequireConfirmedPhoneNumber = false; options.Password.RequireDigit = false; options.Password.RequiredLength = 4; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequiredUniqueChars = 0; options.Password.RequireNonAlphanumeric = false; options.ClaimsIdentity.UserNameClaimType = ClaimTypes.Name; options.ClaimsIdentity.RoleClaimType = ClaimTypes.Role; }); services.AddControllers(); var rabbitMessageBus = new RabbitMqMessageBus(RabbitHutch.CreateBus(Configuration.GetConnectionString("RabbitMQ"))); services.AddSingleton<IMessageBus>(rabbitMessageBus); }
/// <summary> /// 创建服务总线 /// </summary> /// <param name="config"></param> /// <returns></returns> public static IBus CreateEventBus() { var config = SystemJsonConfigManage.GetInstance().AppSettings["MeessageService"]; if (string.IsNullOrEmpty(config)) { throw new Exception("消息地址未配置"); } if (bus == null && !string.IsNullOrEmpty(config)) { lock (lockHelper) { if (bus == null) { bus = RabbitHutch.CreateBus(config); } } } return(bus); }
public List <Model.Queue> PopulateMessageCounts(List <Model.Queue> deliveryQueues) { try { using (var advancedBus = RabbitHutch.CreateBus(_connectionString).Advanced) { foreach (var queue in deliveryQueues) { var existingQueue = new EasyNetQ.Topology.Queue(queue.Name, false); queue.MessageCount = advancedBus.MessageCount(existingQueue); } } return(deliveryQueues); } catch (Exception ex) { throw ex; } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var rabbitString = $"host={Configuration["RabbitMQ:HostName"]};"; rabbitString += "virtualHost=" + (Configuration["RabbitMQ:VirtualHost"] ?? "/") + ";"; rabbitString += $"username={Configuration["RabbitMQ:User"]};"; rabbitString += $"password={Configuration["RabbitMQ:Password"]}"; services.AddRazorPages(); services.AddSignalR(); services.AddControllersWithViews(); services.AddOptionsObjects(Configuration); services.AddSingleton <IBus>(RabbitHutch.CreateBus(rabbitString)); services.AddHostedService <AppointmentSubscriber>(); services.AddResponseCompression(opts => { opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat( new[] { "application/octet-stream" }); }); }
protected override void OnStart(string[] args) { var sqlConnectionString = ConfigurationManager.AppSettings["SqlConnectionString"]; var rabbitMqConnectionString = ConfigurationManager.AppSettings["RabbitMqConnectionString"]; _context = new EmpiriCallDbContext(new SqlConnection(sqlConnectionString)); using (var bus = RabbitHutch.CreateBus(rabbitMqConnectionString)) { bus.Subscribe <QueueMessage>("EmpiriCallQueueMessage", SaveRecordToDatabase); if (_showConsole) { Console.WriteLine("Now listening for messages of type: " + typeof(QueueMessage).FullName); Console.WriteLine("Press ENTER to stop."); Console.ReadLine(); } } base.OnStart(args); }
/// <summary> Subscribes this object. </summary> private void Subscribe() { Bus = RabbitHutch.CreateBus("host=localhost", x => { x.Register <IConventions, AttributeBasedConventions>(); x.EnableMessageVersioning(); }); IExchange exchange = Bus?.Advanced?.ExchangeDeclare("EvolvedAI", ExchangeType.Topic); IQueue queue = Bus?.Advanced?.QueueDeclare("Speech"); Bus?.Advanced?.Bind(exchange, queue, ""); Bus?.Subscribe <SpeechRequestMessage>(Environment.MachineName, msg => ProcessSpeechRequestMessage(msg), config => config?.WithTopic("Speech")); Bus?.Subscribe <WikipediaSearchMessage>(Environment.MachineName, msg => ProcessWikipediaSearchMessage(msg), config => config?.WithTopic("Speech")); }
internal static IServiceCollection AddServiceLayer(this IServiceCollection services, IConfiguration configuration) { var rabbitString = $"host={configuration["RabbitMQ:HostName"]};"; rabbitString += "virtualHost=" + (configuration["RabbitMQ:VirtualHost"] ?? "/") + ";"; rabbitString += $"username={configuration["RabbitMQ:User"]};"; rabbitString += $"password={configuration["RabbitMQ:Password"]}"; services .AddHttpClient() .AddSingleton <IExternalPatientApiService, ExternalPatientApiService>() .AddSingleton <IBus>(RabbitHutch.CreateBus(rabbitString)) .AddSingleton <IAppointmentPublisher, AppointmentPublisher>() .AddScoped <IAppointmentService, AppointmentService>() .AddTransient <ITimeSlotService, TimeSlotService>() .AddTransient <IConsultantService, ConsultantService>(); return(services); }
public void Should_be_able_to_replace_default_service_provider() { var bus = MockRepository.GenerateStub <IBus>(); var container = new MyAlternativeContainer(bus); try { RabbitHutch.SetContainerFactory(() => container); var resolvedBus = RabbitHutch.CreateBus("host=localhost"); resolvedBus.ShouldBeTheSameAs(bus); // Console.Out.WriteLine(container.RegisteredComponents); } finally { RabbitHutch.SetContainerFactory(() => new DefaultServiceProvider()); } }
public static void AddRabbitMq(this IServiceCollection services) { services.AddSingleton(typeof(RabbitMqOptions), service => { var configuration = service.GetRequiredService <IConfiguration>(); var options = new RabbitMqOptions(); configuration.GetSection("RabbitMq").Bind(options); return(options); }); services.AddTransient(typeof(IBus), service => { var options = service.GetRequiredService <RabbitMqOptions>(); return(RabbitHutch.CreateBus(options.ConnectionString)); }); services.AddTransient <IBusPublisher, BusPublisher>(); services.AddSingleton <IBusSubscriber, BusSubscriber>(); }
public void SetUp() { var loggers = new[] { new ConsoleLogger(), MockRepository.GenerateStub <IEasyNetQLogger>() }; rallyCount = 0; for (int i = 0; i < 2; i++) { buses[i] = RabbitHutch.CreateBus("host=localhost", x => x.Register(_ => loggers[i])); var name = string.Format("advanced_ping_pong_{0}", i); exchanges[i] = buses[i].Advanced.ExchangeDeclare(name, "direct"); queues[i] = buses[i].Advanced.QueueDeclare(name); buses[i].Advanced.QueuePurge(queues[i]); buses[i].Advanced.Bind(exchanges[i], queues[i], routingKey); } }
public static void Produce() { using (var bus = RabbitHutch.CreateBus("host=localhost")) { for (int i = 0; i < 3; i++) { string body = $"message No {i}"; byte[] bytes = Encoding.UTF8.GetBytes(body); var properties = new MessageProperties(); bus.Advanced.Publish( Exchange.GetDefault(), Stats.PIKA_QUEUE, false, properties, bytes); } System.Console.WriteLine("publishing done!"); } }
public static void Main(string[] args) { IBus myBus = null; try { myBus = RabbitHutch.CreateBus("host=localhost"); myBus.Subscribe <FutureMessage>("FutureMessageSub", msg => Console.WriteLine($"{DateTime.Now:T}: {msg.Content} (schedule at {msg.Timestamp:T})")); } catch (Exception ex) { Console.WriteLine(ex); } finally { myBus?.Dispose(); } Console.ReadLine(); }
public static void Receive() { using (var bus = RabbitHutch.CreateBus("host=localhost")) { //subscriptionId相同时,publisher消息轮流发送到Server //test为队列后缀名 //一个subscriptionId名称创建一个队列 //bus.Subscribe<TextMessage>("test", HandleTextMessage); //subscriptionId相同时,publisher消息同时发送到Server //string str = DateTime.Now.ToString(); //bus.Subscribe<TextMessage>(str, HandleTextMessage); AsyncSubscripe(bus); //var log = new NullLogger(); //log.DebugWrite("{0}", "ssss"); Console.WriteLine("Listening for messages. Hit <return> to quit."); Console.ReadLine(); } }
static void Main(string[] args) { var payment = new CardPaymentRequestMessage { Amount = 99.00m, CardHolderName = "Sample Card Holder", CardNumber = "1234589652369", ExpiryDate = "12/12" }; using (var bus = RabbitHutch.CreateBus("host=localhost")) { Console.WriteLine("publishing messages with request and response"); Console.WriteLine(); var response = bus.Request <CardPaymentRequestMessage, CardPaymentResponseMessage>(payment); Console.WriteLine(response.AuthCode); Console.WriteLine("response received"); Console.ReadLine(); } }
public void Init(string instanceAliasName, int instanceID, string[] args, Dictionary <string, string> settings) { _instanceID = instanceID; _instanceAliasName = instanceAliasName; string enableLoggingString; settings.TryGetValue("enableLogging", out enableLoggingString); bool enableLogging = false; if (enableLoggingString != null) { enableLogging = Boolean.Parse(enableLoggingString); } bus = RabbitHutch.CreateBus(settings["connectionString"], x => x.Register <IEasyNetQLogger>(_ => new PluginLogger(log, enableLogging))); OnInit(args, settings); }
public static void Main(string[] args) { IBus myBus = null; try { myBus = RabbitHutch.CreateBus("host=localhost"); Console.WriteLine("Verbindung wurde aufgebaut: {0}", myBus.IsConnected); } catch (Exception ex) { Console.WriteLine("Verbindung ist fehlgeschlagen"); Console.WriteLine(ex); } finally { myBus?.Dispose(); } Console.ReadLine(); }
public void Subscribe() { Bus = RabbitHutch.CreateBus("host=localhost", x => { x.Register <IConventions, AttributeBasedConventions>(); x.EnableMessageVersioning(); }); IExchange exchange = Bus.Advanced.ExchangeDeclare("EvolvedAI", EasyNetQ.Topology.ExchangeType.Topic); IQueue queue = Bus.Advanced.QueueDeclare("Deployments"); Bus.Advanced.Bind(exchange, queue, ""); Bus.Subscribe <DeploymentStartMessage>("Deployment.Start", msg => { ProcessDeploymentStartMessage(msg); }, config => config.WithTopic("Deployments")); Bus.Subscribe <DeploymentStopMessage>("Deployment.Stop", msg => { ProcessDeploymentStopMessage(msg); }, config => config.WithTopic("Deployments")); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDbContextPool <EmailContext>(options => options.UseMySql(Configuration.GetConnectionString("Me"))); services.AddScoped <IUnitOfWork, UnitOfWork <EmailContext> >(); services.Configure <EmailSettings>(Configuration); services.AddTransient <IHistoryService, HistoryService>(); services.AddTransient <IEmailService, EmailService>(); services.AddTransient <IHistoryRepository, HistoryRepository>(); services.AddSingleton(RabbitHutch.CreateBus(Configuration.GetSection("RabbitMQ:Connection").Value).Advanced); services.AddHostedService <EmailHandle>(); }
public void Register(ref ContainerBuilder container) { var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RabbitMQ"].ConnectionString; container.Register(c => RabbitHutch.CreateBus(connectionString)) .As <EasyNetQ.IBus>().SingleInstance(); container.RegisterType <Bus>() .As <IBus>() .SingleInstance() .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies) .EnableClassInterceptors(new Castle.DynamicProxy.ProxyGenerationOptions() { Hook = new A.Core.Interceptors.ForceVirtualMethodsHook() }) .InterceptedBy(typeof(A.Core.Interceptors.LogInterceptorProxy)) .InterceptedBy(typeof(A.Core.Interceptors.CacheInterceptorProxy)) .InterceptedBy(typeof(A.Core.Interceptors.TransactionInterceptorProxy)); }
public Task Run(CancellationToken cancellationToken) { bus = RabbitHutch.CreateBus("host=localhost"); bus.Advanced.Conventions.RpcRequestExchangeNamingConvention = type => customRpcRequestConventionDictionary.ContainsKey(type) ? customRpcRequestConventionDictionary[type] : defaultRpcExchange; bus.Advanced.Conventions.RpcResponseExchangeNamingConvention = type => customRpcResponseConventionDictionary.ContainsKey(type) ? customRpcResponseConventionDictionary[type] : defaultRpcExchange; bus.RespondAsync <TestModifiedRequestExhangeRequestMessage, TestModifiedRequestExhangeResponseMessage>(HandleModifiedRequestExchangeRequest); bus.RespondAsync <TestModifiedResponseExhangeRequestMessage, TestModifiedResponseExhangeResponseMessage>(HandleModifiedResponseExchangeRequest); bus.RespondAsync <TestAsyncRequestMessage, TestAsyncResponseMessage>(HandleAsyncRequest); bus.Respond <TestRequestMessage, TestResponseMessage>(HandleRequest); Console.WriteLine("Waiting to service requests"); Console.WriteLine("Press enter to stop"); Console.ReadLine(); return(Task.FromResult(0)); }
static void Main(string[] args) { Console.WriteLine("Starting DierenHok Service..."); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddInMemoryCollection(); IConfiguration configuration = builder.Build(); string rabbitConnectionString = configuration.GetValue <string>("Konijn"); var bus = RabbitHutch.CreateBus(rabbitConnectionString); DierenProvider.VolumeName = configuration.GetValue <string>("VolumeName"); SubscribeToBus(bus); Seed(); }
public static void Main(string[] args) { IBus myBus = null; try { myBus = RabbitHutch.CreateBus("host=localhost"); //SimpleSubscription(myBus); PolymorphicSubscription(myBus); } catch (Exception ex) { Console.WriteLine(ex); } finally { myBus?.Dispose(); } Console.ReadLine(); }
static void Main(string[] args) { var payment = new CardPaymentRequestMessage() { CardNumber = "1234567890544433", CardHolderName = "Mr Seun", ExpiryDate = "12/12", Amount = 99.00m }; using (var bus = RabbitHutch.CreateBus("host=localhost")) { Console.WriteLine("Publishing messages with request and response"); Console.WriteLine(); var task = bus.RequestAsync <CardPaymentRequestMessage, CardPaymentResponseMessage>(payment); task.ContinueWith(response => { Console.WriteLine("Got response : '{0}'", response.Result.AuthCode); }); Console.ReadLine(); } }