/// <summary> /// 获取连接请求处理 委托 /// </summary> /// <param name="heartbeatService"></param> /// <returns></returns> private Func <TcpClient, CancellationToken, Task> GetRequestConnectionEventHandle(HeartbeatService heartbeatService, ForwardRuleDetail forwardRuleDetail) { return(async(tcp, serviceToken) => { var remoteEndPoint = tcp.Client.RemoteEndPoint; Action EndNotice = null; try { _logger.LogInformation("接收到访问请求:ClientId, {0}:{1}, 访问者:{2}", forwardRuleDetail.ClientId, forwardRuleDetail.RuleId, remoteEndPoint); var(serverTcp, EndNotice2) = await heartbeatService.GetRequestTcpClient(serviceToken, forwardRuleDetail); EndNotice = EndNotice2; if (serverTcp == null) { _logger.LogInformation("连接请求失败: 未获得服务端tcp连接"); return; } using (var forwarder = new Forwarder(tcp, serverTcp)) { await forwarder.Start(); } } catch (IOException ex) { _logger.LogInformation("数据转发连接断开:ClientId, {0}:{1}, 访问者:{2}, {3}", forwardRuleDetail.ClientId, forwardRuleDetail.RuleId, remoteEndPoint, ex.Message); } catch (Exception ex) { _logger.LogError(ex, "数据转发出现异常:ClientId, {0}:{1}, 访问者:{2}", forwardRuleDetail.ClientId, forwardRuleDetail.RuleId, remoteEndPoint); } EndNotice?.Invoke(); }); }
public async Task when_a_forwarder_is_started_messages_are_forwarded_via_the_endpoint() { await CreateSubscriptionEntitiesIfRequired(namespaceConnectionString, TopicName, destinationQueue); forwarder.Start(); var topicClient = TopicClient.CreateFromConnectionString(namespaceConnectionString, TopicName); var eventMessage = await MessageFactory.CreateMessageWithJsonBody(); var tcs = new TaskCompletionSource<string>(); await topicClient.SendAsync(eventMessage); A.CallTo(messageForwarder).Invokes(() => tcs.SetResult("kfd")); if (!tcs.Task.Wait(TimeSpan.FromSeconds(10))) { Assert.Fail("Timed out waiting for message to be forwarded"); } }
public void forwarder_for_pub() { const string pubEndpoint = "tcp://127.0.0.1:90012"; const string XpubEndpoint = "tcp://127.0.0.1:80010"; // set up a pub sub using (var pubSocket = base.Context.CreateSocket(SocketType.Pub)) using (var subSocket = base.Context.CreateSocket(SocketType.Sub)) { pubSocket.Bind(pubEndpoint); // this is an indirection between the original pub/sub using xsub/xpub using (var fwd = new Forwarder(base.Context, pubEndpoint, XpubEndpoint)) { fwd.Start(); // connects to xpub subSocket.Connect(XpubEndpoint); subSocket.Subscribe("topic"); Thread.Sleep(1000); pubSocket.Send("topic", null, hasMoreToSend: true); pubSocket.Send("data"); Thread.Sleep(1000); var topic = subSocket.RecvString(); Assert.AreEqual("topic", topic); var data = subSocket.RecvString(); Assert.AreEqual("data", data); } } }
private static async Task MainAsync() { var instrumentationKey = Environment.GetEnvironmentVariable("Payments.InstrumentationKey", EnvironmentVariableTarget.Process); var license = Environment.GetEnvironmentVariable("NServiceBus.License", EnvironmentVariableTarget.Process); var ordersConnectionString = Environment.GetEnvironmentVariable("Orders.ConnectionString", EnvironmentVariableTarget.Process); var paymentsConnectionString = Environment.GetEnvironmentVariable("Payments.ConnectionString", EnvironmentVariableTarget.Process); System.Net.ServicePointManager.DefaultConnectionLimit = Int32.MaxValue; TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey; var telemetryClient = new TelemetryClient(); var defaultFactory = LogManager.Use <DefaultFactory>(); defaultFactory.Level(LogLevel.Info); var endpointConfig = new EndpointConfiguration("Payments"); if (!string.IsNullOrEmpty(license)) { endpointConfig.License(license); } endpointConfig.UsePersistence <InMemoryPersistence>(); endpointConfig.SendFailedMessagesTo("error"); var transport = endpointConfig.UseTransport <AzureServiceBusTransport>(); transport.ConnectionString(paymentsConnectionString); var topology = transport.UseForwardingTopology(); var factories = transport.MessagingFactories(); var receivers = transport.MessageReceivers(); var perReceiverConcurrency = 10; var numberOfReceivers = 2; // Premium messaging has 2 partitions var globalConcurrency = numberOfReceivers * perReceiverConcurrency; endpointConfig.LimitMessageProcessingConcurrencyTo(globalConcurrency); factories.NumberOfMessagingFactoriesPerNamespace(numberOfReceivers * 2); //Bus receiver, bus sender transport.NumberOfClientsPerEntity(numberOfReceivers); factories.BatchFlushInterval(TimeSpan.FromMilliseconds(100)); receivers.PrefetchCount(1000); // The more we prefetch, the better the throughput will be, needs to be balanced though as you can only pull so many messages per batch topology.NumberOfEntitiesInBundle(1); // Only use 1 bundle topic, there is no benefit to using more and Particular are going to remove this support moving forward transport.Transactions(TransportTransactionMode.ReceiveOnly); // Use peek lock, vastly quicker than transport.BrokeredMessageBodyType(SupportedBrokeredMessageBodyTypes.Stream); // Need to use this for non-NSB integrations - will be what Particular use moving forward too transport.TransportType(TransportType.Amqp); // Use this rather than netmessaging, allows more connections to the namespace and is an open standard // See here for a better example of this that handles ungraceful shutdowns - https://github.com/Particular/docs.particular.net/blob/master/samples/application-insights/Metrics_1/Endpoint/ApplicationInsightsFeature.cs var metricOptions = endpointConfig.EnableMetrics(); metricOptions.RegisterObservers(context => { foreach (var duration in context.Durations) { duration.Register(observer: durationLength => telemetryClient.TrackMetric(new MetricTelemetry(duration.Name, durationLength.TotalMilliseconds))); } foreach (var signal in context.Signals) { signal.Register(observer: () => telemetryClient.TrackEvent(new EventTelemetry(signal.Name))); } }); var endpoint = await Endpoint.Start(endpointConfig).ConfigureAwait(false); var forwarderConfig = new ForwarderConfiguration( new ForwarderSourceConfiguration(500, () => CreateMessageReceiver(ordersConnectionString, "Payments")), new ForwarderDestinationConfiguration("Payments", () => CreateMessageForwarder(paymentsConnectionString, "Payments"))) .UsingLogger(new Logger(LogManager.GetLogger <Forwarder>())) .WithConcurrencyOf(3); var forwarder = new Forwarder(forwarderConfig); await CreateSubscriptionEntitiesIfRequired(ordersConnectionString, "Returns", "Payments"); forwarder.Start(); }