- Updated service template structure in `ARCHITECTURE.md` and `README.md` for clarity and usability. - Enhanced bilingual documentation across skills, increasing the number of available skills from 15 to 25. - Added new sections on event-driven architecture, inter-service communication, and performance optimization. - Improved formatting and removed outdated references to streamline the documentation experience.
7.0 KiB
Giao Tiếp Giữa Các Services (Inter-Service Communication)
Inter-service communication patterns for GoodGo microservices including gRPC, GraphQL, service-to-service authentication, protocol selection, and client patterns. Use when implementing service-to-service calls, choosing communication protocols, or building service clients.
Các patterns giao tiếp giữa services cho GoodGo microservices bao gồm gRPC, GraphQL, service-to-service authentication, lựa chọn protocol, và client patterns. Sử dụng khi implement service-to-service calls, chọn communication protocols, hoặc xây dựng service clients.
Tổng Quan
Inter-service communication enables services to work together in a microservices architecture. GoodGo supports multiple protocols: HTTP/REST (current standard), gRPC (for high performance), and GraphQL (for flexible queries). This skill covers patterns for implementing resilient, secure, and performant inter-service communication.
Giao tiếp giữa các services cho phép các services làm việc cùng nhau trong kiến trúc microservices. GoodGo hỗ trợ nhiều protocols: HTTP/REST (chuẩn hiện tại), gRPC (cho hiệu suất cao), và GraphQL (cho queries linh hoạt). Skill này bao gồm các patterns để implement giao tiếp giữa services có khả năng phục hồi, bảo mật và hiệu suất cao.
Khi Nào Sử Dụng
Use this skill when:
- Implementing service-to-service communication
- Choosing between REST, gRPC, or GraphQL protocols
- Setting up gRPC services and clients
- Implementing GraphQL services and resolvers
- Implementing service-to-service authentication
- Building resilient service clients with circuit breakers
Sử dụng skill này khi:
- Implement giao tiếp giữa các services
- Chọn giữa REST, gRPC, hoặc GraphQL protocols
- Setup gRPC services và clients
- Implement GraphQL services và resolvers
- Implement service-to-service authentication
- Xây dựng service clients có khả năng phục hồi với circuit breakers
Khái Niệm Chính
Các Lựa Chọn Protocol
HTTP/REST:
- Dễ đọc, dễ debug / Human-readable, easy to debug
- Tương thích browser / Browser-compatible
- Semantics HTTP chuẩn / Standard HTTP semantics
- JSON payloads
- Tốt cho external APIs / Good for external APIs
gRPC:
- Binary protocol (Protocol Buffers)
- Hiệu suất cao, độ trễ thấp / High performance, low latency
- Hỗ trợ streaming / Streaming support
- Strong typing với .proto files
- Dựa trên HTTP/2 / HTTP/2 based
GraphQL:
- Ngôn ngữ query linh hoạt / Flexible query language
- Single endpoint
- Client kiểm soát data fetching / Client-controlled data fetching
- Strong typing với schema
Hướng Dẫn Lựa Chọn Protocol
Chọn protocol dựa trên use case, yêu cầu hiệu suất, chuyên môn team, và nhu cầu ecosystem.
Choose protocol based on use case, performance requirements, team expertise, and ecosystem needs.
Các Patterns Chính
HTTP/REST Service Client
// EN: Service client với circuit breaker
// VI: Service client với circuit breaker
import { ServiceClient } from '../../core/clients/service-client';
const notificationClient = new ServiceClient({
baseURL: process.env.NOTIFICATION_SERVICE_URL || 'http://notification-service:5003',
serviceName: 'notification-service',
timeout: 5000,
enableCircuitBreaker: true,
});
// EN: Usage
// VI: Sử dụng
await notificationClient.post('/api/v1/notifications', {
userId,
message,
});
gRPC Service
// EN: gRPC server
// VI: gRPC server
import { UserGrpcServer } from './user.grpc.service';
const grpcServer = new UserGrpcServer(userService);
grpcServer.start(50051);
// EN: gRPC client
// VI: gRPC client
const userGrpcClient = new GrpcClient({
protoPath: './proto/user_service.proto',
packageName: 'goodgo.user.v1',
serviceName: 'UserService',
serverUrl: 'localhost:50051',
});
const user = await userGrpcClient.call('getUser', { user_id: '123' });
GraphQL Service
// EN: GraphQL client
// VI: GraphQL client
const userGraphQLClient = new GraphQLServiceClient({
endpoint: 'http://user-service:5002/graphql',
});
const GET_USER_QUERY = `
query GetUser($id: ID!) {
user(id: $id) {
id
email
name
}
}
`;
const user = await userGraphQLClient.query(GET_USER_QUERY, { id: '123' });
Service-to-Service Authentication
// EN: Internal auth middleware
// VI: Internal auth middleware
import { internalAuthMiddleware } from '../../middlewares/internal-auth.middleware';
router.use('/internal', internalAuthMiddleware);
// EN: Client tự động thêm auth header
// VI: Client automatically adds auth header
const client = new ServiceClient({
baseURL: 'http://service:5000',
serviceName: 'service',
});
// X-Service-Auth header được thêm tự động
Best Practices / Thực Hành Tốt
Protocol Selection / Lựa Chọn Protocol
- REST: External APIs, browser clients, simple CRUD / APIs ngoài, browser clients, CRUD đơn giản
- gRPC: Internal services, high performance, streaming / Services nội bộ, hiệu suất cao, streaming
- GraphQL: Complex queries, mobile apps, flexible data / Queries phức tạp, mobile apps, data linh hoạt
Performance / Hiệu Suất
- Use connection pooling / Sử dụng connection pooling
- Enable HTTP keep-alive / Bật HTTP keep-alive
- Set appropriate timeouts / Thiết lập timeout phù hợp
- Implement circuit breakers / Implement circuit breakers
Security / Bảo Mật
- Always authenticate internal calls / Luôn xác thực internal calls
- Use TLS/mTLS / Sử dụng TLS/mTLS
- Store secrets securely / Lưu secrets an toàn
- Implement rate limiting / Implement rate limiting
Observability / Khả Năng Quan Sát
- Log with correlation IDs / Ghi log với correlation IDs
- Track metrics (duration, success rate) / Theo dõi metrics
- Add distributed tracing / Thêm distributed tracing
- Monitor service health / Giám sát sức khỏe service
Testing / Kiểm Thử
// EN: Mock service client
// VI: Mock service client
const mockClient = createMockServiceClient();
mockClient.get.mockResolvedValue({ id: '123' });
Skills Liên Quan
- Resilience Patterns - Circuit breaker, retry patterns / Circuit breaker, các patterns retry
- Security - Authentication, authorization / Authentication, authorization
- API Design - RESTful API patterns / RESTful API patterns
- Project Rules - GoodGo coding standards / Tiêu chuẩn coding GoodGo
Tài Nguyên
- gRPC Documentation - Tài liệu gRPC chính thức
- GraphQL Documentation - Tài liệu GraphQL
- Protocol Buffers - Hướng dẫn Protocol Buffers
- Skill Source:
.cursor/skills/inter-service-communication/SKILL.md- Source file đầy đủ