public void TestRabbitMq() { RabbitMqConfig rabbitMqConfig = new RabbitMqConfig { Host = "10.10.10.110", UserName = "******", Password = "******", }; RabbitMqService rabbitMqService = new RabbitMqService(rabbitMqConfig); Task.Factory.StartNew(() => { while (true) { rabbitMqService.Publish("test-exchange", "test-queue", "test-exchange", "{\"Data\":\"啊实打实大苏打实打实打算大苏打\"}"); System.Threading.Thread.Sleep(1000); } }); Task.Factory.StartNew(() => { rabbitMqService.Subscribe <object>("test-queue", false, t => { var msg = JsonConvert.SerializeObject(t); Debug.WriteLine($"时间:{DateTime.Now},当前消息内容:{msg}"); System.Threading.Thread.Sleep(1000); }, false); }); while (true) { } }
private static void RefreshRabbitMqQueue(IServiceProvider serviceProvider) { var linkRepository = serviceProvider.GetService <IRepository <Link> >(); var unitOfWorkFactory = serviceProvider.GetService <IUnitOfWorkFactory>(); var rabbitMqConfiguration = serviceProvider.GetService <RabbitMqConfiguration>(); var rabbitMqService = new RabbitMqService(rabbitMqConfiguration); using (var uow = unitOfWorkFactory.GetUoW()) { var links = linkRepository.GetAll() .Where(x => x.LinkStatus == LinkStatus.Waiting) .ToArray(); foreach (var link in links) { var linkEvent = new LinkEvent { Id = link.Id, Href = link.Href }; var successfullySent = rabbitMqService.SendLinkEvent(linkEvent); link.LinkStatus = successfullySent ? LinkStatus.Queue : LinkStatus.Waiting; } uow.Commit(); } }
static void Main(string[] args) { var rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(60), Host = "localhost", UserName = "******", Password = "******" }); var input = Input(); while (input != "exit") { var log = new MessageModel { CreateDateTime = DateTime.Now, Msg = input }; rabbitMqProxy.Publish(log); input = Input(); } rabbitMqProxy.Dispose(); }
public void RabbitMqService_PublishMessage_When_Null_Throws_Exception() { string message = string.Empty; var rabbitMqService = new RabbitMqService(_rabbitMqOptionsMock.Object); rabbitMqService.PublishMessage(message); }
/// <summary> /// 发布消息到RabbitMQ /// </summary> /// <param name="msg"></param> public static void PublishMessage(MessageModel msg) { var ts = Task.Factory.StartNew(() => { string MQHost = new DataItemDetailBLL().GetItemValue("host", "MQConfig"); // MQ主机地址 string MQUser = new DataItemDetailBLL().GetItemValue("user", "MQConfig"); // MQ用户 string MQPwd = new DataItemDetailBLL().GetItemValue("pwd", "MQConfig"); // MQ密码 string isPush = new DataItemDetailBLL().GetItemValue("ispush", "MQConfig"); //是否推送 string MQVirHost = new DataItemDetailBLL().GetItemValue("virhost", "MQConfig"); //MQ虚拟主机名称 string port = new DataItemDetailBLL().GetItemValue("port", "MQConfig"); //端口号 port = string.IsNullOrWhiteSpace(port) ? "5672" : port; if (isPush == "1") { if (!string.IsNullOrWhiteSpace(MQHost)) { var rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(60), Host = MQHost, UserName = MQUser, Password = MQPwd, VirtualHost = MQVirHost, Port = int.Parse(port) }); rabbitMqProxy.Publish(msg); } } }); }
public void AddMessageToQueue(Payment payment) { var mImpl = new MailImpl(); var connection = RabbitMqService.RabbitMqConnection; var channel = RabbitMqService.RabbitMqModel; RabbitMqService.SetupInitialTopicQueue(channel); var basicProperties = channel.CreateBasicProperties(); basicProperties.DeliveryMode = 2; var envelope = new MailLetter { Envelope = "ParkingAds A/S", //to be replaced with customer email //[email protected] Recipient = "Customer", //to be replaced Mime = new Mime { From = "*****@*****.**", To = "*****@*****.**", Subject = "Receipt payment: ", // complete email subject with payment details TextVersion = "Dear customer, " + Environment.NewLine + Environment.NewLine + "Your payment receipment issued " + DateTime.Now + " is attached above. " + Environment.NewLine + "Thank you for your doing business with us ! ", //add payment details Attachments = new Attachments { Base64String = payment.Base64Receipt } } }; byte[] customerBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(envelope)); channel.BasicPublish(RabbitMqService.SerialisationExchangeName, RabbitMqService.SerialisationRoutingKey, basicProperties, customerBuffer); mImpl.SendMail(); }
private static void RunSerialisationDemo() { RabbitMqService commonService = new RabbitMqService(); using (var connection = commonService.RabbitMqConnection) { using (var channel = commonService.RabbitMqModel) { while (true) { commonService.SetupInitialTopicQueue(channel); var random = new Random(); MyMessage customer = new MyMessage() { body = "this is the body of the message", someVal = random.Next(1, 20) }; var basicProperties = channel.CreateBasicProperties(); basicProperties.DeliveryMode = 2; string jsonified = JsonConvert.SerializeObject(customer); byte[] customerBuffer = Encoding.UTF8.GetBytes(jsonified); //container for the exchange information // PublicationAddress address = new PublicationAddress(ExchangeType.Direct, RabbitMqService.SerialisationExchangeName, RabbitMqService.SerialisationQueueExchangeBinding); channel.BasicPublish(RabbitMqService.SerialisationExchangeName, RabbitMqService.SerialisationRoutingKey, basicProperties, customerBuffer); Console.WriteLine("Published message: " + jsonified); Thread.Sleep(1000); } } } }
static async Task Main(string[] args) { ConfigurationBuilder builder = new ConfigurationBuilder(); //builder.AddUserSecrets<OTHubSettings>(); builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false); IConfigurationRoot configuration = builder.Build(); var settings = new OTHubSettings(); configuration.Bind("OTHub", settings); settings.Validate(); //Add any new tables, indexes, columns etc to the database. This can only be used to upgrade somewhat recent databases. DatabaseUpgradeTask.Execute(); await RabbitMqService.Connect(); await SmartContractManager.Load(); Bootstrapper bootstrapper = new Bootstrapper(); bootstrapper.RunUntilExit(); }
static void Main(string[] args) { var rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(60), Host = "localhost", UserName = "******", Password = "******" }); var input = Input(); while (input != "exit") { var rpcMsgModel = new RpcMsgModel { CreateDateTime = DateTime.Now, Msg = input }; var result = rabbitMqProxy.RpcClient(rpcMsgModel); Console.WriteLine(result); input = Input(); } rabbitMqProxy.Dispose(); }
public JsonResult SendMsg(string message, string friend) { RabbitMqService obj = new RabbitMqService(); bool flag = obj.SendMessage(message, friend); return(Json(null)); }
static void publishSendReply(RabbitMqService rabbitMqProxy) { var beingIMEIINumber = 500000000000000; int loop = 100; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); string exchangeName = "terreply.exchange"; string queueName = "terreply_queue"; try { sw.Start(); Console.WriteLine("*****************消息发布开始******************"); string imei = string.Empty; int logId = 0; for (int i = 0; i < loop; i++) { for (int k = 0; k < 2; k++) { logId++; //rabbitMqProxy.Publish(exchangeName, queueName,"",GetSendReplyStr((beingIMEIINumber+i).ToString(), logId)); rabbitMqProxy.Publish(exchangeName, queueName, "", GetSendReplyStr((beingIMEIINumber + i).ToString(), logId)); } } System.Threading.Thread.Sleep(100); sw.Stop(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("总耗时:" + sw.Elapsed.Milliseconds); }
static void publishUpgradeStatus(RabbitMqService rabbitMqProxy) { var beingIMEIINumber = 500000000000000; int loop = 2; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); string exchangeName = "upgradestatus.exchange"; string queueName = "upgradestatus_queue"; try { sw.Start(); Console.WriteLine("*****************消息发布开始******************"); //升级任务详情ID;升级状态;IMEI;固件ID rabbitMqProxy.Publish(exchangeName, queueName, "", $"4377892;2;500000000000000;3612;0;VKEL_MT2503D_T100_1V0;FE00_2017/11/29;FE13"); rabbitMqProxy.Publish(exchangeName, queueName, "", $"4377880;2;867282032269330;3612;0;VKEL_MT2503D_T100_1V0;FE00_2017/11/29;FE13"); //rabbitMqProxy.Publish(exchangeName, queueName, "", $"3567095;2;500000000000000"); System.Threading.Thread.Sleep(100); sw.Stop(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("总耗时:" + sw.Elapsed.Milliseconds); }
public void OnGet([FromServices] RabbitMqService rabbitMq) { rabbitMq.Channel.QueueDeclare(queue: "TestQueue", durable: false, exclusive: false, autoDelete: false, arguments: null); var message = Encoding.UTF8.GetBytes("This is Working!!!!"); rabbitMq.Channel.BasicPublish("", routingKey: "TestQueue", basicProperties: null, body: message); }
static void Main(string[] args) { var rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(60), Host = "localhost", UserName = "******", Password = "******", }); System.Console.WriteLine("u 升级日志队列;r 设备应答队列;s 升级状态队列;"); while (true) { var input = Console.ReadLine().ToLower(); switch (input) { case "r": publishSendReply(rabbitMqProxy); break; case "s": publishUpgradeStatus(rabbitMqProxy); break; case "u": publishUpgradeLogSchedule(rabbitMqProxy); break; case "q": return; } } }
public static void PublishTest() { var rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(60), Host = "192.168.2.8", UserName = "******", Password = "******", VirtualHost = "PaymentVHost" }); while (true) { Thread.Sleep(1000); var input = Guid.NewGuid().ToString(); rabbitMqProxy.Publish(new MessageModel { Msg = input, CreateDateTime = DateTime.Now }); } Console.ReadLine(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("localhost", builder => { builder .WithOrigins("http://localhost:4200") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.AddDbContext <AppDbContext>(options => options.UseSqlServer(ConnectionBuilderHelper.GetDefaultConnectionString())); var rabbitMq = ConnectionBuilderHelper.BuildDefault().GetSection(nameof(RabbitMq)).Get <RabbitMq>(); services.AddSingleton <IRabbitMqService>(options => { var rabbitMqService = new RabbitMqService(rabbitMq); rabbitMqService.Start(); return(rabbitMqService); }); services.AddScoped <IFibCalcService, FibCalcService>(); services.AddScoped <IFibDbService, FibDbService>(); services.AddControllers(); }
public MessageService(RabbitMqService rabbitMqService, IOptions <ExchangeSettings> exchangeSettings, IOptions <QueueSettings> queueSettings, ILogger <MessageService> logger) { _rabbitMqService = rabbitMqService; _logger = logger; _exchangeSettings = exchangeSettings.Value; _queueSettings = queueSettings.Value; }
public Consumer(string queueName) { _rabbitMqService = new RabbitMqService(); var connection = _rabbitMqService.GetRabbitMqConnection(); var channel = connection.CreateModel(); ConsumerEvent = new EventingBasicConsumer(channel); // Received event'i sürekli listen modunda olacaktır. ConsumerEvent.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); //var data = $"{queueName} isimli queue üzerinden gelen mesaj: \"{message}\""; if (queueName == "MailLog") { var data = JsonConvert.DeserializeObject <List <MailLog> >(message); //işlemler } else if (queueName == "Customer") { var data = JsonConvert.DeserializeObject <List <Customer> >(message); //işlemler } }; channel.BasicConsume(queueName, true, ConsumerEvent); }
static void Main(string[] args) { RabbitMqService rabbitMqService = new RabbitMqService(); IConnection connection = rabbitMqService.GetRabbitMqConnection(); IModel model = connection.CreateModel(); //model.QueueDeclare(RabbitMqService.BadMessageBufferedQueue, true, false, false, null); RunBadMessageDemo(model); }
/// <summary> /// 自定义配置和消息处理方式 /// </summary> /// <param name="config"></param> /// <param name="handler"></param> public RabbitMQRpcService(RabbitMqConfig config, IMQMsgHandler handler) { //自定义MQ配置 this.rabbitMqService = new RabbitMqService(config); //自定义消息处理方式 this.mqMsgHandler = handler; }
public LinkController(IRepository <Link> linkRepository, IUnitOfWorkFactory unitOfWorkFactory, RabbitMqConfiguration rabbitMqConfiguration) { _linkRepository = linkRepository; _unitOfWorkFactory = unitOfWorkFactory; _rabbitMqService = new RabbitMqService(rabbitMqConfiguration); }
/// <summary> /// 自定义配置 /// </summary> /// <param name="config"></param> public RabbitMQRpcService(RabbitMqConfig config) { //自定义MQ配置 this.rabbitMqService = new RabbitMqService(config); //使用默认消息处理方式 this.mqMsgHandler = new DefaultMQMsgHandler(); }
public Consumer(string queueName) { _rabbitMqService = new RabbitMqService(); var connection = _rabbitMqService.GetRabbitMqConnection(); var channel = connection.CreateModel(); ConsumerEvent = new EventingBasicConsumer(channel); // Received event'i sürekli listen modunda olacaktır. ConsumerEvent.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); //var data = $"{queueName} isimli queue üzerinden gelen mesaj: \"{message}\""; if (queueName == "MailLog") { var data = JsonConvert.DeserializeObject <MailLog>(message); //işlemler new Repository.MailLogRepo().Insert(new MailLog() { Id = data.Id, CustomerId = data.CustomerId, Message = data.Message, Subject = data.Subject }); Form1.logMailLog++; Form.Text = $"Customer {Form1.logCustomer} - MailLog {Form1.logMailLog}"; } else if (queueName == "Customer") { var data = JsonConvert.DeserializeObject <List <Customer> >(message); var repo = new Repository.CustomerRepo(); for (var i = 0; i < data.Count; i++) { var item = data[i]; Form1.logCustomer++; Form.Text = $"Customer {Form1.logCustomer} - MailLog {Form1.logMailLog}"; repo.InsertForMark(new Customer() { Address = item.Address, Email = item.Email, Id = item.Id, Name = item.Name, Phone = item.Phone, Surname = item.Surname, RegisterDate = item.RegisterDate }); if (i % 100 == 0) { repo.Save(); } } repo.Save(); //işlemler } }; channel.BasicConsume(queueName, true, ConsumerEvent); }
static void Main(string[] args) { RabbitMqService rabbitMqService = new RabbitMqService(); IConnection connection = rabbitMqService.GetRabbitMqConnection(); IModel model = connection.CreateModel(); //model.QueueDeclare(RabbitMqService.BadMessageBufferedQueue, true, false, false, null); RunBadMessageDemo(model); }
static void Main(string[] args) { RabbitMqService commonService = new RabbitMqService(); IConnection connection = commonService.GetRabbitMqConnection(); IModel model = connection.CreateModel(); //ReceiveBufferedMessages(model); ReceiveChunkedMessages(model); }
static void Main(string[] args) { RabbitMqService messageService = new RabbitMqService(); IConnection connection = messageService.GetRabbitMqConnection(); IModel model = connection.CreateModel(); //ReceiveBadMessages(model); ReceiveBadMessageExtended(model); }
public MainService() { _rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(600), Host = "localhost", UserName = "******", Password = "******" }); }
public MainService() { _rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(60), Host = "192.168.1.109", UserName = "******", Password = "******" }); }
public async Task SongChange(DeezerState deezerState) { if (File.Exists("deezer.json")) { var lastSong = _playerFactoryService.GetCurrentSongInfo(); if ((DateTime.UtcNow - lastSong.LastModifed) > TimeSpan.FromMinutes(1)) { await _lastFMService.StartScrobble(new SongDetails { Album = lastSong.Album, Song = lastSong.Song, Artist = lastSong.Artist }); } } var context = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <ServerHub>(); if (context == null) { return; } var pandoraInfo = new PandoraResult { Album = deezerState.AlbumName, AlbumUri = deezerState.AlbumUri, Artist = deezerState.ArtistName, IsPlaying = deezerState.IsPlaying, LastModifed = deezerState.UpdatedUtc, Loved = false, Radio = deezerState.StreamName, Song = deezerState.SongName }; RabbitMqService.SongChange(pandoraInfo); context.Clients.All.pandoraRefresh(pandoraInfo); var song = new SongDetails() { Album = pandoraInfo.Album, Artist = pandoraInfo.Artist, Song = pandoraInfo.Song }; await _lastFMService.UpdateNowPlaying(song); var json = JsonConvert.SerializeObject(deezerState); File.WriteAllText("deezer.json", json, Encoding.UTF8); }
public bool SignalRTest(string param = null) { var context = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <ServerHub>(); if (context == null) { return(false); } RabbitMqService.Hello(param ?? "Call from server"); context.Clients.All.hello(param ?? "Call from server"); return(true); }
public MQService() { _rabbitMqProxy = new RabbitMqService(new MqConfig { AutomaticRecoveryEnabled = true, HeartBeat = 60, NetworkRecoveryInterval = new TimeSpan(60), Host = "localhost", UserName = "******", Password = "******", VirtualHost="test" }); }
static void Main(string[] args) { RabbitMqService rabbitMqService = new RabbitMqService(); IConnection connection = rabbitMqService.GetRabbitMqConnection(); IModel model = connection.CreateModel(); //SetupDurableElements(model); SendDurableMessageToDurableQueue(model); /* IBasicProperties basicProperties = model.CreateBasicProperties(); basicProperties.SetPersistent(true); byte[] payload = Encoding.UTF8.GetBytes("This is a persistent message from Visual Studio"); PublicationAddress address = new PublicationAddress(ExchangeType.Topic, "exchangeFromVisualStudio", "superstars"); model.BasicPublish(address, basicProperties, payload);*/ }