eShopOnContainers 知多少[7]:Basket microservice

640?wx_fmt=png

引言

Basket microservice(购物车微服务)主要用于处理购物车的业务逻辑,包括:

  1. 购物车商品的CRUD

  2. 订阅商品价格更新事件,进行购物车商品同步处理

  3. 购物车结算事件发布

  4. 订阅订单成功创建事件,进行购物车的清空操作

架构模式

640?wx_fmt=png

如上图所示,本微服务采用数据驱动的CRUD微服务架构,并使用Redis数据库进行持久化。 这种类型的服务在单个 ASP.NET Core Web API 项目中即可实现所有功能,该项目包括数据模型类、业务逻辑类及其数据访问类。其项目结构如下:640?wx_fmt=png

核心技术选型:

  1. ASP.NET Core Web API

  2. Entity Framework Core

  3. Redis

  4. Swashbuckle(可选)

  5. Autofac

  6. Eventbus

  7. Newtonsoft.Json

实体建模和持久化

该微服务的核心领域实体是购物车,其类图如下:640?wx_fmt=png

其中 CustomerBasketBasketItem为一对多关系,使用仓储模式进行持久化。

  1. 通过对 CustomerBasket对象进行json格式的序列化和反序列化来完成在redis中的持久化和读取。

  2. 以单例模式注入redis连接 ConnectionMultiplexer,该对象最终通过构造函数注入到 RedisBasketRepository中。

  1. services.AddSingleton<ConnectionMultiplexer>(sp =>

  2. {

  3.    var settings = sp.GetRequiredService<IOptions<BasketSettings>>().Value;

  4.    var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);


  5.    configuration.ResolveDns = true;


  6.    return ConnectionMultiplexer.Connect(configuration);

  7. });

事件的注册和消费

在本服务中主要需要处理以下事件的发布和消费:

  1. 事件发布:当用户点击购物车结算时,发布用户结算事件。

  2. 事件消费:订单创建成功后,进行购物车的清空

  3. 事件消费:商品价格更新后,进行购物车相关商品的价格同步


  1. private void ConfigureEventBus(IApplicationBuilder app)

  2. {

  3.    var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();


  4.    eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>();

  5.    eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>();

  6. }

以上都是基于事件总线来达成。

认证和授权

购物车管理界面是需要认证和授权。那自然需要与上游的 IdentityMicroservice进行衔接。在启动类进行认证中间件的配置。

  1. private void ConfigureAuthService(IServiceCollection services)

  2. {

  3.    // prevent from mapping "sub" claim to nameidentifier.

  4.    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

  5.    var identityUrl = Configuration.GetValue<string>("IdentityUrl");


  6.    services.AddAuthentication(options =>

  7.    {

  8.        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

  9.        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

  10.    }).AddJwtBearer(options =>

  11.    {

  12.        options.Authority = identityUrl;

  13.        options.RequireHttpsMetadata = false;

  14.        options.Audience = "basket";

  15.    });

  16. }

  17. protected virtual void ConfigureAuth(IApplicationBuilder app)

  18. {

  19.    if (Configuration.GetValue<bool>("UseLoadTest"))

  20.    {

  21.        app.UseMiddleware<ByPassAuthMiddleware>();

  22.    }

  23.    app.UseAuthentication();

  24. }

手动启用断路器

在该微服务中,定义了一个中断中间件FailingMiddleware,通过访问 http://localhost:5103/failing获取该中间件的启用状态,通过请求参数指定:即通过 http://localhost:5103/failing?enablehttp://localhost:5103/failing?disable来手动中断和恢复服务,来模拟断路,以便用于测试断路器模式。 开启断路后,当访问购物车页面时,Polly在重试指定次数依然无法访问服务时,就会抛出 BrokenCircuitException异常,通过捕捉该异常告知用户稍后再试。

  1. public class CartController : Controller

  2. {

  3.    //…

  4.    public async Task<IActionResult> Index()

  5.    {

  6.        try

  7.        {          

  8.            var user = _appUserParser.Parse(HttpContext.User);

  9.            //Http requests using the Typed Client (Service Agent)

  10.            var vm = await _basketSvc.GetBasket(user);

  11.            return View(vm);

  12.        }

  13.        catch (BrokenCircuitException)

  14.        {

  15.            // Catches error when Basket.api is in circuit-opened mode                

  16.            HandleBrokenCircuitException();

  17.        }

  18.        return View();

  19.    }      

  20.    private void HandleBrokenCircuitException()

  21.    {

  22.        TempData["BasketInoperativeMsg"] = "Basket Service is inoperative, please try later on. (Business message due to Circuit-Breaker)";

  23.    }

  24. }

