发布日期:2024年7月5日
一、系统架构设计
本教程将开发一个电商平台API系统,采用微服务架构:
- 用户服务:JWT认证与权限管理
- 商品服务:Elasticsearch全文检索
- 订单服务:分布式事务处理
- 支付服务:Swoole协程异步处理
- API网关:统一鉴权与限流
技术栈:PHP8.2 + Laravel + Swoole + Elasticsearch + Redis
二、项目初始化与配置
1. 环境准备
# 安装PHP扩展
sudo apt install php8.2 php8.2-fpm php8.2-mysql php8.2-redis
php8.2-curl php8.2-mbstring php8.2-xml php8.2-zip
# 安装Swoole
pecl install swoole
echo "extension=swoole.so" >> /etc/php/8.2/cli/php.ini
# 创建Laravel项目
composer create-project laravel/laravel api-platform
cd api-platform
2. 目录结构规划
app/
├── Core/ # 核心组件
│ ├── Exceptions/ # 自定义异常
│ └── Traits/ # 通用特性
├── Http/ # HTTP逻辑
│ ├── Controllers/ # 控制器
│ ├── Middleware/ # 中间件
│ └── Requests/ # 表单验证
├── Models/ # 数据模型
├── Services/ # 业务服务
│ ├── User/ # 用户服务
│ └── Product/ # 商品服务
├── Tasks/ # 异步任务
└── Utilities/ # 工具类
三、JWT认证实现
1. JWT服务封装
// app/Services/Auth/JwtService.php
use FirebaseJWTJWT;
use FirebaseJWTKey;
class JwtService {
private $secretKey;
private $algorithm = 'HS256';
public function __construct() {
$this->secretKey = env('JWT_SECRET');
}
public function generateToken(array $payload): string {
$payload = array_merge([
'iss' => env('APP_URL'),
'iat' => time(),
'exp' => time() + 3600 // 1小时过期
], $payload);
return JWT::encode($payload, $this->secretKey, $this->algorithm);
}
public function validateToken(string $token): array {
try {
$decoded = JWT::decode($token, new Key($this->secretKey, $this->algorithm));
return (array)$decoded;
} catch (Exception $e) {
throw new InvalidTokenException();
}
}
}
2. 认证中间件
// app/Http/Middleware/JwtAuthenticate.php
class JwtAuthenticate {
public function handle($request, Closure $next) {
$token = $request->bearerToken();
if (!$token) {
throw new UnauthorizedException('Token缺失');
}
try {
$payload = app(JwtService::class)->validateToken($token);
Auth::setUser(User::find($payload['sub']));
} catch (InvalidTokenException $e) {
throw new UnauthorizedException('Token无效');
}
return $next($request);
}
}
四、Swoole协程应用
1. 协程HTTP服务器
// server.php
$http = new SwooleHttpServer("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {
// 启用协程
Corun(function() use ($request, $response) {
try {
$app = require __DIR__.'/bootstrap/app.php';
$kernel = $app->make(IlluminateContractsHttpKernel::class);
// 转换Swoole请求为Laravel请求
$laravelRequest = transformSwooleRequest($request);
// 处理请求
$laravelResponse = $kernel->handle($laravelRequest);
// 发送响应
$response->status($laravelResponse->getStatusCode());
foreach ($laravelResponse->headers->all() as $name => $values) {
$response->header($name, implode(', ', $values));
}
$response->end($laravelResponse->getContent());
$kernel->terminate($laravelRequest, $laravelResponse);
} catch (Throwable $e) {
$response->status(500);
$response->end('Server Error');
}
});
});
$http->start();
2. 并发数据库查询
// app/Services/Product/ProductQueryService.php
public function getProductsWithConcurrency(array $productIds): array {
$results = [];
$coroutines = [];
foreach ($productIds as $id) {
$coroutines[] = go(function() use ($id, &$results) {
$results[$id] = DB::table('products')
->where('id', $id)
->first();
});
}
// 等待所有协程完成
SwooleCoroutinebatch($coroutines);
return $results;
}
五、Elasticsearch集成
1. 商品索引配置
// app/Models/Product.php
public function searchableAs(): string {
return 'products_index';
}
public function toSearchableArray(): array {
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'price' => $this->price,
'categories' => $this->categories->pluck('name')->toArray()
];
}
// 创建索引
Product::makeAllSearchable();
2. 复杂搜索查询
// app/Services/Product/SearchService.php
public function search(string $query, array $filters): LengthAwarePaginator {
$searchParams = [
'index' => 'products_index',
'body' => [
'query' => [
'bool' => [
'must' => [
'multi_match' => [
'query' => $query,
'fields' => ['name^3', 'description', 'categories']
]
],
'filter' => $this->buildFilters($filters)
]
],
'sort' => $this->buildSort($request->input('sort'))
]
];
$results = Product::searchRaw($searchParams);
return new LengthAwarePaginator(
collect($results['hits']['hits']),
$results['hits']['total']['value'],
$request->input('per_page', 15)
);
}
六、分布式事务处理
1. Saga模式实现
// app/Services/Order/CreateOrderSaga.php
class CreateOrderSaga {
public function execute(array $orderData): Order {
DB::beginTransaction();
try {
// 步骤1:创建订单
$order = $this->createOrder($orderData);
// 步骤2:扣减库存
$this->inventoryService->decreaseStock(
$orderData['items']
);
// 步骤3:创建支付记录
$payment = $this->paymentService->create(
$order->id,
$orderData['payment']
);
DB::commit();
return $order;
} catch (Exception $e) {
DB::rollBack();
$this->compensate($order ?? null, $payment ?? null);
throw $e;
}
}
private function compensate(?Order $order, ?Payment $payment) {
// 补偿操作
if ($order) $order->delete();
if ($payment) $payment->delete();
}
}
2. 消息队列处理
// app/Tasks/ProcessPayment.php
class ProcessPayment implements ShouldQueue {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
private Payment $payment
) {}
public function handle(PaymentService $service) {
try {
$service->process($this->payment);
} catch (PaymentFailedException $e) {
$this->release(60); // 1分钟后重试
}
}
public function failed(Throwable $exception) {
$this->payment->update(['status' => 'failed']);
}
}
七、API网关实现
1. 统一鉴权处理
// app/Http/Middleware/GatewayAuth.php
class GatewayAuth {
public function handle($request, Closure $next) {
// 验证签名
$this->validateSignature($request);
// 限流检查
if ($this->rateLimiter->tooManyAttempts()) {
abort(429, '请求过于频繁');
}
// 权限验证
if (!$this->checkPermission($request)) {
abort(403, '无权访问');
}
return $next($request);
}
}
2. 服务发现与负载均衡
// app/Services/Gateway/RouterService.php
class RouterService {
private $services = [
'user' => ['http://user-service1', 'http://user-service2'],
'product' => ['http://product-service1', 'http://product-service2']
];
public function route(string $serviceName): string {
$instances = $this->services[$serviceName] ?? [];
if (empty($instances)) {
throw new ServiceUnavailableException();
}
// 简单轮询负载均衡
static $index = 0;
$instance = $instances[$index % count($instances)];
$index++;
return $instance;
}
}
八、总结与扩展
通过本教程,您已经掌握了:
- JWT认证系统实现
- Swoole协程高性能开发
- Elasticsearch全文检索
- 分布式事务处理方案
- API网关核心设计
扩展学习方向:
- Service Mesh架构集成
- GraphQL API设计
- PHP8.3新特性应用
- Serverless部署方案