Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Thành thạo Redis: Nâng cao hạ tầng Microservices với Messaging nâng cao

Năm 2019, tôi viết về cách tạo event store trong Redis. Tôi giải thích Redis Streams phù hợp cho event store, vì chúng lưu events trong immutable append-only mechanism như transaction log. Bây giờ, với update của sample OrderShop application giới thiệu trong blog đó, tôi sẽ demo cách dùng Redis as a message queue, thêm chứng minh nhiều use cases Redis Enterprise ngoài caching.

Nhìn nhanh microservices, infrastructure services, distributed systems

Redis là great solution tạo infrastructure services như message queues và event stores, nhưng có vài điều cần cân nhắc khi dùng microservices architecture tạo distributed system. Relational databases thường tốt cho monolithic applications, nhưng chỉ NoSQL databases như Redis cung cấp scalability và availability requirements cần cho microservices architecture.

Distributed systems ngụ ý distributed state. Theo CAP theorem, software implementation chỉ deliver 2 trong 3 attributes: consistency, availability, partition tolerance (CAP). Vì vậy, để fault tolerant, bạn phải chọn giữa availability và consistency. Nếu chọn availability, eventual consistency—data consistent sau một thời gian. Chọn consistency ảnh hưởng performance vì cần synchronize và isolate write operations throughout distributed system.

Event sourcing, persist state của business entity như order, customer, as sequence of state-changing events, chọn availability thay vì consistency. Cho phép write operations trivial, nhưng read operations costly hơn vì, nếu span multiple services, có thể require additional mechanism như read model.

Communication trong distributed system có thể brokered hoặc brokerless. Brokerless styles well-known, HTTP famous instance. Brokered approach có broker giữa sender và receiver của message. Nó decouples sender và receiver, enable synchronous và asynchronous communication. Result more resilient behavior vì message consumer không cần available tại thời điểm message sent. Brokered communication cũng cho phép independent scaling sender và receiver.

(Thêm info, xem post What to Choose for Your Synchronous and Asynchronous Communication Needs—Redis Streams, Redis Pub/Sub, Kafka, etc.)

OrderShop: sample e-commerce implementation

"Hello World" của microservice architecture là OrderShop, simple implementation e-commerce system dùng event-based approach. Sample app dùng simple domain model, nhưng fulfill application's purpose.

OrderShop orchestrated dùng Docker Compose. All network communication qua gRPC. Central components là event store và message queue: each service connected to và only to them qua gRPC. OrderShop sample implementation Python. Xem source code trên GitHub.

(Note: Code này không production-ready, chỉ demo purposes!)

Run and fun

  • Clone GitHub repository: https://github.com/redis-demos/ordershop-v2
  • Chạy OrderShop v2 quy trình 5 bước đơn giản:
  1. Start app với docker-compose up
  2. Mở browser vào https://localhost:5000/
    1. Watch events và browse state
  3. Run client với python -m unittest tests/unit.py
  4. Mở tab khác browser vào https://localhost:8001/
    1. Dùng redis:6379 connect test database
  5. Stop app với docker-compose down

OrderShop v2 architecture

Trong case này, server architecture gồm multiple services. State distributed over several domain services nhưng stored trong single event store. Component Read model tập trung logic reading và caching state, như hình:

Thành thạo Redis: Nâng cao hạ tầng Microservices với Messaging nâng cao

Commands và queries communicated via Message queue component, trong khi events communicated via Event store component, cũng đóng vai event bus.

Infrastructure services

Trong OrderShop v2, all unicast communication xảy ra qua Message queue component. Tôi dùng Redis Lists, đặc biệt 2 lists combined into "reliable queue". Xử lý simple commands (single entity operations) synchronously, nhưng long-running ones (batches, mails) asynchronously và support responses cho synchronous messages out of the box.

Event store based on Redis Streams. Domain services (chỉ dummies demo OrderShop functionality) subscribed đến event streams named after event topic (entity name) và publish events onto streams. Mỗi event là stream-entry với event timestamp as ID. Tổng published events in streams resulting in overall system state.

Application services

Read model caches deduced entities từ Event store trong Redis dùng domain model. Disregarding cache, nó stateless.

API gateway stateless, serve REST-API trên port 5000. Terminate HTTP connections và route chúng either đến read model reading state (queries) hoặc dedicated domain service writing state (commands). Conceptual separation giữa read/write operations là pattern Command Query Responsibility Segregation (CQRS).

Domain services

Domain services nhận write operations qua Message queue từ API gateway. Sau successful execution, publish event cho each đến Event store. Ngược lại, all read operations handled by Read model get state từ Event store.

CRM service (Customer Relation Management service) stateless—subscribed domain events từ event store và send emails cho customers dùng Mail service.

Central domain entity là order. Có field 'status' transitions performed dùng state machine, như diagram:

Thành thạo Redis: Nâng cao hạ tầng Microservices với Messaging nâng cao

Transitions done trong several event handlers, subscribed domain events (SAGA pattern), ví dụ:

Clients

Clients simulated dùng Unit testing framework Python. Hiện 10 unit tests implemented. Xem tests/unit.py chi tiết.

Simple UI served port 5000 watch events và browse state (dùng WebSockets).

RedisInsight container cũng available inspect Redis instance. Mở browser https://localhost:8001/ và dùng redis:6379 connect test database.

Thành thạo Redis: Nâng cao hạ tầng Microservices với Messaging nâng cao

Kết luận

Redis không chỉ powerful tool ở domain layer (catalog search) và application layer (HTTP session store) mà còn infrastructure layer (event store hoặc message queue). Dùng Redis throughout các layers giảm operational overhead và cho developers reuse technologies họ đã biết.

Tham khảo code và thử implement. Hy vọng demo Redis's versatility và flexibility trong domain và infrastructure services và chứng minh dùng beyond caching.

Cho biết kết quả trên Twitter: @martinez099.