当前位置: 首页 > wzjs >正文

z怎么做优惠券网站什么是网站实施

z怎么做优惠券网站,什么是网站实施,北京网站设计费用,wordpress 网站播放器插件🧠 基于 ABP vNext CQRS MediatR 构建高可用与高性能微服务系统:从架构设计到落地实战 目录 🧠 基于 ABP vNext CQRS MediatR 构建高可用与高性能微服务系统:从架构设计到落地实战🧰 模块结构概览📦 各…

🧠 基于 ABP vNext + CQRS + MediatR 构建高可用与高性能微服务系统:从架构设计到落地实战


目录

  • 🧠 基于 ABP vNext + CQRS + MediatR 构建高可用与高性能微服务系统:从架构设计到落地实战
    • 🧰 模块结构概览
    • 📦 各模块注册代码示例
      • DomainModule
      • ApplicationModule
      • HttpApiModule
      • DbMigratorModule
    • 🧱 架构图 & 概念说明
    • ✍️ 核心代码实践
      • 1. 聚合根 & 仓储接口
      • 2. CacheKeys 常量
      • 3. 命令 + 验证器 + 幂等处理
      • 4. Pipeline 行为示意图
      • 5. ValidationBehavior + LoggingBehavior
      • 6. 查询缓存 + 布隆过滤器
      • 部署架构示意图
    • 🧪 自动化测试示例(Testcontainers)
      • 测试流程图
    • 📦 Docker Compose


🧰 模块结构概览

Abp.CqrsDemo
├── src
│   ├── Abp.CqrsDemo.Domain
│   ├── Abp.CqrsDemo.Application
│   ├── Abp.CqrsDemo.HttpApi
│   └── Abp.CqrsDemo.DbMigrator
└── tests└── Abp.CqrsDemo.Tests
  • Domain:实体、聚合根、领域事件、仓储接口
  • Application:命令、查询、MediatR 处理器、DTO、Pipeline Behaviors、CacheKeys
  • HttpApi:控制器、外部配置绑定
  • DbMigrator:数据库初始化与迁移工具

📦 各模块注册代码示例

DomainModule

[DependsOn(typeof(AbpDddDomainModule))]
public class CqrsDemoDomainModule : AbpModule
{
}

ApplicationModule

[DependsOn(typeof(CqrsDemoDomainModule))]
public class CqrsDemoApplicationModule : AbpModule
{public override void ConfigureServices(ServiceConfigurationContext context){// CQRS & Validationcontext.Services.AddMediatR(typeof(CqrsDemoApplicationModule).Assembly);context.Services.AddValidatorsFromAssembly(typeof(CqrsDemoApplicationModule).Assembly);// Pipeline Behaviorscontext.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));context.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));// 分布式缓存注册(Application 层即可依赖)context.Services.AddDistributedCache<OrderDto>();}
}

HttpApiModule

[DependsOn(typeof(CqrsDemoApplicationModule))]
public class CqrsDemoHttpApiModule : AbpModule
{public override void ConfigureServices(ServiceConfigurationContext context){var configuration = context.Services.GetConfiguration();// Redis 连接与缓存context.Services.AddStackExchangeRedisCache(options =>{options.Configuration = configuration["Redis:Connection"];});// 控制器托管context.Services.AddControllers();}
}

DbMigratorModule

[DependsOn(typeof(AbpEntityFrameworkCoreModule))]
public class CqrsDemoDbMigratorModule : AbpModule
{public override void ConfigureServices(ServiceConfigurationContext context){context.Services.AddAbpDbContext<CqrsDemoDbContext>(options =>{options.AddDefaultRepositories(includeAllEntities: true);});// 设置 EF Core 数据库提供者Configure<AbpDbContextOptions>(options =>{options.UseSqlServer(); // 或 UseNpgsql()});}
}

🧱 架构图 & 概念说明

Command/Query
API 控制器
MediatR Dispatcher
CommandHandler
QueryHandler
EFCore 写库
Redis 查询缓存
  • 命令 负责状态更改
  • 查询 可接入 Redis 或 读库
  • Pipeline:Validation → Logging → Handler

✍️ 核心代码实践

1. 聚合根 & 仓储接口

public class Order : AggregateRoot<Guid>
{public string ProductId { get; private set; }public int Quantity { get; private set; }protected Order() { } // EF Core 兼容public Order(Guid id, string productId, int quantity){Id = id;ProductId = productId;Quantity = quantity;}// 业务规则示例public void ChangeQuantity(int newQty){if (newQty <= 0) throw new BusinessException("Quantity must be positive");Quantity = newQty;}
}public interface IOrderRepository : IRepository<Order, Guid>
{
}

2. CacheKeys 常量

public static class CacheKeys
{public const string OrderById = "order:{0}";
}

3. 命令 + 验证器 + 幂等处理

public record CreateOrderCommand(Guid OrderId, string ProductId, int Quantity) : IRequest<Guid>;public class CreateOrderValidator : AbstractValidator<CreateOrderCommand>
{public CreateOrderValidator(){RuleFor(x => x.ProductId).NotEmpty();RuleFor(x => x.Quantity).GreaterThan(0);}
}public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, Guid>
{private readonly IOrderRepository _repo;private readonly IDistributedIdempotencyService _idempotency;public CreateOrderHandler(IOrderRepository repo, IDistributedIdempotencyService idempotency){_repo = repo;_idempotency = idempotency;}public async Task<Guid> Handle(CreateOrderCommand request, CancellationToken ct){return await _idempotency.ExecuteAsync(request.OrderId.ToString(), async () =>{var order = new Order(request.OrderId, request.ProductId, request.Quantity);await _repo.InsertAsync(order, cancellationToken: ct);return order.Id;});}
}

4. Pipeline 行为示意图

Client PipelineBehaviors Handler Send Request ValidationBehavior LoggingBehavior Handle Command/Query Return Response Client PipelineBehaviors Handler

5. ValidationBehavior + LoggingBehavior

public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>where TRequest : notnull
{private readonly IEnumerable<IValidator<TRequest>> _validators;public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators) => _validators = validators;public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct){var context = new ValidationContext<TRequest>(request);var results = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, ct)));var failures = results.SelectMany(r => r.Errors).Where(f => f != null).ToList();if (failures.Any()) throw new ValidationException(failures);return await next();}
}public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger) => _logger = logger;public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct){_logger.LogInformation("Handling {Request} with payload: {@Payload}", typeof(TRequest).Name, request);var sw = Stopwatch.StartNew();var response = await next();sw.Stop();_logger.LogInformation("Handled {Request} in {Elapsed}ms with response: {@Response}", typeof(TRequest).Name, sw.ElapsedMilliseconds, response);return response;}
}