640?wx_fmt=png

注入过滤器

在配置MVC服务时指定了两个过滤器:全局异常过滤器和模型验证过滤器。

  1. // Add framework services.

  2. services.AddMvc(options =>

  3. {

  4.    options.Filters.Add(typeof(HttpGlobalExceptionFilter));

  5.    options.Filters.Add(typeof(ValidateModelStateFilter));


  6. }).AddControllersAsServices();


1. 全局异常过滤器是通过定义 BasketDomainException异常和 HttpGlobalExceptionFilter过滤器来实现的。

2. 模型验证过滤器是通过继承 ActionFilterAttribute特性实现的 ValidateModelStateFilter来获取模型状态中的错误。


  1. public class ValidateModelStateFilter : ActionFilterAttribute

  2. {

  3.    public override void OnActionExecuting(ActionExecutingContext context)

  4.    {

  5.        if (context.ModelState.IsValid)

  6.        {

  7.            return;

  8.        }


  9.        var validationErrors = context.ModelState

  10.            .Keys

  11.            .SelectMany(k => context.ModelState[k].Errors)

  12.            .Select(e => e.ErrorMessage)

  13.            .ToArray();


  14.        var json = new JsonErrorResponse

  15.        {

  16.            Messages = validationErrors

  17.        };


  18.        context.Result = new BadRequestObjectResult(json);

  19.    }

  20. }

SwaggerUI认证授权集成

因为默认启用了安全认证,所以为了方便在SwaggerUI界面进行测试,那么我们就必须为其集成认证授权。代码如下:

  1. services.AddSwaggerGen(options =>

  2. {

  3.    options.DescribeAllEnumsAsStrings();

  4.    options.SwaggerDoc("v1", new Info

  5.    {

  6.        Title = "Basket HTTP API",

  7.        Version = "v1",

  8.        Description = "The Basket Service HTTP API",

  9.        TermsOfService = "Terms Of Service"

  10.    });

  11.    options.AddSecurityDefinition("oauth2", new OAuth2Scheme

  12.    {

  13.        Type = "oauth2",

  14.        Flow = "implicit",

  15.        AuthorizationUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize",

  16.        TokenUrl = $"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token",

  17.        Scopes = new Dictionary<string, string>()

  18.        {

  19.            { "basket", "Basket API" }

  20.        }

  21.    });

  22.    options.OperationFilter<AuthorizeCheckOperationFilter>();

  23. });

其中有主要做了三件事:

1. 配置授权Url

2. 配置TokenUrl

3. 指定授权范围

4. 注入授权检查过滤器 AuthorizeCheckOperationFilter用于拦截需要授权的请求

  1. public class AuthorizeCheckOperationFilter : IOperationFilter

  2. {

  3.    public void Apply(Operation operation, OperationFilterContext context)

  4.    {

  5.        // Check for authorize attribute

  6.        var hasAuthorize = context.ApiDescription.ControllerAttributes().OfType<AuthorizeAttribute>().Any() ||

  7.                           context.ApiDescription.ActionAttributes().OfType<AuthorizeAttribute>().Any();

  8.        if (hasAuthorize)

  9.        {

  10.            operation.Responses.Add("401", new Response { Description = "Unauthorized" });

  11.            operation.Responses.Add("403", new Response { Description = "Forbidden" });

  12.            operation.Security = new List<IDictionary<string, IEnumerable<string>>>();

  13.            operation.Security.Add(new Dictionary<string, IEnumerable<string>>

  14.            {

  15.                { "oauth2", new [] { "basketapi" } }

  16.            });

  17.        }

  18.    }

  19. }

最后

本服务较之前讲的Catalog microservice 而言,主要是多了一个认证和redis存储。

640?wx_fmt=png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值