private static void Open(MqConfig config) { if (_conn != null) { return; } lock (LockObj) { var factory = new ConnectionFactory { //设置主机名 HostName = config.Host, //设置心跳时间 RequestedHeartbeat = config.HeartBeat, //设置自动重连 AutomaticRecoveryEnabled = config.AutomaticRecoveryEnabled, //重连时间 NetworkRecoveryInterval = config.NetworkRecoveryInterval, //用户名 UserName = config.UserName, //密码 Password = config.Password }; factory.AutomaticRecoveryEnabled = true; factory.NetworkRecoveryInterval = new TimeSpan(1000); _conn = _conn ?? factory.CreateConnection(); } }
private static void Open(MqConfig config) { if (_conn != null) { return; } lock (LockObj) { var factory = new ConnectionFactory { //设置主机名 HostName = config.Host, //设置心跳时间 RequestedHeartbeat = config.HeartBeat, //设置自动重连 AutomaticRecoveryEnabled = config.AutomaticRecoveryEnabled, //重连时间 NetworkRecoveryInterval = config.NetworkRecoveryInterval, //用户名 UserName = config.UserName, //密码 Password = config.Password }; factory.AutomaticRecoveryEnabled = true; factory.Endpoint = new AmqpTcpEndpoint(new Uri("amqp://192.168.1.109:5672/")); factory.VirtualHost = "/"; factory.NetworkRecoveryInterval = new TimeSpan(1000); _conn = _conn ?? factory.CreateConnection(); } }
/// <summary> /// 建立mq连接 /// </summary> /// <param name="config"></param> private static void Open(MqConfig config) { if (_conn != null) { return; } lock (LockObj) { //建立RabbitMq连接 var factory = new ConnectionFactory() { //是否自动重连 AutomaticRecoveryEnabled = config.AutomaticRecoveryEnabled, //重新连接间隔 NetworkRecoveryInterval = config.NetworkRecoveryInterval, //主机名 HostName = config.Host, //用户名 UserName = config.UserName, //密码 Password = config.Password, }; _conn = _conn ?? factory.CreateConnection(); } }
public SubscriptConsumerTests() { base.Setup(); var mqCofnig = new MqConfig(config.Host, config.Port, config.Username, config.Password, config.VirtualHost); _receiver = new SubscriptConsumer(mqCofnig); }
static void TestEventbus() { var config = new MqConfig { UserName = "******", Password = "******", HostIp = "localhost", Port = 5672, Exchange = "Eventbus", ExchangeType = "direct", VirtualHost = "/" }; var manager = new MessageHandlerManager(config); Console.WriteLine("请输入要发送的消息……"); var msg = Console.ReadLine(); while (msg != "exit") { var e = new TestEvent { Message = msg }; manager.PublishAsync(e); Console.WriteLine($"{e.EventTime:yyyy-MM-dd HH:mm:ss.fff} 发送消息 | {e.Id} {e.Message}"); Console.WriteLine("请输入要发送的消息……"); msg = Console.ReadLine(); } }
public void Client_prevents_times_out() { var clientConfig = new MqConfig { Ip = Config.Ip, Port = Config.Port, PingFrequency = 100 }; Client = new MqClient <SimpleMqSession, MqConfig>(clientConfig); Config.PingTimeout = 200; Server = new MqServer <SimpleMqSession, MqConfig>(Config); Client.Closed += (sender, args) => { if (args.CloseReason == SocketCloseReason.TimeOut) { TestStatus.Set(); } else { LastException = new Exception("Client closed for reason other than timeout."); } }; StartAndWait(false, 1500); if (TestStatus.IsSet) { throw new Exception("Client timed out."); } }
/// <summary> /// 开启服务 /// </summary> /// <param name="config"></param> private static void OpenRabbitMqService(MqConfig config) { if (_conn != null && _conn.IsOpen) { return; } lock (LockObj) { config.NetworkRecoveryInterval = TimeSpan.FromSeconds(10); var factory = new ConnectionFactory { //设置主机名 HostName = config.Host, //设置心跳时间 RequestedHeartbeat = config.HeartBeat, //设置自动重连 AutomaticRecoveryEnabled = config.AutomaticRecoveryEnabled, //重连时间 NetworkRecoveryInterval = config.NetworkRecoveryInterval, //用户名 UserName = config.UserName, //密码 Password = config.Password, //虚拟主机 VirtualHost = config.VirtualHost }; _conn = _conn ?? factory.CreateConnection(); } }
public void SetUp() { base.Setup(); var mqCofnig = new MqConfig(config.Host, config.Port, config.Username, config.Password, config.VirtualHost); _sender = new SubscriptPublisher(mqCofnig); }
/// <summary> /// Creates a frame with the specified parameters. /// Fixes common issues with frame creation. /// </summary> /// <param name="bytes">Byte buffer to add to this frame.</param> /// <param name="type">Type of frame to create.</param> /// <param name="config">Socket configurations for the frame to use.</param> /// <returns>Configured frame.</returns> public static MqFrame CreateFrame(byte[] bytes, MqFrameType type, MqConfig config) { if (type == MqFrameType.Ping || type == MqFrameType.Empty || type == MqFrameType.EmptyLast) { bytes = null; } return(new MqFrame(bytes, type, config)); }
public void Setup() { //AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "App.config"); config = ConfigurationManager.GetSection(MqConfig.DEFAULT_CONFIG_NAME) as MqConfig; if (config == null) { config = new MqConfig(); } }
public SubscriptConsumer(MqConfig config) { _config = config; var factory = new ConnectionFactory { HostName = _config.Host, Port = _config.Port, UserName = _config.Username, Password = _config.Password, VirtualHost = _config.VirtualHost }; connection = factory.CreateConnection(); channel = connection.CreateModel(); }
public MqTestsBase(ITestOutputHelper output) { Output = output; Port = FreeTcpPort(); Config = new MqConfig { Ip = "127.0.0.1", Port = Port }; Server = new MqServer <SimpleMqSession, MqConfig>(Config); Client = new MqClient <SimpleMqSession, MqConfig>(Config); }
public TaskPublisher(MqConfig config) { _config = config; var factory = new ConnectionFactory { HostName = _config.Host, Port = _config.Port, UserName = _config.Username, Password = _config.Password, VirtualHost = _config.VirtualHost }; connection = factory.CreateConnection(); channel = connection.CreateModel(); properties = channel.CreateBasicProperties(); properties.Persistent = true; //properties.DeliveryMode = 2; //持久化 另一种设置方式 }
public SubscriptPublisher(MqConfig config) { _config = config; var factory = new ConnectionFactory { HostName = _config.Host, Port = _config.Port, UserName = _config.Username, Password = _config.Password, VirtualHost = _config.VirtualHost }; connection = factory.CreateConnection(); channel = connection.CreateModel(); //properties = (IBasicProperties)(new MapMessageBuilder(channel).GetContentHeader()); //properties.Persistent = true; //properties.DeliveryMode = 2; }
static void MqInProcessTest() { var config = new MqConfig { Ip = "127.0.0.1", Port = 2828 }; Console.WriteLine("FrameBufferSize: {0}; SendAndReceiveBufferSize: {1}\r\n", config.FrameBufferSize, config.SendAndReceiveBufferSize); var smallMessage = new MqMessage { new MqFrame(SequentialBytes(50), MqFrameType.More, config), new MqFrame(SequentialBytes(50), MqFrameType.More, config), new MqFrame(SequentialBytes(50), MqFrameType.More, config), new MqFrame(SequentialBytes(50), MqFrameType.Last, config) }; MqInProcessPerformanceTests(1000000, 5, smallMessage, config); var medimumMessage = new MqMessage { new MqFrame(SequentialBytes(500), MqFrameType.More, config), new MqFrame(SequentialBytes(500), MqFrameType.More, config), new MqFrame(SequentialBytes(500), MqFrameType.More, config), new MqFrame(SequentialBytes(500), MqFrameType.Last, config) }; MqInProcessPerformanceTests(100000, 5, medimumMessage, config); var largeMessage = new MqMessage(); for (int i = 0; i < 20; i++) { largeMessage.Add(new MqFrame(SequentialBytes(3000), MqFrameType.More, config)); } MqInProcessPerformanceTests(10000, 5, largeMessage, config); Console.WriteLine("Performance complete"); Console.ReadLine(); }
/// <summary> /// 向容器注册mqclient服务。 /// 通过委托构建mq相关的配置选项 /// </summary> /// <param name="services">服务集合</param> /// <param name="optionsBuilder">构建mq配置选项的委托</param> /// <returns>服务集合</returns> public static IServiceCollection AddMqClient(this IServiceCollection services, Action <MqConfig> optionsBuilder) { if (optionsBuilder == null) { throw new ArgumentNullException(nameof(optionsBuilder)); } services.TryAddSingleton <ISerializer, Serializer>(); services.TryAddSingleton <IZaabeeRabbitMqClient>(serviceProvider => { var serializer = serviceProvider.GetRequiredService <ISerializer>(); var options = new MqConfig(); optionsBuilder.Invoke(options); return(new ZaabeeRabbitMqClient(options, serializer)); }); return(services); }
static void Main(string[] args) { var mqconfig = new MqConfig { UserName = "******", Password = "******", HostIp = "localhost", Port = 5672, VirtualHost = "/", Exchange = "Abs.Exchange", ExchangeType = "direct", Durable = true, AutoDelete = false }; var ehm = new MessageHandlerManager(mqconfig); //_eventbus = new EventBus(ehm); ehm.Register <HelloEvent>(new HelloEventHandler()); Console.ReadLine(); }
/// <summary> /// 创建MQ连接 /// </summary> /// <param name="config">mq配置信息</param> /// <returns>MQ连接</returns> public IConnection Connection(MqConfig config) { var key = config.UserId + config.Password + config.Port + config.ServerIp; if (!_mqConnectionFactoryDic.ContainsKey(key)) { _mqConnectionFactoryDic[key] = new ConnectionFactory { UserName = config.UserId, Password = config.Password, HostName = config.ServerIp, Port = config.Port, VirtualHost = "/", AutomaticRecoveryEnabled = true, TopologyRecoveryEnabled = true, RequestedChannelMax = 10, UseBackgroundThreadsForIO = false }; } return(_mqConnectionFactoryDic[key].CreateConnection()); }
static void Test() { var config = new MqConfig() { HostIp = "127.0.0.1", Port = 5672, UserName = "******", Password = "******" }; var manager = new MqServcieManager(); manager.AddService(new DemoMqService(config)); manager.OnAction = OnActionOutput; manager.Start(); Console.WriteLine("服务已启动"); Console.ReadLine(); manager.Stop(); Console.WriteLine("服务已停止,按任意键退出..."); Console.ReadLine(); }
static void TestEventbus() { var config = new MqConfig { UserName = "******", Password = "******", HostIp = "localhost", Port = 5672, Exchange = "Eventbus", ExchangeType = "direct", VirtualHost = "/" }; var manager = new MessageHandlerManager(config); manager.Register <TestEvent>(new ActionEventHandler <TestEvent>(TestActionHandler)); manager.Register <TestEvent>(new TestEventHandler()); manager.Register <TestEvent>(new TestMessageHandler()); manager.Register <TestEvent>(new MessageHandlerTest()); Console.ReadLine(); manager.Unregister <TestEvent>(typeof(TestMessageHandler)); }
public IMqReceiver GetMqReceiver(MqConfig config) { return(new MqReceiver(config)); }
public MqReceiver(MqConfig config) { _config = config; IsReceiving = false; }
public RabbitMqService(MqConfig config) { Open(config); }
public IMqSender GetMqSender(MqConfig config) { return(new MqSender(config)); }
/// <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) { if (jwtOptins == null) { jwtOptins = new JwtIssuerOptions(); } services.AddJwt(out jwtOptins); // 添加jwt验证: services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, //是否验证Issuer ValidateAudience = true, //是否验证Audience ValidateLifetime = true, //是否验证失效时间 ClockSkew = TimeSpan.FromSeconds(30), ValidateIssuerSigningKey = true, //是否验证SecurityKey ValidAudience = Const.Domain, //Audience ValidIssuer = Const.Domain, //Issuer,这两项和前面签发jwt的设置一致 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey)) //拿到SecurityKey }; }); services.AddScoped <IEventBus, EventBus>(); var mqconfig = new MqConfig { UserName = "******", Password = "******", HostIp = "localhost", Port = 5672, VirtualHost = "/", Exchange = "Abs.Exchange", ExchangeType = "direct", Durable = true, AutoDelete = false }; var ehm = new MessageHandlerManager(mqconfig); services.AddSingleton <IEventHandlerManager>(ehm); services.AddScoped <IJwtService, JwtService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title = "AspNetCore WebApi", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); options.IncludeXmlComments(@"bin\Debug\netcoreapp2.2\AspNetCoreTest.xml"); options.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Type = "apiKey", Name = "Authorization", Description = "请输入API访问 Token,前面加上Bearer。例如:Bearer {token}" }); options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", Enumerable.Empty <string>() } }); }); }
private static void MqInProcessPerformanceTests(int runs, int loops, MqMessage message, MqConfig config) { var server = new MqServer <SimpleMqSession, MqConfig>(config); server.Start(); double[] totalValues = { 0, 0, 0 }; var count = 0; var sw = new Stopwatch(); var wait = new AutoResetEvent(false); var completeTest = new AutoResetEvent(false); var client = new MqClient <SimpleMqSession, MqConfig>(config); Console.WriteLine("| Build | Messages | Msg Bytes | Milliseconds | Msg/sec | MBps |"); Console.WriteLine("|---------|------------|-----------|--------------|------------|----------|"); var messageSize = message.Size; server.IncomingMessage += (sender, args2) => { count += args2.Messages.Count; if (count == runs) { sw.Stop(); var mode = "Release"; #if DEBUG mode = "Debug"; #endif var messagesPerSecond = (int)((double)runs / sw.ElapsedMilliseconds * 1000); var msgSizeNoHeader = messageSize - 12; var mbps = runs * (double)(msgSizeNoHeader) / sw.ElapsedMilliseconds / 1000; Console.WriteLine("| {0,7} | {1,10:N0} | {2,9:N0} | {3,12:N0} | {4,10:N0} | {5,8:N2} |", mode, runs, msgSizeNoHeader, sw.ElapsedMilliseconds, messagesPerSecond, mbps); totalValues[0] += sw.ElapsedMilliseconds; totalValues[1] += messagesPerSecond; totalValues[2] += mbps; wait.Set(); } }; var send = new Action(() => { count = 0; sw.Restart(); for (var i = 0; i < runs; i++) { client.Send(message); } //MqServer sv = server; wait.WaitOne(); wait.Reset(); }); client.Connected += (sender, args) => { for (var i = 0; i < loops; i++) { send(); } Console.WriteLine("| | | AVERAGES | {0,12:N0} | {1,10:N0} | {2,8:N2} |", totalValues[0] / loops, totalValues[1] / loops, totalValues[2] / loops); Console.WriteLine(); server.Stop(); client.Close(); completeTest.Set(); }; client.Connect(); completeTest.WaitOne(); }
public MqSender(MqConfig config) { _config = config; }