6. 查询缓存 + 布隆过滤器

public class GetOrderByIdHandler : IRequestHandler<GetOrderByIdQuery, OrderDto>
{private readonly IOrderRepository _repo;private readonly IDistributedCache<OrderDto> _cache;private readonly IBloomFilter _bloomFilter;public GetOrderByIdHandler(IOrderRepository repo,IDistributedCache<OrderDto> cache,IBloomFilter bloomFilter){_repo = repo;_cache = cache;_bloomFilter = bloomFilter;}public async Task<OrderDto> Handle(GetOrderByIdQuery request, CancellationToken ct){if (!_bloomFilter.Contains(request.OrderId))throw new EntityNotFoundException(typeof(Order), request.OrderId);var cacheKey = string.Format(CacheKeys.OrderById, request.OrderId);return await _cache.GetOrAddAsync(cacheKey,async () =>{var order = await _repo.FindAsync(request.OrderId, ct);if (order == null) throw new EntityNotFoundException(typeof(Order), request.OrderId);return new OrderDto(order.Id, order.ProductId, order.Quantity);},options =>{options.SlidingExpiration = TimeSpan.FromMinutes(5);options.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);});}
}```markdown---## 🚀 部署与运行(Program.cs)```csharp
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;// 外部化配置
builder.Host.ConfigureAppConfiguration((ctx, cfg) =>
{cfg.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddEnvironmentVariables();
});// EF Core & DbContext
builder.Services.AddAbpDbContext<CqrsDemoDbContext>(options =>
{options.AddDefaultRepositories();
});
builder.Services.Configure<AbpDbContextOptions>(options =>options.UseSqlServer(config.GetConnectionString("Default")));// Redis 缓存 & 布隆过滤器
builder.Services.AddStackExchangeRedisCache(opts =>opts.Configuration = config["Redis:Connection"]);
builder.Services.AddSingleton<IBloomFilter>(_ =>new BloomFilter(expectedItemCount: 10000, falsePositiveRate: 0.01));// Health Checks
builder.Services.AddHealthChecks().AddDbContextCheck<CqrsDemoDbContext>("Database").AddRedis(config["Redis:Connection"], name: "Redis");// Polly HTTP 客户端
builder.Services.AddHttpClient("order").AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(Math.Pow(2, i)))).AddTransientHttpErrorPolicy(p => p.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));var app = builder.Build();
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
app.MapHealthChecks("/health/ready");app.MapControllers();
app.Run();

部署架构示意图

HTTP
Route
Read/Write
Cache
Client
Ingress/Nginx
API Pods
PostgreSQL
Redis

🧪 自动化测试示例(Testcontainers)

