Azure Service Bus(三)在 .NET Core Web 应用程序发送ServiceBus Queue
一,引言
在之前上一篇讲解到 Azure ServiceBus Queue 中,我们实地的演示了在控制台中如何操作ServiceBus Queue ,使用 Azure.Messgae.Service 的依赖包完成 Message 的接收/发送,今天我们继续探究 ServiceBus Queue,如何利用 Microsoft.Azure.ServiceBus 以来完成消息的发送。
--------------------我是分割线--------------------
Azure ServiceBus 系列:
1,Azure Service Bus(一)入门简介
2,Azure Service Bus(二)在NET Core 控制台中如何操作 ServiceBus Queue
3,Azure Service Bus(三)在 .NET Core Web 应用程序发送ServiceBus Queue
二,正文
1,创建ServiceBus Queue
Azure Portal 点击 “create a resource”,输入 “Service Bus” 搜索,并且进行创建。
Resource group 选择:“Web_Test_SB_RG”
Namespace name:“cnbateblogweb”
Loaction:“East Asia”
Pricing tier:“Basic”
点击 “Review + create” 进行创建预校验。
校验完成后,点击 “Create” 进行创建
创建完成后,点击 “Go to resource” 跳转到创建好的资源
最后,选择 “Entities=》Queue”,点击 “+ Queue” 添加 ServiceBus Queue
创建 ServiceBus Queue 输入
Name:“cnbateblogweb_queue”
其他参数选择默认,点击 “Create” 进行创建
创建完成后,我们可以在列表中查看到刚刚创建的名字叫 “cnbateblogweb_queue” 的 Queue 的信息了
2,.NET Core Web MVC 添加对 ServiceBus Queue 的消息的发送
2.1,创建Web项目,添加对 "ServiceBus Queue“ 的依赖包
接下来就是创建 Web 项目,点击 “ASP.NET Core Web 应用程序”,并命名为 “Azure.ServiceBus.Web”,我这里选择的目标框架为 “.NET 5.0”
项目创建完成之后,需要添加 Azure ServiceBus 的引用 “Microsoft.Azure.ServiceBus”
使用程序包管理控制台进行安装
1
|
Install-Package Microsoft.Azure.ServiceBus -Version 5.1.0 |
2.2,创建 ServiceBusQueueSerivice
我们需要创建 ServiceBusQueueSerivice 负责创建与ServiceBus 连接并且发送信息
IServiceBusQueueService
public interface IServiceBusQueueService { Task SendMessageAsync(Message msg); }
ServiceBusQueueService
public class ServiceBusQueueService : IServiceBusQueueService { private readonly AzureServiceBus.IQueueClient _queueClient; public ServiceBusQueueService(AzureServiceBus.QueueClient queueClient) { _queueClient = queueClient; } public async Task SendMessageAsync(Message msg) { try { // Serialize data model and create message. string messageBody = JsonSerializer.Serialize(msg); // create a message that we can send. UTF-8 encoding is used when providing a string. var message = new AzureServiceBus.Message(Encoding.UTF8.GetBytes(messageBody)); /// send the message await _queueClient.SendAsync(message); } catch (Exception ex) { } } }
2.3,创建 ServiceBusQueueController
通过页面文本输入的表单需要提交内容,再将需要发送的Message 发送到 ServiceBus 中
ServiceBusQueueController
public class ServiceBusQueueController : Controller { private IServiceBusQueueService _serviceBusQueueService; public ServiceBusQueueController(IServiceBusQueueService serviceBusQueueService) { _serviceBusQueueService = serviceBusQueueService; } public IActionResult Index(string msg) { ViewBag.Message = string.Empty; if (!string.IsNullOrEmpty(msg)) ViewBag.Message = msg; return View(); } [Route("ServiceBusQueue/Send")] [HttpPost()] public async Task<IActionResult> SendMessage(IFormCollection collection) { var msg = new Message { Id=1, Title = collection["Title"], Content = collection["Content"], CreateTime=DateTime.Now }; await _serviceBusQueueService.SendMessageAsync(msg); return RedirectToAction("Index", "ServiceBusQueue",new {msg= " Success!" }); } }
用户在页面上提交需要发送的 Message 的内容
@model Azure.ServiceBus.Web.Models.Message @{ ViewData["Title"] = "ServiceBusQueue Page"; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewData["Title"]</title> </head> <body> <h4>ServiceBusQueue Add Message:<span class="text-success">@ViewBag.Message</span></h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Send"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Title" class="control-label"></label> <input asp-for="Title" class="form-control" /> <span asp-validation-for="Title" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Content" class="control-label"></label> <input asp-for="Content" class="form-control" /> <span asp-validation-for="Content" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Send" class="btn btn-primary" /> </div> </form> </div> </div> </body> </html>
2.4,依赖注入 Service,Appsettings 配置等
Startup.cs 的ConfigureService 方法
services.AddSingleton(new Appsettings(Env.ContentRootPath)); services.AddSingleton<AzureServiceBus.QueueClient>(new AzureServiceBus.QueueClient(Appsettings.app("ServiceBus", "PrimaryConnectionString"), Appsettings.app("ServiceBus", "QueueName"))); services.AddSingleton<IServiceBusQueueService, ServiceBusQueueService>();
Appsettings.cs
/// <summary> /// appsettings.json操作类 /// </summary> public class Appsettings { static IConfiguration Configuration { get; set; } static string contentPath { get; set; } public Appsettings(string contentPath) { string Path = "appsettings.json"; //如果你把配置文件 是 根据环境变量来分开了,可以这样写 //string Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json"; //var contentPath = env.ContentRootPath; Configuration = new ConfigurationBuilder() .SetBasePath(contentPath) .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性 .Build(); } /// <summary> /// 封装要操作的字符 /// </summary> /// <param name="sections"></param> /// <returns></returns> public static string app(params string[] sections) { try { var val = string.Empty; for (int i = 0; i < sections.Length; i++) { val += sections[i] + ":"; } return Configuration[val.TrimEnd(':')]; } catch (Exception) { return ""; } } }
appsettings.json
"ServiceBus": { "PrimaryConnectionString": "Endpoint=sb://cnbateblogweb.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=X3O9dsC0c+mir8A7porSEn9S/LoQX9GB0TNCv0W6Ev0=", "QueueName": "CNBATEBLOGWEB_QUEUE" }
最重要的一步不要忘记了,回到Azure Portal 上,复制ServiceBus Queue 的 “Shared access policies”
完整代码请查看文章底部 github 地址