예제 #1
0
        public void Start(PushRuntimeSettings limitations)
        {
            maxConcurrency = limitations.MaxConcurrency;

            var prefetchCount = maxConcurrency * prefetchMultiplier;

            if (overriddenPrefetchCount.HasValue)
            {
                prefetchCount = overriddenPrefetchCount.Value;
            }

            var receiveMode = pushSettings.RequiredTransactionMode == TransportTransactionMode.None ? ReceiveMode.ReceiveAndDelete : ReceiveMode.PeekLock;

            if (tokenProvider == null)
            {
                receiver = new MessageReceiver(connectionStringBuilder.GetNamespaceConnectionString(), pushSettings.InputQueue, receiveMode, retryPolicy: retryPolicy, prefetchCount);
            }
            else
            {
                receiver = new MessageReceiver(connectionStringBuilder.Endpoint, pushSettings.InputQueue, tokenProvider, connectionStringBuilder.TransportType, receiveMode, retryPolicy: retryPolicy, prefetchCount);
            }

            semaphore = new SemaphoreSlim(maxConcurrency, maxConcurrency);

            messageProcessing = new CancellationTokenSource();

            receiveLoopTask = Task.Run(() => ReceiveLoop());
        }
예제 #2
0
 public MessageReceiver(
     ServiceBusConnectionStringBuilder connectionStringBuilder,
     ReceiveMode receiveMode = ReceiveMode.PeekLock,
     RetryPolicy retryPolicy = null,
     int prefetchCount       = DefaultPrefetchCount)
     : this(connectionStringBuilder?.GetNamespaceConnectionString(), connectionStringBuilder.EntityPath, receiveMode, retryPolicy, prefetchCount)
 {
 }
        private static async Task ConfigureSubscriptionAsync(ServiceBusConnectionStringBuilder builder, string subscriptionName)
        {
            var subscriptionDescription = new SubscriptionDescription(builder.EntityPath, subscriptionName);

            var client = new ManagementClient(builder.GetNamespaceConnectionString());

            if (!await client.SubscriptionExistsAsync(builder.EntityPath, subscriptionName).ConfigureAwait(false))
            {
                await client.CreateSubscriptionAsync(subscriptionDescription).ConfigureAwait(false);
            }
        }
예제 #4
0
        private static string GetConnectionString()
        {
            ServiceBusConnectionStringBuilder sb = new ServiceBusConnectionStringBuilder();

            sb.Endpoint   = BaseAddress;
            sb.SasKey     = AccessKey;
            sb.EntityPath = "tranfers";
            sb.SasKeyName = KeyName;
            var connectionString = sb.GetNamespaceConnectionString();

            return(connectionString);
        }
예제 #5
0
        public DefaultServiceBusPersisterConnection(ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder,
                                                    ILogger <DefaultServiceBusPersisterConnection> logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _serviceBusConnectionStringBuilder = serviceBusConnectionStringBuilder ??
                                                 throw new ArgumentNullException(nameof(serviceBusConnectionStringBuilder));

            var test = _serviceBusConnectionStringBuilder.GetNamespaceConnectionString();

            _topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default);
        }
        private static MessageReceiver CreateReceiver(ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder, string entityName, string subscriptionName)
        {
            var entityPath = entityName;

            if (string.IsNullOrWhiteSpace(subscriptionName) == false)
            {
                entityPath = $"{entityPath}/subscriptions/{subscriptionName}";
            }

            var connectionString = serviceBusConnectionStringBuilder.GetNamespaceConnectionString();

            return(new MessageReceiver(connectionString, entityPath));
        }
        public static IServiceCollection AddCustomHealthChecks(this IServiceCollection services, IConfiguration configuration)
        {
            var hcBuilder = services.AddHealthChecks();

            hcBuilder.AddCheck("liveness", () => HealthCheckResult.Healthy());

            var serviceBusConnectionString = configuration["EventBus:ConnectionString"];
            var serviceBusConnection       = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);

            hcBuilder.AddSqlServer(configuration["Database:ConnectionString"], name: "web-app-on-containers-db-sb-check", tags: new[] { "web-app-on-containers-db-sb" });
            hcBuilder.AddAzureServiceBusTopic(serviceBusConnection.GetNamespaceConnectionString(), serviceBusConnection.EntityPath, "service-bus-check", tags: new[] { "service-bus" });

            return(services);
        }
