This is a viewer only at the moment see the article on how this works.
To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk
This is a preview from the server running through my markdig pipeline
Monday, 13 January 2025
ग़ौर करें: यह एक पुराना लेख है जिसे मैं छोड़ना भूल गया ।
यहाँ है, आनंद!
मैं इसे अद्यतन किया लेकिन मैं याद किया हो सकता है कुछ मुद्दों हो सकता है.
इस लेख में, मैं आपको दिखाने के लिए जा रहा हूँ उन्हें आधुनिक औज़ारों का उपयोग करने के लिए ठीक तरह से काम करने के लिए।
**मैं भी तुम को "समसीय-संत्र" कैश- आधारित विकल्प दिखाता हूँ, और समझाता हूँ कि क्यों मैनुअल कैश के साथ घटना को मिलाने की कोशिश कर रहा है।**परिचय
**CQRS (अंग्रेजी ज़िम्मेदारी की घोषणा) और घटना दोनों ही विशिष्ट रूप हैं जो असाधारण रूप से एक साथ काम करते हैं:**सीक्यूआरएस
अपने लेखन मॉडल से अपने पढ़ने के मॉडल अलग करना
घटना अत्यन्त तेज हो रही है
जब मार्टेन की तरह उपकरण के साथ ठीक से किया, आप पाते हैं:
प्रत्येक परिवर्तन का गलत निशान पूरा करें
समय में किसी भी बिन्दु पर राज्य फिर से बनाने के लिए शक्तिमॉडल सहायकों को स्वचलित पढ़ा जा रहा हैडोमेन का डिजाइन के साथ स्वाभाविक फिट
ठीक
// Write Model - Commands that change state
public record CreateBlogPostCommand(string Title, string Content, string AuthorId);
// Read Model - DTOs optimised for display
public class BlogPostListItemDto
{
public Guid Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; }
public DateTime PublishedDate { get; set; }
public int CommentCount { get; set; }
}
सीक्यूआर क्या है?
// Traditional: Store current state
public class BlogPost
{
public Guid Id { get; set; }
public string Title { get; set; } // Current title
public bool IsPublished { get; set; } // Current status
}
// Event Sourcing: Store the events
public record BlogPostCreated(Guid Id, string Title, string Content, DateTime CreatedAt);
public record BlogPostTitleChanged(Guid Id, string OldTitle, string NewTitle, DateTime ChangedAt);
public record BlogPostPublished(Guid Id, DateTime PublishedAt);
अपने कोर पर, सीक्यूआरएस का अर्थ है पढ़ने और डाटा लिखने के लिए अलग मॉडल का प्रयोग करें:
**पढ़ने का किनारा प्रदर्शन के लिए सामान्य तथा अधिकतम है.**सरल पर्याप्त है, लेकिन सही सीक्यूएस का अर्थ है वे अपने अनुप्रयोग के माध्यम से पूरी तरह से अलग पथ कर रहे हैं.
**घटना क्या है?**मौजूदा स्थिति को स्टोर करने के बजाय, आप उन घटनाओं को जमा करते हैं जो कि राज्य के अधीन हो गए हैं:
**वर्तमान स्थिति को पुनःप्ले करने वाली घटना द्वारा लिया गया है.**यह आप अपने तंत्र में कभी हुआ है कि सब कुछ का पूरा इतिहास देता है.
**क्यों घटना का इस्तेमाल सीक्यूस के साथ करें?**ऑडियोपथ ट्रैल पूरा करें
**: हर बदलाव का रिकॉर्ड है ।**आर्थिक व्यवस्थाओं, स्वास्थ्य देखभाल, या आप जहाँ भी हो, यह साबित करने की ज़रूरत है कि क्या हुआ और कब हुआ ।
**: "इस ब्लॉग पोस्ट ने पिछले मंगलवार की तरह क्या देखा?" संक्षिप्त रूप में फिर से उस बिंदु पर घटनाओं को फिर से लोड किया.**डिबगिंग
**: उन घटनाओं के आधार पर फिर से कोशिश करके बग जोड़े.**व्यापार अधिकार
**: बिना पायलटों के ऐतिहासिक आंकड़ों से नई रिपोर्टें बनाइए ।**घटनाएँ पहले से ही मौजूद हैं.
स्वाभाविक सीआरआरटीएस अनुरूप: घटनाएँ स्वाभाविक रूप से अलग होती हैं (कंत्रित घटनाएँ) जिन्हें पढ़ने से अलग किया गया है ।
सादा स्लोरो: अगर आप सिर्फ डेटा जमा कर रहे हैं और फिर से प्राप्त कर रहे हैं, तो घटना अपिंग हास्यास्पद है.अनुभव के बिना छोटा टीम
: सीखने का वक्र खड़ी है.
मारटेन
dotnet add package Marten
dotnet add package Marten.AspNetCore
Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMarten(options =>
{
options.Connection(builder.Configuration.GetConnectionString("Marten")!);
// Register event types
options.Events.AddEventType<BlogPostCreated>();
options.Events.AddEventType<BlogPostPublished>();
options.Events.AddEventType<BlogPostTitleChanged>();
options.Events.AddEventType<CommentAdded>();
// Configure async projections
options.Projections.Add<BlogPostProjection>(ProjectionLifecycle.Async);
});
builder.Services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
var app = builder.Build();
मार्टन क्यों?
flowchart TB
subgraph Client["Client Application"]
UI[User Interface]
end
subgraph Commands["Command Side (Writes)"]
CMD[Commands] --> CMDH[Command Handlers]
CMDH --> MARTEN[Marten Session]
MARTEN --> EVENTS[(Event Store)]
end
subgraph Background["Async Processing"]
EVENTS -.->|Event Stream| DAEMON[Marten Async Daemon]
DAEMON --> PROJ[Projections]
PROJ --> READDB[(Read Models)]
end
subgraph Queries["Query Side (Reads)"]
QRY[Queries] --> QRYH[Query Handlers with Dapper]
QRYH --> READDB
end
UI -->|Commands| CMD
UI -->|Queries| QRY
classDef commandStyle fill:none,stroke:#e63946,stroke-width:3px
classDef queryStyle fill:none,stroke:#457b9d,stroke-width:3px
classDef dataStyle fill:none,stroke:#2a9d8f,stroke-width:3px
class CMD,CMDH,MARTEN commandStyle
class QRY,QRYH queryStyle
class EVENTS,READDB dataStyle
एसक्यूएल पर अंतर्निर्मित (आप पहले से ही जानते हैं)
यहाँ सब कुछ एक साथ फिट होता है:
// Always past tense - these things have happened
public record BlogPostCreated(
Guid BlogPostId,
string Title,
string Content,
string AuthorId,
DateTime CreatedAt
);
public record BlogPostPublished(
Guid BlogPostId,
DateTime PublishedAt
);
public record BlogPostTitleChanged(
Guid BlogPostId,
string OldTitle,
string NewTitle,
DateTime ChangedAt
);
public record CommentAdded(
Guid BlogPostId,
Guid CommentId,
string Author,
string Content,
DateTime CreatedAt
);
कुंजी पाइंट्स:
घटनाएँ नियत की जा रही हैं
public class BlogPost
{
// Marten requires an Id property
public Guid Id { get; set; }
// Current state (private setters)
public string Title { get; private set; } = string.Empty;
public string Content { get; private set; } = string.Empty;
public string AuthorId { get; private set; } = string.Empty;
public bool IsPublished { get; private set; }
public DateTime? PublishedDate { get; private set; }
private readonly List<Comment> _comments = new();
public IReadOnlyList<Comment> Comments => _comments.AsReadOnly();
// Apply methods - called by Marten when replaying events
public void Apply(BlogPostCreated e)
{
Id = e.BlogPostId;
Title = e.Title;
Content = e.Content;
AuthorId = e.AuthorId;
}
public void Apply(BlogPostPublished e)
{
IsPublished = true;
PublishedDate = e.PublishedAt;
}
public void Apply(BlogPostTitleChanged e)
{
Title = e.NewTitle;
}
public void Apply(CommentAdded e)
{
_comments.Add(new Comment
{
Id = e.CommentId,
Author = e.Author,
Content = e.Content,
CreatedAt = e.CreatedAt
});
}
// Business logic methods that produce events
public static BlogPostCreated Create(string title, string content, string authorId)
{
if (string.IsNullOrWhiteSpace(title))
throw new ArgumentException("Title is required");
return new BlogPostCreated(
Guid.NewGuid(),
title,
content,
authorId,
DateTime.UtcNow
);
}
public BlogPostPublished Publish()
{
if (IsPublished)
throw new InvalidOperationException("Post is already published");
return new BlogPostPublished(Id, DateTime.UtcNow);
}
public BlogPostTitleChanged ChangeTitle(string newTitle)
{
if (string.IsNullOrWhiteSpace(newTitle))
throw new ArgumentException("Title cannot be empty");
if (newTitle == Title)
throw new InvalidOperationException("New title is the same as current title");
return new BlogPostTitleChanged(Id, Title, newTitle, DateTime.UtcNow);
}
}
public class Comment
{
public Guid Id { get; set; }
public string Author { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
}
घटनाएँ सक्षम नहीं की गई हैं जो उन चीजों का वर्णन करती हैं जो हुई हैं:
// Define commands
public record CreateBlogPostCommand(
string Title,
string Content,
string AuthorId
) : IRequest<Guid>;
public record PublishBlogPostCommand(Guid BlogPostId) : IRequest;
public record ChangeBlogPostTitleCommand(
Guid BlogPostId,
string NewTitle
) : IRequest;
// Handler for creating a blog post
public class CreateBlogPostHandler : IRequestHandler<CreateBlogPostCommand, Guid>
{
private readonly IDocumentSession _session;
public CreateBlogPostHandler(IDocumentSession session)
{
_session = session;
}
public async Task<Guid> Handle(CreateBlogPostCommand request, CancellationToken cancellationToken)
{
// Create the event
var created = BlogPost.Create(
request.Title,
request.Content,
request.AuthorId
);
// Start a new event stream
_session.Events.StartStream<BlogPost>(created.BlogPostId, created);
await _session.SaveChangesAsync(cancellationToken);
return created.BlogPostId;
}
}
// Handler for publishing
public class PublishBlogPostHandler : IRequestHandler<PublishBlogPostCommand>
{
private readonly IDocumentSession _session;
public PublishBlogPostHandler(IDocumentSession session)
{
_session = session;
}
public async Task Handle(PublishBlogPostCommand request, CancellationToken cancellationToken)
{
// Load the aggregate by replaying its events
var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(
request.BlogPostId,
token: cancellationToken
);
if (blogPost == null)
throw new InvalidOperationException($"Blog post {request.BlogPostId} not found");
// Business logic produces new event
var published = blogPost.Publish();
// Append event to the stream
_session.Events.Append(request.BlogPostId, published);
await _session.SaveChangesAsync(cancellationToken);
}
}
// Handler for changing title
public class ChangeBlogPostTitleHandler : IRequestHandler<ChangeBlogPostTitleCommand>
{
private readonly IDocumentSession _session;
public ChangeBlogPostTitleHandler(IDocumentSession session)
{
_session = session;
}
public async Task Handle(ChangeBlogPostTitleCommand request, CancellationToken cancellationToken)
{
var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(
request.BlogPostId,
token: cancellationToken
);
if (blogPost == null)
throw new InvalidOperationException($"Blog post {request.BlogPostId} not found");
var titleChanged = blogPost.ChangeTitle(request.NewTitle);
_session.Events.Append(request.BlogPostId, titleChanged);
await _session.SaveChangesAsync(cancellationToken);
}
}
व्यवसाय में धनी
पैटर्न:
आंतरिक स्थिति अद्यतन करने के लिए विधियाँ लागू करें
// Read model - optimised for queries
public class BlogPostReadModel
{
public Guid Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public string AuthorId { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public DateTime? PublishedAt { get; set; }
public bool IsPublished { get; set; }
public int CommentCount { get; set; }
}
// Projection - tells Marten how to build read models from events
public class BlogPostProjection : MultiStreamProjection<BlogPostReadModel, Guid>
{
public BlogPostProjection()
{
// Identity tells Marten which stream each event belongs to
Identity<BlogPostCreated>(x => x.BlogPostId);
Identity<BlogPostPublished>(x => x.BlogPostId);
Identity<BlogPostTitleChanged>(x => x.BlogPostId);
Identity<CommentAdded>(x => x.BlogPostId);
}
// Apply methods - Marten calls these to update read models
public void Apply(BlogPostReadModel view, BlogPostCreated e)
{
view.Id = e.BlogPostId;
view.Title = e.Title;
view.Content = e.Content;
view.AuthorId = e.AuthorId;
view.CreatedAt = e.CreatedAt;
view.IsPublished = false;
}
public void Apply(BlogPostReadModel view, BlogPostPublished e)
{
view.IsPublished = true;
view.PublishedAt = e.PublishedAt;
}
public void Apply(BlogPostReadModel view, BlogPostTitleChanged e)
{
view.Title = e.NewTitle;
}
public void Apply(BlogPostReadModel view, CommentAdded e)
{
view.CommentCount++;
}
}
मारटन घटना लगन और फिर खेल को संभालता है
कमांडों को नदियों में जोड़ने के लिए हैंडल किया जाता है:
// Define queries
public record GetRecentBlogPostsQuery(
int Count,
bool PublishedOnly
) : IRequest<List<BlogPostListItemDto>>;
public record GetBlogPostByIdQuery(Guid Id) : IRequest<BlogPostDetailDto?>;
// DTOs for display
public class BlogPostListItemDto
{
public Guid Id { get; set; }
public string Title { get; set; } = string.Empty;
public string AuthorName { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public DateTime? PublishedAt { get; set; }
public int CommentCount { get; set; }
public bool IsPublished { get; set; }
}
public class BlogPostDetailDto
{
public Guid Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public string AuthorId { get; set; } = string.Empty;
public string AuthorName { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public DateTime? PublishedAt { get; set; }
public bool IsPublished { get; set; }
public List<CommentDto> Comments { get; set; } = new();
}
public class CommentDto
{
public Guid Id { get; set; }
public string Author { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
}
// Query handlers
public class GetRecentBlogPostsHandler : IRequestHandler<GetRecentBlogPostsQuery, List<BlogPostListItemDto>>
{
private readonly string _connectionString;
public GetRecentBlogPostsHandler(IConfiguration config)
{
_connectionString = config.GetConnectionString("Marten")!;
}
public async Task<List<BlogPostListItemDto>> Handle(
GetRecentBlogPostsQuery request,
CancellationToken cancellationToken)
{
await using var connection = new NpgsqlConnection(_connectionString);
// Query the Marten-generated read model table
const string sql = @"
SELECT
bp.id AS Id,
bp.title AS Title,
u.name AS AuthorName,
bp.created_at AS CreatedAt,
bp.published_at AS PublishedAt,
bp.comment_count AS CommentCount,
bp.is_published AS IsPublished
FROM blog_post_read_models bp
LEFT JOIN users u ON bp.author_id = u.id
WHERE (@PublishedOnly = false OR bp.is_published = true)
ORDER BY
CASE WHEN bp.is_published THEN bp.published_at
ELSE bp.created_at
END DESC
LIMIT @Count";
var results = await connection.QueryAsync<BlogPostListItemDto>(
sql,
new
{
PublishedOnly = request.PublishedOnly,
Count = request.Count
});
return results.ToList();
}
}
public class GetBlogPostByIdHandler : IRequestHandler<GetBlogPostByIdQuery, BlogPostDetailDto?>
{
private readonly string _connectionString;
public GetBlogPostByIdHandler(IConfiguration config)
{
_connectionString = config.GetConnectionString("Marten")!;
}
public async Task<BlogPostDetailDto?> Handle(
GetBlogPostByIdQuery request,
CancellationToken cancellationToken)
{
await using var connection = new NpgsqlConnection(_connectionString);
const string sql = @"
SELECT
bp.id AS Id,
bp.title AS Title,
bp.content AS Content,
bp.author_id AS AuthorId,
u.name AS AuthorName,
bp.created_at AS CreatedAt,
bp.published_at AS PublishedAt,
bp.is_published AS IsPublished
FROM blog_post_read_models bp
LEFT JOIN users u ON bp.author_id = u.id
WHERE bp.id = @Id";
var post = await connection.QuerySingleOrDefaultAsync<BlogPostDetailDto>(
sql,
new { request.Id });
if (post == null)
return null;
// Get comments from event stream if needed
// Or maintain a separate comment read model
return post;
}
}
प्रवाहः
काल व्यापार विधि (vervs और घटना को लौटाता है)
[ApiController]
[Route("api/[controller]")]
public class BlogPostsController : ControllerBase
{
private readonly IMediator _mediator;
public BlogPostsController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<ActionResult<List<BlogPostListItemDto>>> GetRecent(
[FromQuery] int count = 10,
[FromQuery] bool publishedOnly = true)
{
var query = new GetRecentBlogPostsQuery(count, publishedOnly);
var results = await _mediator.Send(query);
return Ok(results);
}
[HttpGet("{id}")]
public async Task<ActionResult<BlogPostDetailDto>> GetById(Guid id)
{
var query = new GetBlogPostByIdQuery(id);
var result = await _mediator.Send(query);
if (result == null)
return NotFound();
return Ok(result);
}
[HttpPost]
public async Task<ActionResult<Guid>> Create([FromBody] CreateBlogPostCommand command)
{
var postId = await _mediator.Send(command);
return CreatedAtAction(nameof(GetById), new { id = postId }, postId);
}
[HttpPost("{id}/publish")]
public async Task<ActionResult> Publish(Guid id)
{
await _mediator.Send(new PublishBlogPostCommand(id));
return NoContent();
}
[HttpPut("{id}/title")]
public async Task<ActionResult> ChangeTitle(
Guid id,
[FromBody] ChangeBlogPostTitleCommand command)
{
if (id != command.BlogPostId)
return BadRequest();
await _mediator.Send(command);
return NoContent();
}
}
परिवर्तन सहेजें
sequenceDiagram
participant Client
participant Controller
participant MediatR
participant CommandHandler
participant Marten
participant EventStore
participant AsyncDaemon
participant ReadDB
participant QueryHandler
Note over Client,ReadDB: Write Operation
Client->>Controller: POST /api/blogposts
Controller->>MediatR: Send CreateBlogPostCommand
MediatR->>CommandHandler: Handle command
CommandHandler->>CommandHandler: Validate & create event
CommandHandler->>Marten: StartStream(event)
Marten->>EventStore: Append event
EventStore-->>Marten: Success
Marten-->>CommandHandler: Success
CommandHandler-->>Controller: Return ID
Controller-->>Client: 201 Created
Note over AsyncDaemon,ReadDB: Background Processing
EventStore->>AsyncDaemon: New event available
AsyncDaemon->>AsyncDaemon: Apply projection
AsyncDaemon->>ReadDB: Update read model
ReadDB-->>AsyncDaemon: Updated
Note over Client,ReadDB: Read Operation
Client->>Controller: GET /api/blogposts
Controller->>MediatR: Send Query
MediatR->>QueryHandler: Handle query
QueryHandler->>ReadDB: SELECT with Dapper
ReadDB-->>QueryHandler: Return data
QueryHandler-->>Controller: Return DTOs
Controller-->>Client: 200 OK
मॉडलों और परियोजनाओं को पढ़ें
परियोजना परिवर्तन घटनाएँ सामान्य रूप से पढ़ने योग्य मॉडलों में बदल जाते हैं:
builder.Services.AddMarten(options =>
{
// This projection runs synchronously
options.Projections.Add<CriticalDataProjection>(ProjectionLifecycle.Inline);
// This projection runs async
options.Projections.Add<BlogPostProjection>(ProjectionLifecycle.Async);
});
मार्टेन के अतुल्यकालिक डेमन घटनाएँ पृष्ठभूमि में होती हैं और तिथि पर मॉडल पढ़ने की जारी रहती हैं.
var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(id);
Dapper के साथ क्वैरी बाजू
मीडिया पर, नियंत्रण बहुत ही सरल है:
// Command handler
public class CreateBlogPostHandler : IRequestHandler<CreateBlogPostCommand, int>
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _cache;
public async Task<int> Handle(CreateBlogPostCommand request, CancellationToken cancellationToken)
{
var blogPost = new BlogPost
{
Title = request.Title,
Content = request.Content,
AuthorId = request.AuthorId,
PublishedDate = DateTime.UtcNow
};
_context.BlogPosts.Add(blogPost);
await _context.SaveChangesAsync(cancellationToken);
// Manual cache invalidation - this is the tedious bit
_cache.Remove("recent-posts");
_cache.Remove($"author-posts-{request.AuthorId}");
_cache.Remove($"post-{blogPost.Id}");
return blogPost.Id;
}
}
// Query handler
public class GetRecentPostsHandler : IRequestHandler<GetRecentPostsQuery, List<BlogPostDto>>
{
private readonly string _connectionString;
private readonly IMemoryCache _cache;
public async Task<List<BlogPostDto>> Handle(GetRecentPostsQuery request, CancellationToken cancellationToken)
{
var cacheKey = "recent-posts";
if (_cache.TryGetValue<List<BlogPostDto>>(cacheKey, out var cached))
return cached!;
// Cache miss - query with Dapper
using var connection = new NpgsqlConnection(_connectionString);
var posts = (await connection.QueryAsync<BlogPostDto>(
"SELECT id, title, author_name, published_date FROM blog_posts ORDER BY published_date DESC LIMIT 10"
)).ToList();
_cache.Set(cacheKey, posts, TimeSpan.FromMinutes(5));
return posts;
}
}
**भाग 2: आधा- से- अधिक जानकारी (सी- छाँट)**ठीक है, तो तुमने सही घटना के बारे में पढ़ा है सोचिंग और आप सोच रहे हैं कि "काम का एक बहुत कुछ है."
**बहुत अच्छे।**यहाँ "इनफ़ॉर्मल सीआर" है कि अधिकांश टीम वास्तव में उपयोग करते हैं।
सेटअपडाटाबेस में कमांड लिखने के लिए (एएफ या डीएचर के जरिए)
**मैं मेकरीश या आईडीिस्टीश से पढ़ा.**लिखने के बाद इस्तेमाल के लिए औज़ारों को अवैध करता है
कोई घटना केआईओिंग नहीं, कोई प्रोजेक्शन, कोई अतुल्यकालिक डेमन नहींयह सच सीक्यूआरएस नहीं है.
तुम्हें पता नहीं है कि आप एक निष्क्रिय निशान, macuties, या स्वचालित प्रक्षेपण नहीं मिलता है.
क्विक उदाहरण
जटिल आवश्यकताओं के बगैर सरल अनुप्रयोग
आप प्रदर्शन की जरूरत है लेकिन जटिलता को उचित नहीं कर सकते
कुछ सेकण्डों की स्थिरता स्वीकार्य हैसमस्याएँ
कैश अवैध है: मिस एक कैश कुंजी और आप केमरिस डाटा सेवा करते हैं.
**हर कमांड को जानना होगा कि कौन सा कैश अवैध है.**सूची पता नहीं लगाएँ (D)
**: आपके पास सिर्फ मौज़ूदा राज्य है.**क्या हुआ या जब साबित नहीं कर सकते.
यु. पू.: क्या नहीं पूछ सकता है "दुनिया कल कैसा दिखता है?"
: मेपलसीश के साथ, प्रत्येक सर्वर का अपना कैश है.
क्वैरी बदलें, कमांड तोड़ सकता है.
भाग ३: सब से बुरा घटना सोकिंग + मैनुअल कैशिंग
// Don't do this!
public class PublishBlogPostHandler : IRequestHandler<PublishBlogPostCommand>
{
private readonly IDocumentSession _session;
private readonly IMemoryCache _cache; // ← BAD
public async Task Handle(PublishBlogPostCommand request, CancellationToken cancellationToken)
{
var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(request.BlogPostId);
var published = blogPost.Publish();
_session.Events.Append(request.BlogPostId, published);
await _session.SaveChangesAsync(cancellationToken);
// Manually invalidating cache while using Event Sourcing ← TERRIBLE IDEA
_cache.Remove($"post-{request.BlogPostId}");
_cache.Remove("recent-posts");
// Now you have:
// 1. Event in event store
// 2. Cache invalidated
// 3. But projection hasn't run yet!
// Queries will hit database before projection completes = stale data
}
}
लोग ऐसा क्यों करते हैं
तो वे सोचते हैं कि "मैं केवल कैश को अवैध रूप से पढ़ने के लिए सक्षम करता हूँ और अधिक संगत बनाने के लिए"
क्यों यह भयानक है
: अब आपके पास दो सिस्टम हैं सिंक - मारटन प्रक्षेपण में मॉडल पढ़ने के लिए और अपने मैनुअल कैश अवैध.
वे सिंक से बाहर हैं.
डिबगिंग सपना
सही सवाल
मार्टेन के प्रक्षेपण का प्रयोग करें (अंड या इनलाइन)
पढ़ने के मॉडलों से सीधे क्वैरी करेंसमाप्ति संगतता स्वीकारें (यह आमतौर पर ठीक है)इनलाइन प्रक्षेपण का प्रयोग करें यदि आपको वास्तव में तत्काल संगतता की आवश्यकता है
© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.