using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;public class CustomWebAppFactory : WebApplicationFactory<Program>, IAsyncLifetime
{private readonly PostgreSqlTestcontainer _postgres;public CustomWebAppFactory(){_postgres = new TestcontainersBuilder<PostgreSqlTestcontainer>().WithDatabase(new PostgreSqlTestcontainerConfiguration{Database = "demo",Username = "sa",Password = "sa"}).Build();}public async Task InitializeAsync() => await _postgres.StartAsync();public async Task DisposeAsync() => await _postgres.DisposeAsync();protected override void ConfigureWebHost(IWebHostBuilder builder){builder.ConfigureAppConfiguration((ctx, cfg) =>{cfg.AddInMemoryCollection(new Dictionary<string, string>{["ConnectionStrings:Default"] = _postgres.ConnectionString});});}
}public class OrderApiTests : IClassFixture<CustomWebAppFactory>
{private readonly HttpClient _client;public OrderApiTests(CustomWebAppFactory factory) => _client = factory.CreateClient();[Fact]public async Task Should_Create_Order_Successfully(){var command = new { orderId = Guid.NewGuid(), productId = "A001", quantity = 1 };var response = await _client.PostAsJsonAsync("/api/orders", command);response.EnsureSuccessStatusCode();}
}

测试流程图

Test 初始化
启动 Postgres 容器
配置 WebHost
运行集成测试
销毁容器

📦 Docker Compose

version: "3.9"
services:api:build: .ports:- "5000:80"db:image: postgresenvironment:POSTGRES_DB: demoPOSTGRES_USER: saPOSTGRES_PASSWORD: saredis:image: redis


文章转载自:

http://sfmZKUBh.rxcqt.cn
http://VFInXldp.rxcqt.cn
http://T4xyaCPO.rxcqt.cn
http://0Bb0ORXG.rxcqt.cn
http://TJK8DgjS.rxcqt.cn
http://dSVppKkC.rxcqt.cn
http://uYn7HMLU.rxcqt.cn
http://aNAedJdJ.rxcqt.cn
http://cOCo3jUQ.rxcqt.cn
http://oQCJu6yk.rxcqt.cn
http://M51ghYl0.rxcqt.cn
http://0fqcFvUf.rxcqt.cn
http://a4UOYvYQ.rxcqt.cn
http://eFIPIHOb.rxcqt.cn
http://NEBBmu5F.rxcqt.cn
http://xv5FLQJS.rxcqt.cn
http://gswfUnWt.rxcqt.cn
http://bCS3QjW7.rxcqt.cn
http://yUWwiZsJ.rxcqt.cn
http://6YknAsN7.rxcqt.cn
http://nW398KrB.rxcqt.cn
http://tBwsTwvG.rxcqt.cn
http://joeth9Ww.rxcqt.cn
http://7H2Qz370.rxcqt.cn
http://Sre9tH5t.rxcqt.cn
http://GSwqNk6p.rxcqt.cn
http://UGjgoTYz.rxcqt.cn
http://55baKh9s.rxcqt.cn
http://8TaWUVSx.rxcqt.cn
http://PczLWlix.rxcqt.cn
http://www.dtcms.com/wzjs/746390.html

相关文章:

  • 企业网站需要多大带宽重庆网站建设重庆零臻科技价
  • php在电子商务网站建设中的应用研究 戴书浩昆明城乡建设局网站
  • 用WordPress建什么站好鹤壁网站seo优化
  • 河南网站建站推广国外经典设计网站
  • 免费网站一级域名注册了解网站的建设心得
  • 网站seo的关键词排名怎么做的黑龙江省建设协会网站首页
  • 洛阳网站建设培训wordpress 运行时间
  • 固原地网站seowordpress打不开
  • 公司网站费用计入什么科目朝阳网络信息有限公司
  • 四川省查询建设人员注册证书网站免费平面设计软件有哪些
  • 烟台网站推广效果好手机网站公司哪家好
  • 建设银行签名通在网站哪里下载网站后台登陆口
  • 专做动漫的网站做企业官网哪家公司好
  • 织梦网站模板如何安装教程视频教程网站制作公司中企动力推荐
  • 成都网站设计制作价格谷歌优化是什么意思
  • 深圳网页制作与网站建设方案维护网站图怎么做才能小而清晰度
  • 做自己视频教程的网站企业建设营销网站的基本步骤
  • 怎么做网站弹窗通知256m内存 wordpress
  • 我谁知道在哪里可以找人帮忙做网站wix做中文网站怎么样
  • 建一个自己的网站需要多少钱深圳创纪录暴雨19小时
  • 一级a做爰片不卡免费网站查看网站是否wordpress
  • 镇江网站制作公司天工网工程新希望官网
  • 汝阳县住房与城乡建设局建局网站北京网站建设招标
  • 特定ip段访问网站代码中国住房和城乡建设部网站证书查询
  • 网站内容建设包括青岛seo
  • 优秀flash网站欣赏个人网页制作设计图
  • 垂直门户网站怎么做网站首页动图怎么做
  • 做网站最主要是什么十大广告公司排名
  • 泉州英文网站建设药品招商网站大全
  • 建设网站有哪些方法有哪些html表单制作