การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS)
ใช้รูปแบบ CQRS เพื่อแยกการอ่านและการเขียนในแอปพลิเคชันโดยใช้ RabbitMQ เพิ่มความสามารถในการขยายระบบและประสิทธิภาพสำหรับระบบที่ใช้ข้อมูลจำนวนมาก
การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS) เป็นบทเรียน RabbitMQ Messaging & Async Systems ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน RabbitMQ Messaging & Async Systems และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is CQRS?
Ever wished your application could handle tons of writes and reads without slowing down? That's where CQRS comes in! It stands for Command-Query Responsibility Segregation.
CQRS is an architectural pattern that separates the operations for reading data from the operations for updating data. Think of it as having two specialized teams: one for taking orders and one for answering questions.
Understanding Commands
The "Command" side handles all requests that change the state of your application. These are actions like "CreateProduct", "UpdateOrderStatus", or "AddUser".
- Commands are imperative: They tell the system to do something specific.
- Commands are processed: They go through handlers that validate and execute the requested change.
- Commands often trigger events: After a command is successfully processed, an event might be published.
Understanding Queries
The "Query" side is all about retrieving data. These are requests like "GetProductDetails", "ListAllOrders", or "FindUsersByLocation".
- Queries are declarative: They ask for information without changing anything.
- Queries use optimized models: Data is often stored in a read-optimized format, perfect for fast retrieval.
- Queries return data: They provide the information requested by the user interface or other services.
Benefits of CQRS
Separating commands and queries offers several advantages, especially in complex systems:
- Scalability: You can scale read and write services independently. Read models often get more traffic.
- Performance: Read models can be highly optimized for queries (e.g., de-normalized data, different databases).
- Flexibility: Different data stores can be used for reads (e.g., NoSQL for speed) and writes (e.g., SQL for consistency).
- Simplicity: Each model is simpler, focused on its specific task.
RabbitMQ's Role in CQRS
RabbitMQ is an excellent fit for implementing CQRS, particularly for the command side. When a command is issued, it can be published as a message to a RabbitMQ queue.
Consumers (command handlers) then pick up these messages and execute the business logic to update the write model. This makes command processing asynchronous and decoupled.
Producer: Update Product Name
Let's imagine we want to update a product's name. We'll send a "UpdateProductNameCommand" message to RabbitMQ. Here's a simple Java producer example:
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class CommandProducer {
private final static String QUEUE_NAME = "product_commands";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost"); // Assuming RabbitMQ is local
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String commandJson = "{\"commandType\":\"UpdateProductName\", \"productId\":\"P123\", \"newName\":\"New Awesome Product\"}";
channel.basicPublish("", QUEUE_NAME, null, commandJson.getBytes("UTF-8"));
System.out.println(" [x] Sent command: '" + commandJson + "'");
}
}
}Consumer: Process Product Update
On the other side, a consumer service (our command handler) listens for these commands. When it receives an "UpdateProductName" command, it updates the authoritative write model (e.g., a SQL database).
This consumer represents the "write" side of our CQRS architecture.
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
public class CommandConsumer {
private final static String QUEUE_NAME = "product_commands";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for commands. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received command: '" + message + "'");
// In a real app, parse JSON, validate, update write model (e.g., database)
System.out.println(" [x] Product write model updated for: " + message.split(":")[2].split(",")[0]);
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}Synchronizing Read Models
After the write model is updated, how does the read model get the new data? This is often done by publishing events.
When a product name changes, the command handler can publish a "ProductNameUpdatedEvent" to another RabbitMQ exchange. A separate service (a projector or denormalizer) subscribes to this event and updates the read-optimized data store.
- Write Model: Optimized for transactional consistency.
- Read Model: Optimized for query performance.
Fast Data Retrieval
With the read model now updated, client applications can query it directly. Since this model is specifically designed for reads, queries are often much faster and simpler.
For example, a product catalog service would query this read model to display product details, without ever touching the complex transactional write model.
CQRS Core Principle
Consider the architecture we've discussed. What is the primary benefit of separating read and write models in CQRS?
CQRS: Scalability & Performance
In this lesson, you learned about Command-Query Responsibility Segregation (CQRS). We saw how it separates data modification (commands) from data retrieval (queries), often using different data models.
RabbitMQ plays a crucial role by enabling asynchronous processing of commands, allowing for independent scaling and optimization of your application's read and write functionalities. This pattern is powerful for data-intensive and high-performance systems.
เรียนรู้ RabbitMQ Messaging & Async Systems ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 11
- บทเรียน
- 44
คำถามที่พบบ่อย
บทเรียน “การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS)” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS)” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส RabbitMQ Messaging & Async Systems ให้อัปเกรดเป็น CoddyKit PRO คอร์ส RabbitMQ Messaging & Async Systems มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS)”
ใช้รูปแบบ CQRS เพื่อแยกการอ่านและการเขียนในแอปพลิเคชันโดยใช้ RabbitMQ เพิ่มความสามารถในการขยายระบบและประสิทธิภาพสำหรับระบบที่ใช้ข้อมูลจำนวนมาก คุณปฏิบัติ RabbitMQ Messaging & Async Systems ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน RabbitMQ Messaging & Async Systems หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน RabbitMQ Messaging & Async Systems บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS)” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน RabbitMQ Messaging & Async Systems นี้ได้ไหม
ได้ บทเรียน RabbitMQ Messaging & Async Systems ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ความเป็นไอดีมโพเทนต์ในการประมวลผลข้อความ
- รูปแบบ Saga ด้วย RabbitMQ
- การแยกความรับผิดชอบคำสั่งและการสอบถาม (CQRS)
- รูปแบบ Outbox สำหรับการเผยแพร่ที่เชื่อถือได้