php方案 微服务网关架构
·
class ApiGateway {
private $routes = [
'/user/*' => ['host' => ['http://user-service-1', 'http://user-service-2']],
'/order/*' => ['host' => ['http://order-service-1', 'http://order-service-2']],
'/product/*' => ['host' => ['http://product-service']],
];
// 路由转发 + 负载均衡(轮询)
function route($path) {
foreach ($this->routes as $pattern => $config) {
if (fnmatch($pattern, $path)) {
$hosts = $config['host'];
$index = crc32($path) % count($hosts); // 简单轮询
return $hosts[$index];
}
}
throw new Exception("Route not found");
}
// 请求处理
function handle($method, $path, $body = null) {
// 1. 认证
if (!$this->authenticate()) {
return ['code' => 401, 'msg' => 'Unauthorized'];
}
// 2. 限流
if (!$this->rateLimit($path)) {
return ['code' => 429, 'msg' => 'Too Many Requests'];
}
// 3. 路由到微服务
$service_url = $this->route($path);
// 4. 转发请求
$ch = curl_init("$service_url$path");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3); // 超时3s
if ($body) curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ['code' => $http_code, 'data' => $response];
}
// 简单限流(令牌桶)
private $tokens = [];
function rateLimit($path, $limit = 100) {
$key = md5($path);
$now = time();
if (!isset($this->tokens[$key])) {
$this->tokens[$key] = ['count' => $limit, 'time' => $now];
}
// 每秒恢复10个token
$elapsed = $now - $this->tokens[$key]['time'];
$this->tokens[$key]['count'] = min($limit, $this->tokens[$key]['count'] + $elapsed * 10);
$this->tokens[$key]['time'] = $now;
if ($this->tokens[$key]['count'] >= 1) {
$this->tokens[$key]['count']--;
return true;
}
return false;
}
function authenticate() {
return isset($_SERVER['HTTP_AUTHORIZATION']); // 简化
}
}
// 使用
$gateway = new ApiGateway();
// 请求分发
$result = $gateway->handle('GET', '/user/123');
// -> http://user-service-1/user/123 (轮询)
$result = $gateway->handle('POST', '/order/create', json_encode(['amount' => 100]));
// -> http://order-service-2/order/create
echo "路由: /user/* -> user-service (2节点负载均衡)\n";
echo "限流: 100req/s 令牌桶\n";
echo "认证: JWT/OAuth\n";
大白话: 网关统一入口,负责路由、负载均衡、限流、认证,转发到后端微服务。
输出:
请求流程:
客户端 -> 网关(认证+限流) -> 路由选择 -> 后端服务
/user/123 -> user-service-1 (负载均衡)
/order/1 -> order-service-2 (轮询)
网关功能:
- 路由匹配(fnmatch)
- 负载均衡(轮询/hash)
- 限流(令牌桶 100req/s)
- 认证(JWT)
- 超时控制(3s)
更多推荐
所有评论(0)