예제 #8
0
        private static async Task QueueOrders(int requestedAmount)
        {
            var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(ConnectionString);

            var queueClient = new QueueClient(serviceBusConnectionStringBuilder.GetNamespaceConnectionString(), serviceBusConnectionStringBuilder.EntityPath, ReceiveMode.PeekLock);

            for (int currentOrderAmount = 0; currentOrderAmount < requestedAmount; currentOrderAmount++)
            {
                var order        = GenerateOrder();
                var rawOrder     = JsonConvert.SerializeObject(order);
                var orderMessage = new Message(Encoding.UTF8.GetBytes(rawOrder));

                Console.WriteLine($"Queuing order {order.Id} - A {order.ArticleNumber} for {order.Customer.FirstName} {order.Customer.LastName}");
                await queueClient.SendAsync(orderMessage);
            }
        }
예제 #9
0
        public void Start(PushRuntimeSettings limitations)
        {
            maxConcurrency = limitations.MaxConcurrency;

            var prefetchCount = overriddenPrefetchCount;

            if (prefetchCount == 0)
            {
                prefetchCount = maxConcurrency * prefetchMultiplier;
            }

            var receiveMode = pushSettings.RequiredTransactionMode == TransportTransactionMode.None ? ReceiveMode.ReceiveAndDelete : ReceiveMode.PeekLock;

            if (tokenProvider == null)
            {
                receiver = new MessageReceiver(connectionStringBuilder.GetNamespaceConnectionString(), pushSettings.InputQueue, receiveMode, retryPolicy: default, prefetchCount);
        private static async Task ConfigureQueueAsync(ServiceBusConnectionStringBuilder builder, bool canCreateQueue)
        {
            if (canCreateQueue)
            {
                var queueDescription = new QueueDescription(builder.EntityPath)
                {
                    EnableBatchedOperations = true,
                    EnablePartitioning      = true
                };

                var client = new ManagementClient(builder.GetNamespaceConnectionString());
                if (!await client.QueueExistsAsync(builder.EntityPath).ConfigureAwait(false))
                {
                    await client.CreateQueueAsync(queueDescription).ConfigureAwait(false);
                }
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddRazorPages();
            services.AddSignalR();

            services.AddOptions();
            var orderQueueSection = Configuration.GetSection("OrderQueue");

            services.Configure <OrderQueueSettings>(orderQueueSection);

            services.AddSwagger();
            services.AddScoped <QueueClient>(serviceProvider =>
            {
                var connectionString = Configuration.GetValue <string>("KEDA_SERVICEBUS_QUEUE_CONNECTIONSTRING");
                var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString);
                return(new QueueClient(serviceBusConnectionStringBuilder.GetNamespaceConnectionString(), serviceBusConnectionStringBuilder.EntityPath));
            });
        }
예제 #12
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var ordersQueue = Configuration.GetValue <string>("SERVICEBUS_QUEUE_ORDERS");
            var queueClient = new QueueClient(_serviceBusConnectionStringBuilder.GetNamespaceConnectionString(), ordersQueue, ReceiveMode.PeekLock);

            Logger.LogInformation("Starting message pump");
            queueClient.RegisterMessageHandler(HandleMessage, HandleReceivedException);
            Logger.LogInformation("Message pump started");

            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
            }

            Logger.LogInformation("Closing message pump");
            await queueClient.CloseAsync();

            Logger.LogInformation("Message pump closed : {Time}", DateTimeOffset.UtcNow);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            var openApiInformation = new OpenApiInfo
            {
                Title   = "KEDA API",
                Version = "v1"
            };

            services.AddScoped <QueueClient>(serviceProvider =>
            {
                var configuration    = serviceProvider.GetRequiredService <IConfiguration>();
                var connectionString = configuration["KEDA_SERVICEBUS_QUEUE_CONNECTIONSTRING"];
                var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString);
                return(new QueueClient(serviceBusConnectionStringBuilder.GetNamespaceConnectionString(), serviceBusConnectionStringBuilder.EntityPath, ReceiveMode.PeekLock));
            });

            services.AddSwaggerGen(swaggerGenerationOptions =>
            {
                swaggerGenerationOptions.SwaggerDoc("v1", openApiInformation);
                swaggerGenerationOptions.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "Keda.Samples.Dotnet.API.Open-Api.xml"));
            });
        }
예제 #14
0
        public ShipmentRepository(ServiceBusConnectionStringBuilder connectionStringBuilder, IConfiguration configuration)
        {
            var shipmentsQueue = configuration.GetValue <string>("SERVICEBUS_QUEUE_SHIPMENTS");

            _queueClient = new QueueClient(connectionStringBuilder.GetNamespaceConnectionString(), shipmentsQueue, ReceiveMode.PeekLock);
        }
