Command Query Responsibility Segregation Pattern (CQRS)
Ngo Tran Quoc Tuan (Liam)
? Software Developer | Java Spring boot | Database | Studies Performance Tuning at Wecommit Vi?t Nam. Let's connect!
Command Query Responsibility Segregation (CQRS) là m?u thi?t k? tách bi?t ho?t ??ng ??c và ghi d? li?u trong m?t h? th?ng. Vi?c tách bi?t này giúp t?ng kh? n?ng m? r?ng, b?o m?t và hi?u su?t, khi?n CQRS tr? thành m?t l?a ch?n ph? bi?n cho các ?ng d?ng ph?c t?p.
Tìm hi?u v? CQRS
CQRS chia h? th?ng thành hai thành ph?n chính:
Vi?c tách bi?t này cho phép t?ng kh? n?ng m? r?ng c?a các ho?t ??ng ??c và ghi m?t cách ??c l?p.
L?i ích c?a CQRS
1. Kh? n?ng m? r?ng ??
2. B?o m?t ??
3. T?i ?u hi?u su?t ?
4. Linh ho?t ??
Tri?n khai CQRS trong Spring Boot
1. Phía Command
@RestController
@RequestMapping("/commands")
public class CommandController {
private final CommandService commandService;
public CommandController(CommandService commandService) {
this.commandService = commandService;
}
@PostMapping("/create")
public ResponseEntity<String> createItem(@RequestBody CreateItemCommand command) {
commandService.handle(command);
return ResponseEntity.ok("T?o m?i thành c?ng");
}
}
2. Phía Query
@RestController
@RequestMapping("/queries")
public class QueryController {
private final QueryService queryService;
public QueryController(QueryService queryService) {
this.queryService = queryService;
}
@GetMapping("/items")
public List<ItemDTO> getAllItems() {
return queryService.getAllItems();
}
}
Khi nào nên s? d?ng CQRS?
? H? th?ng có kh?i l??ng ??c và ghi khác nhau l?n.
? Yêu c?u b?o m?t và phan quy?n cao.
? Các ?ng d?ng ??ng b? s? ki?n.
? Các h? th?ng l?n c?n t?i ?u hi?u su?t.
? Kh?ng thích h?p v?i các ?ng d?ng CRUD ??n gi?n do t?ng ?? ph?c t?p.
K?t lu?n ??
CQRS mang l?i nhi?u l?i ích v? hi?u su?t, kh? n?ng m? r?ng và linh ho?t. Tuy nhiên, nó c?ng ?i kèm v?i ?? ph?c t?p cao h?n. H?y xem xét k? l??ng tr??c khi áp d?ng CQRS cho d? án c?a b?n! ??
? Software Developer | Java Spring boot | Database | Studies Performance Tuning at Wecommit Vi?t Nam. Let's connect!
1 个月Hi Liam, thank you for your article. However, I think your model is not realistic. In real-world scenarios, we typically use different databases—one for writing and another for reading, for example: You can use postgres for writing and elasticsearch for reading
??Full-stack Developer | Database Optimization
1 个月R?t thi?t th?c ?. ?úng cái em ?ang tìm