Basket microservice(购物车微服务)主要用于处理购物车的业务逻辑,包括:redis
如上图所示,本微服务采用数据驱动的CRUD微服务架构,来执行购物车商品的维护操做。并使用Redis数据库进行持久化。
这种类型的服务在单个 ASP.NET Core Web API 项目中便可实现全部功能,该项目包括数据模型类、业务逻辑类及其数据访问类。其项目结构以下:
数据库
核心技术选型:json
Newtonsoft.Jsonapi
该微服务的核心领域实体是购物车,其类图以下:安全
其中CustomerBasket
与BasketItem
为一对多关系,使用仓储模式进行持久化。架构
CustomerBasket
对象进行json格式的序列化和反序列化来完成在redis中的持久化和读取。ConnectionMultiplexer
,该对象最终经过构造函数注入到RedisBasketRepository
中。services.AddSingleton<ConnectionMultiplexer>(sp => { var settings = sp.GetRequiredService<IOptions<BasketSettings>>().Value; var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true); configuration.ResolveDns = true; return ConnectionMultiplexer.Connect(configuration); });
在本服务中主要须要处理如下事件的发布和消费:app
private void ConfigureEventBus(IApplicationBuilder app) { var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>(); eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>(); eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>(); }
以上都是基于事件总线来达成。async
购物车管理界面是须要认证和受权。那天然须要与上游的Identity Microservice
进行衔接。在启动类进行认证中间件的配置。ide
private void ConfigureAuthService(IServiceCollection services) { // prevent from mapping "sub" claim to nameidentifier. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); var identityUrl = Configuration.GetValue<string>("IdentityUrl"); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Authority = identityUrl; options.RequireHttpsMetadata = false; options.Audience = "basket"; }); } protected virtual void ConfigureAuth(IApplicationBuilder app) { if (Configuration.GetValue<bool>("UseLoadTest")) { app.UseMiddleware<ByPassAuthMiddleware>(); } app.UseAuthentication(); }
在该微服务中,定义了一个中断中间件:FailingMiddleware
,经过访问http://localhost:5103/failing
获取该中间件的启用状态,经过请求参数指定:即经过http://localhost:5103/failing?enable
和http://localhost:5103/failing?disable
来手动中断和恢复服务,来模拟断路,以便用于测试断路器模式。
开启断路后,当访问购物车页面时,Polly在重试指定次数依然没法访问服务时,就会抛出BrokenCircuitException
异常,经过捕捉该异常告知用户稍后再试。函数
public class CartController : Controller { //… public async Task<IActionResult> Index() { try { var user = _appUserParser.Parse(HttpContext.User); //Http requests using the Typed Client (Service Agent) var vm = await _basketSvc.GetBasket(user); return View(vm); } catch (BrokenCircuitException) { // Catches error when Basket.api is in circuit-opened mode HandleBrokenCircuitException(); } return View(); } private void HandleBrokenCircuitException() { TempData["BasketInoperativeMsg"] = "Basket Service is inoperative, please try later on. (Business message due to Circuit-Breaker)"; } }
在配置MVC服务时指定了两个过滤器:全局异常过滤器和模型验证过滤器。
// Add framework services. services.AddMvc(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); options.Filters.Add(typeof(ValidateModelStateFilter)); }).AddControllersAsServices();
BasketDomainException
异常和HttpGlobalExceptionFilter
过滤器来实现的。ActionFilterAttribute
特性实现的ValidateModelStateFilter
来获取模型状态中的错误。public class ValidateModelStateFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (context.ModelState.IsValid) { return; } var validationErrors = context.ModelState .Keys .SelectMany(k => context.ModelState[k].Errors) .Select(e => e.ErrorMessage) .ToArray(); var json = new JsonErrorResponse { Messages = validationErrors }; context.Result = new BadRequestObjectResult(json); } }
由于默认启用了安全认证,因此为了方便在SwaggerUI界面进行测试,那么咱们就必须为其集成认证受权。代码以下:
services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new Info { Title = "Basket HTTP API", Version = "v1", Description = "The Basket Service HTTP API", TermsOfService = "Terms Of Service" }); options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize", TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token", Scopes = new Dictionary<string, string>() { { "basket", "Basket API" } } }); options.OperationFilter<AuthorizeCheckOperationFilter>(); });
其中有主要作了三件事:
AuthorizeCheckOperationFilter
用于拦截须要受权的请求public class AuthorizeCheckOperationFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { // Check for authorize attribute var hasAuthorize = context.ApiDescription.ControllerAttributes().OfType<AuthorizeAttribute>().Any() || context.ApiDescription.ActionAttributes().OfType<AuthorizeAttribute>().Any(); if (hasAuthorize) { operation.Responses.Add("401", new Response { Description = "Unauthorized" }); operation.Responses.Add("403", new Response { Description = "Forbidden" }); operation.Security = new List<IDictionary<string, IEnumerable<string>>>(); operation.Security.Add(new Dictionary<string, IEnumerable<string>> { { "oauth2", new [] { "basketapi" } } }); } } }
本服务较以前讲的Catalog microservice 而言,主要是多了一个认证和redis存储。