예제 #15
0
        static async Task MainAsync(string[] args)
        {
            // The connection string for the RootManageSharedAccessKey can be accessed from the Azure portal
            // by selecting the SB namespace and clicking on "Connection Information"
            Console.Write("Enter your connection string for the RootManageSharedAccessKey for your Service Bus namespace: ");
            nsConnectionString = Console.ReadLine();

            var cxn = new ServiceBusConnectionStringBuilder(nsConnectionString);
            ///////////////////////////////////////////////////////////////////////////////////////
            // Create a topic with a SAS Listen rule and an associated subscription
            ///////////////////////////////////////////////////////////////////////////////////////
            ManagementClient nm = new ManagementClient(cxn);

            contosoTListenRule = new SharedAccessAuthorizationRule("contosoTListenKey",
                                                                   new[] { AccessRights.Listen });

            TopicDescription td = new TopicDescription(topicPath);

            td.AuthorizationRules.Add(contosoTListenRule);
            if ((await nm.TopicExistsAsync(topicPath)))
            {
                await nm.DeleteTopicAsync(topicPath);
            }
            await nm.CreateTopicAsync(td);

            await nm.CreateSubscriptionAsync(topicPath, subscriptionName);

            ///////////////////////////////////////////////////////////////////////////////////////
            // Send a message to the topic
            // Note that this uses the connection string for RootManageSharedAccessKey
            // configured on the namespace root
            ///////////////////////////////////////////////////////////////////////////////////////

            TopicClient tc          = new TopicClient(cxn.GetNamespaceConnectionString(), topicPath, RetryPolicy.Default);
            Message     sentMessage = CreateHelloMessage();
            await tc.SendAsync(sentMessage);

            Console.WriteLine("Sent Hello message to topic: ID={0}, Body={1}.", sentMessage.MessageId, Encoding.UTF8.GetString(sentMessage.Body));

            ///////////////////////////////////////////////////////////////////////////////////////
            // Generate a SAS token scoped to a subscription using the SAS rule with
            // a Listen right configured on the Topic & TTL of 1 day
            ///////////////////////////////////////////////////////////////////////////////////////
            ServiceBusConnectionStringBuilder csBuilder = new ServiceBusConnectionStringBuilder(nsConnectionString);
            string subscriptionUri = new Uri(new Uri(csBuilder.Endpoint), topicPath + "/subscriptions/" + subscriptionName).ToString();

            // This is how you acquire a token in an STS to pass it out to a client.
            var tp = TokenProvider.CreateSharedAccessSignatureTokenProvider(contosoTListenRule.KeyName, contosoTListenRule.PrimaryKey);
            var subscriptionToken = await tp.GetTokenAsync(subscriptionUri, TimeSpan.FromMinutes(180));

            Console.WriteLine($"Acquired token: {subscriptionToken.TokenValue}");

            ///////////////////////////////////////////////////////////////////////////////////////
            // Use the SAS token scoped to a subscription to receive the messages
            ///////////////////////////////////////////////////////////////////////////////////////

            var are = new AutoResetEvent(false);
            SubscriptionClient sc = new SubscriptionClient(csBuilder.Endpoint, topicPath, subscriptionName, TokenProvider.CreateSharedAccessSignatureTokenProvider(subscriptionToken.TokenValue));

            sc.RegisterMessageHandler(async(m, c) =>
            {
                Console.WriteLine("Received message from subscription: ID = {0}, Body = {1}.", m.MessageId, Encoding.UTF8.GetString(m.Body));
                await sc.CompleteAsync(m.SystemProperties.LockToken);
                are.Set();
            },
                                      new MessageHandlerOptions(async(e) =>
            {
                Console.WriteLine($"Exception: {e.Exception.ToString()}");
            })
            {
                AutoComplete = false
            });


            are.WaitOne();
            await sc.CloseAsync();

            ///////////////////////////////////////////////////////////////////////////////////////
            // Clean-up
            ///////////////////////////////////////////////////////////////////////////////////////
            await nm.DeleteTopicAsync(topicPath);
        }
예제 #16
0
 /// <summary>
 /// Creates a new AMQP MessageSender.
 /// </summary>
 /// <param name="connectionStringBuilder">The <see cref="ServiceBusConnectionStringBuilder"/> having entity level connection details.</param>
 /// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param>
 /// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks>
 public MessageSender(
     ServiceBusConnectionStringBuilder connectionStringBuilder,
     RetryPolicy retryPolicy = null)
     : this(connectionStringBuilder?.GetNamespaceConnectionString(), connectionStringBuilder?.EntityPath, retryPolicy)
 {
 }
        public static IHealthChecksBuilder AddCustomAzureServiceBusTopic(this IHealthChecksBuilder builder, IConfiguration configuration)
        {
            var connectionString = new ServiceBusConnectionStringBuilder(configuration.GetAzureServiceBusConnectionString());

            return(builder.AddAzureServiceBusTopic(connectionString.GetNamespaceConnectionString(), connectionString.EntityPath));
        }