以下是基于 Laravel 12 的完整微服务架构实现方案,包含 8 大核心模块 和 生产级部署方案:
项目结构
microservices-arch/
├── api-gateway/ # API 网关服务
├── auth-service/ # 认证服务
├── order-service/ # 订单服务
├── product-service/ # 产品服务
├── notification-service/ # 通知服务
├── docker-compose.yml # Docker 编排
└── infrastructure/ # 基础设施配置
├── prometheus/
├── grafana/
└── elk/
1. API 网关实现 (api-gateway/app/Http/Kernel.php)
// 中间件配置
protected $middlewareGroups = [
'api' => [
\App\Http\Middleware\ServiceDiscovery::class,
\App\Http\Middleware\CircuitBreaker::class,
\App\Http\Middleware\JwtAuth::class,
],
];
// 路由转发控制器
class GatewayController extends Controller
{
public function forward(Request $request)
{
$service = $request->route('service');
$endpoint = $request->route('endpoint');
$response = Http::withHeaders($request->headers->all())
->send($request->method(), "{$service}/{$endpoint}", [
'query' => $request->query(),
'form_params' => $request->post()
]);
return response($response->body(), $response->status());
}
}
2. 服务注册与发现 (auth-service/app/Providers/AppServiceProvider.php)
public function boot()
{
$this->registerWithConsul();
}
private function registerWithConsul()
{
$consulClient = new ConsulClient();
$consulClient->registerService([
'Name' => 'auth-service',
'Address' => env('SERVICE_IP', 'localhost'),
'Port' => env('SERVICE_PORT', 8000),
'Check' => [
'HTTP' => 'http://localhost:8000/health',
'Interval' => '10s'
]
]);
}
3. 熔断机制实现 (api-gateway/app/Http/Middleware/CircuitBreaker.php)
class CircuitBreaker
{
public function handle($request, Closure $next)
{
$service = $request->route('service');
$cacheKey = "circuit:{$service}";
if (Cache::get($cacheKey) === 'open') {
return response()->json(['error' => 'Service unavailable'], 503);
}
try {
$response = $next($request);
$this->recordSuccess($service);
return $response;
} catch (ConnectException $e) {
return $this->handleFailure($service);
}
}
private function handleFailure($service)
{
$failures = Cache::increment("failures:{$service}");
if ($failures >= 5) {
Cache::put("circuit:{$service}", 'open', now()->addMinutes(5));
}
return response()->json(['error' => 'Service unavailable'], 503);
}
}
4. 跨服务通信 (order-service/app/Services/PaymentService.php)
class PaymentService
{
public function chargeOrder(Order $order)
{
$response = Http::withHeaders([
'X-Trace-ID' => request()->header('X-Trace-ID'),
'Authorization' => request()->header('Authorization')
])->post('http://payment-service/charge', [
'amount' => $order->total,
'user_id' => $order->user_id
]);
if ($response->failed()) {
throw new PaymentFailedException();
}
return $response->json();
}
}
5. 分布式事务 Saga 模式 (order-service/app/Jobs/ProcessOrderSaga.php)
class ProcessOrderSaga implements ShouldQueue
{
public function handle()
{
DB::transaction(function () {
// 步骤1: 库存预留
$inventoryReserved = Http::post('inventory-service/reserve', [...]);
// 步骤2: 支付处理
$paymentProcessed = $inventoryReserved && Http::post('payment-service/charge', [...]);
// 步骤3: 订单确认
if ($paymentProcessed) {
$this->confirmOrder();
} else {
// 补偿操作
Http::post('inventory-service/rollback', [...]);
}
});
}
}
6. 统一认证中心 (auth-service/app/Services/JwtService.php)
class JwtService
{
public function generateToken(User $user): string
{
return JWT::encode([
'sub' => $user->id,
'iss' => 'auth-service',
'iat' => time(),
'exp' => time() + 3600,
'roles' => $user->roles->pluck('name')
], env('JWT_SECRET'));
}
public function validateToken(string $token): bool
{
try {
JWT::decode($token, env('JWT_SECRET'), ['HS256']);
return true;
} catch (\Exception $e) {
return false;
}
}
}
7. 分布式追踪 (全局中间件)
class TracingMiddleware
{
public function handle($request, Closure $next)
{
$traceId = $request->header('X-Trace-ID', Str::uuid());
Log::withContext(['trace_id' => $traceId]);
return $next($request)->header('X-Trace-ID', $traceId);
}
}
8. 事件驱动架构 (product-service/app/Events/ProductStockUpdated.php)
class ProductStockUpdated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets;
public $productId;
public $newStock;
public function __construct($productId, $newStock)
{
$this->productId = $productId;
$this->newStock = $newStock;
}
public function broadcastOn()
{
return new Channel('product-updates');
}
}
Docker 部署方案 (docker-compose.yml)
version: '3.8'
services:
# 基础设施
consul:
image: consul:1.15
ports: ["8500:8500"]
rabbitmq:
image: rabbitmq:3-management
ports: ["5672:5672", "15672:15672"]
prometheus:
image: prom/prometheus
volumes: ["./infrastructure/prometheus.yml:/etc/prometheus/prometheus.yml"]
# 微服务
api-gateway:
build: ./api-gateway
ports: ["8000:8000"]
depends_on: [consul]
auth-service:
build: ./auth-service
environment:
CONSUL_HOST: consul
JWT_SECRET: ${JWT_SECRET}
order-service:
build: ./order-service
environment:
DB_HOST: order_db
CONSUL_HOST: consul
生产环境监控方案
-
指标监控:
# prometheus.yml scrape_configs: - job_name: 'laravel_metrics' metrics_path: '/prometheus/metrics' static_configs: - targets: ['api-gateway:8000', 'auth-service:8001']
-
日志收集:
// .env LOG_CHANNEL=elastic // config/logging.php 'elastic' => [ 'driver' => 'custom', 'via' => \App\Logging\ElasticsearchLogger::class, 'host' => env('ELASTIC_HOST'), ]
-
告警规则:
# prometheus/rules.yml groups: - name: service_errors rules: - alert: HighErrorRate expr: sum(rate(laravel_http_requests_total{status=~"5.."}[5m])) / sum(rate(laravel_http_requests_total[5m])) > 0.1 for: 10m
关键优化点
-
性能优化:
- 使用 Swoole 替代 PHP-FPM
- gRPC 替代 HTTP 进行服务通信
- Redis 缓存查询结果
-
安全加固:
// app/Providers/AuthServiceProvider.php Gate::define('update-order', function ($user, Order $order) { return $user->id === $order->user_id; });
-
自动伸缩策略:
# Kubernetes HPA apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler spec: metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70