服务间通信
RESTful API
# 请求
GET /api/users/123 HTTP/1.1
Host: user-service:8080
Accept: application/json
Authorization: Bearer <token>
# 响应
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 123,
"name": "Alice",
"email": "alice@example.com"
}
gRPC
gRPC 使用 Protocol Buffers 作为接口定义语言:
syntax = "proto3";
service UserService {
rpc GetUser (GetUserRequest) returns (User);
rpc ListUsers (ListUsersRequest) returns (stream User);
}
message GetUserRequest {
int64 user_id = 1;
}
message User {
int64 id = 1;
string name = 2;
string email = 3;
}
优势
- 基于 HTTP/2,性能更高
- Protocol Buffers 二进制序列化
- 强类型接口定义
- 支持双向流
消息队列
Kafka 示例
// 生产者
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "StringSerializer");
props.put("value.serializer", "StringSerializer");
Producer<String, String> producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<>("orders", "order-123", "{"id":123}"));
使用场景
| 模式 | 说明 | 适用场景 |
|---|---|---|
| 事件驱动 | 异步通知 | 订单状态变更 |
| 消息分发 | 广播给多个消费者 | 数据同步 |
| 日志采集 | 集中式收集 | 监控审计 |
API 网关
services:
- name: user-service
url: http://user-service:8080
routes:
- paths: [/api/users/*]
- name: order-service
url: http://order-service:8080
routes:
- paths: [/api/orders/*]
