文章目录[隐藏]
WordPress柔性供应链软件开发中的微服务架构教程
引言:为什么柔性供应链需要微服务架构
在当今快速变化的商业环境中,柔性供应链系统已成为企业保持竞争力的关键。传统的单体式WordPress插件在处理复杂供应链逻辑时往往面临扩展性差、维护困难等问题。微服务架构通过将系统拆分为独立部署的小型服务,为WordPress柔性供应链软件提供了理想的解决方案。
本文将详细介绍如何在WordPress环境中实现柔性供应链的微服务架构,包含完整的代码示例和最佳实践。
微服务架构核心概念
服务拆分原则
在供应链系统中,我们可以按业务领域拆分为以下微服务:
- 库存管理服务
- 订单处理服务
- 物流跟踪服务
- 供应商管理服务
- 需求预测服务
通信机制选择
微服务之间通常采用REST API或消息队列进行通信。对于实时性要求高的操作,建议使用REST;对于异步处理,消息队列是更好的选择。
环境搭建与基础配置
Docker容器化部署
<?php
/**
* Docker Compose配置文件示例
* 用于部署WordPress和微服务集群
*/
// docker-compose.yml
$dockerCompose = <<<YAML
version: '3.8'
services:
# WordPress核心容器
wordpress:
image: wordpress:latest
ports:
- "8080:80"
environment:
WORDPRESS_DB_HOST: mysql
WORDPRESS_DB_USER: wp_user
WORDPRESS_DB_PASSWORD: wp_password
volumes:
- ./wp-content:/var/www/html/wp-content
# MySQL数据库
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: wordpress
MYSQL_USER: wp_user
MYSQL_PASSWORD: wp_password
# 库存微服务
inventory-service:
build: ./services/inventory
ports:
- "3001:3000"
environment:
DB_HOST: inventory-db
REDIS_HOST: redis
# 订单微服务
order-service:
build: ./services/order
ports:
- "3002:3000"
# API网关
api-gateway:
build: ./gateway
ports:
- "3000:3000"
YAML;
file_put_contents('docker-compose.yml', $dockerCompose);
echo "Docker Compose配置文件已生成";
?>
库存管理微服务实现
REST API端点设计
<?php
/**
* 库存管理微服务API示例
* 使用Slim PHP微框架
*/
require __DIR__ . '/vendor/autoload.php';
use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use SlimFactoryAppFactory;
use DIContainer;
// 创建应用实例
$app = AppFactory::create();
// 添加中间件
$app->addBodyParsingMiddleware();
/**
* 获取库存信息
* GET /api/inventory/{product_id}
*/
$app->get('/api/inventory/{product_id}', function (Request $request, Response $response, $args) {
$productId = $args['product_id'];
// 模拟数据库查询
$inventoryData = [
'product_id' => $productId,
'quantity' => 150,
'location' => 'WH-01',
'last_updated' => date('Y-m-d H:i:s'),
'reserved' => 25
];
// 计算可用库存
$inventoryData['available'] = $inventoryData['quantity'] - $inventoryData['reserved'];
$response->getBody()->write(json_encode([
'success' => true,
'data' => $inventoryData
]));
return $response
->withHeader('Content-Type', 'application/json')
->withStatus(200);
});
/**
* 更新库存
* PUT /api/inventory/{product_id}
*/
$app->put('/api/inventory/{product_id}', function (Request $request, Response $response, $args) {
$productId = $args['product_id'];
$data = $request->getParsedBody();
// 验证输入数据
if (!isset($data['quantity']) || !is_numeric($data['quantity'])) {
$response->getBody()->write(json_encode([
'success' => false,
'error' => '无效的数量值'
]));
return $response->withStatus(400);
}
// 模拟库存更新逻辑
$updateResult = [
'product_id' => $productId,
'new_quantity' => $data['quantity'],
'previous_quantity' => 150,
'updated_at' => date('Y-m-d H:i:s'),
'operation' => $data['operation'] ?? 'manual_adjustment'
];
// 发布库存变更事件(用于其他微服务)
$this->get('eventBus')->publish('inventory.updated', $updateResult);
$response->getBody()->write(json_encode([
'success' => true,
'message' => '库存更新成功',
'data' => $updateResult
]));
return $response
->withHeader('Content-Type', 'application/json')
->withStatus(200);
});
/**
* 批量查询库存
* POST /api/inventory/batch
*/
$app->post('/api/inventory/batch', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$productIds = $data['product_ids'] ?? [];
if (empty($productIds)) {
$response->getBody()->write(json_encode([
'success' => false,
'error' => '未提供产品ID列表'
]));
return $response->withStatus(400);
}
// 模拟批量查询
$results = [];
foreach ($productIds as $productId) {
$results[] = [
'product_id' => $productId,
'quantity' => rand(50, 500),
'available' => rand(30, 450)
];
}
$response->getBody()->write(json_encode([
'success' => true,
'data' => $results,
'count' => count($results)
]));
return $response
->withHeader('Content-Type', 'application/json')
->withStatus(200);
});
// 运行应用
$app->run();
?>
WordPress与微服务集成
自定义REST API端点
<?php
/**
* WordPress插件:微服务集成
* 提供WordPress与供应链微服务的桥梁
*/
class SupplyChain_Microservice_Integration {
private $service_endpoints;
public function __construct() {
$this->service_endpoints = [
'inventory' => 'http://inventory-service:3000/api',
'order' => 'http://order-service:3000/api',
'logistics' => 'http://logistics-service:3000/api'
];
add_action('rest_api_init', [$this, 'register_rest_routes']);
add_action('admin_menu', [$this, 'add_admin_menu']);
}
/**
* 注册WordPress REST API路由
*/
public function register_rest_routes() {
// 获取产品库存
register_rest_route('supply-chain/v1', '/inventory/(?P<id>d+)', [
'methods' => 'GET',
'callback' => [$this, 'get_product_inventory'],
'permission_callback' => [$this, 'check_api_permission']
]);
// 同步订单到微服务
register_rest_route('supply-chain/v1', '/orders/sync', [
'methods' => 'POST',
'callback' => [$this, 'sync_order_to_microservice'],
'permission_callback' => [$this, 'check_api_permission']
]);
// 批量更新库存
register_rest_route('supply-chain/v1', '/inventory/batch-update', [
'methods' => 'PUT',
'callback' => [$this, 'batch_update_inventory'],
'permission_callback' => [$this, 'check_api_permission']
]);
}
/**
* 获取产品库存信息
*/
public function get_product_inventory($request) {
$product_id = $request->get_param('id');
// 调用库存微服务
$response = wp_remote_get(
$this->service_endpoints['inventory'] . '/inventory/' . $product_id,
[
'timeout' => 15,
'headers' => [
'Content-Type' => 'application/json',
'X-API-Key' => $this->get_api_key()
]
]
);
if (is_wp_error($response)) {
return new WP_Error('service_unavailable', '库存服务暂时不可用', ['status' => 503]);
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
return rest_ensure_response($data);
}
/**
* 同步订单到订单微服务
*/
public function sync_order_to_microservice($request) {
$order_data = $request->get_json_params();
// 验证订单数据
if (!$this->validate_order_data($order_data)) {
return new WP_Error('invalid_data', '订单数据格式错误', ['status' => 400]);
}
// 调用订单微服务
$response = wp_remote_post(
$this->service_endpoints['order'] . '/orders',
[
'method' => 'POST',
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/json',
'X-API-Key' => $this->get_api_key()
],
'body' => json_encode($order_data)
]
);
if (is_wp_error($response)) {
// 失败时进入重试队列
$this->queue_for_retry('order_sync', $order_data);
return new WP_Error('sync_failed', '订单同步失败,已加入重试队列', ['status' => 500]);
}
$body = wp_remote_retrieve_body($response);
$result = json_decode($body, true);
// 更新本地订单状态
if ($result['success'] && isset($order_data['wordpress_order_id'])) {
$this->update_local_order_status($order_data['wordpress_order_id'], 'synced');
}
return rest_ensure_response($result);
}
/**
* 批量更新库存
*/
public function batch_update_inventory($request) {
$updates = $request->get_json_params();
// 调用库存微服务的批量接口
$response = wp_remote_post(
$this->service_endpoints['inventory'] . '/inventory/batch-update',
[
'method' => 'POST',
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/json',
'X-API-Key' => $this->get_api_key()
],
'body' => json_encode(['updates' => $updates])
]
);
if (is_wp_error($response)) {
return new WP_Error('update_failed', '批量更新失败', ['status' => 500]);
}
$body = wp_remote_retrieve_body($response);
$result = json_decode($body, true);
return rest_ensure_response($result);
}
/**
* 验证API权限
*/
public function check_api_permission($request) {
// 实际应用中应实现更复杂的权限验证
return current_user_can('manage_options') ||
$this->validate_api_key($request->get_header('X-API-Key'));
}
/**
* 验证API密钥
*/
private function validate_api_key($api_key) {
$stored_key = get_option('supply_chain_api_key');
return hash_equals($stored_key, $api_key);
}
/**
* 获取API密钥
*/
private function get_api_key() {
return get_option('supply_chain_api_key', '');
}
/**
* 验证订单数据
*/
private function validate_order_data($order_data) {
$required_fields = ['order_id', 'customer_id', 'items', 'total_amount'];
foreach ($required_fields as $field) {
if (!isset($order_data[$field])) {
return false;
}
}
return true;
}
/**
* 添加到重试队列
*/
private function queue_for_retry($action, $data) {
$queue = get_option('supply_chain_retry_queue', []);
$queue[] = [
'action' => $action,
'data' => $data,
'attempts' => 0,
'scheduled_for' => time() + 300 // 5分钟后重试
];
update_option('supply_chain_retry_queue', $queue);
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_menu_page(
'供应链管理',
'供应链',
'manage_options',
'supply-chain',
[$this, 'render_admin_page'],
'dashicons-networking',
30
);
}
/**
* 渲染管理页面
*/
public function render_admin_page() {
?>
<div class="wrap">
<h1>柔性供应链微服务管理</h1>
<div class="card">
<h2>服务状态</h2>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>服务名称</th>
<th>状态</th>
<th>响应时间</th>
<th>最后检查</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->check_service_health() as $service): ?>
<tr>
<td><?php echo esc_html($service['name']); ?></td>
<td>
<span class="dashicons dashicons-<?php echo $service['status'] ? 'yes' : 'no'; ?>"></span>
<?php echo $service['status'] ? '正常' : '异常'; ?>
</td>
<td><?php echo esc_html($service['response_time']); ?>ms</td>
<td><?php echo esc_html($service['last_check']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<?php
}
/**
* 检查服务健康状态
*/
private function check_service_health() {
$services = [];
foreach ($this->service_endpoints as $name => $endpoint) {
$start_time = microtime(true);
$response = wp_remote_get($endpoint . '/health', ['timeout' => 5]);
$response_time = round((microtime(true) - $start_time) * 1000, 2);
$services[] = [
'name' => ucfirst($name) . ' Service',
'status' => !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200,
'response_time' => $response_time,
'last_check' => current_time('mysql')
];
}
return $services;
}
}
// 初始化插件
new SupplyChain_Microservice_Integration();
?>
消息队列与事件驱动架构
RabbitMQ集成示例
<?php
/**
* 事件驱动架构实现
* 使用RabbitMQ进行服务间通信
*/
class EventDrivenArchitecture {
private $connection;
private $channel;
public function __construct() {
$this->init_message_queue();
}
/**
* 初始化消息队列连接
*/
private function init_message_queue() {
try {
// 创建RabbitMQ连接
$this->connection = new AMQPConnection([
'host' => getenv('RABBITMQ_HOST') ?: 'rabbitmq',
'port' => getenv('RABBITMQ_PORT') ?: 5672,
'login' => getenv('RABBITMQ_USER') ?: 'guest',
'password' => getenv('RABBITMQ_PASS') ?: 'guest'
]);
$this->connection->connect();
$this->channel = new AMQPChannel($this->connection);
// 声明交换机
$this->declare_exchanges();
} catch (Exception $e) {
error_log('消息队列连接失败: ' . $e->getMessage());
}
}
/**
* 声明交换机
*/
private function declare_exchanges() {
$exchanges = [
'inventory.events' => AMQP_EX_TYPE_DIRECT,
'order.events' => AMQP_EX_TYPE_DIRECT,
'supply_chain.broadcast' => AMQP_EX_TYPE_FANOUT
];
foreach ($exchanges as $name => $type) {
$exchange = new AMQPExchange($this->channel);
$exchange->setName($name);
$exchange->setType($type);
$exchange->declare();
}
}
/**
* 发布事件
*/
public function publish_event($exchange, $routing_key, $event_data) {
try {
$exchange_obj = new AMQPExchange($this->channel);
$exchange_obj->setName($exchange);
$message = json_encode([
'event_id' => uniqid('event_', true),
'event_type' => $routing_key,
'timestamp' => time(),
'data' => $event_data,
'source' => 'wordpress_supply_chain'
]);
$exchange_obj->publish(
$message,
$routing_key,
AMQP_NOPARAM,
[
'content_type' => 'application/json',
'delivery_mode' => AMQP_DURABLE
]
);
error_log("事件发布成功: {$exchange}/{$routing_key}");
return true;
} catch (Exception $e) {
error_log("事件发布失败: " . $e->getMessage());
return false;
}
}
/**
* 订阅事件
*/
public function subscribe_to_events($queue_name, $exchange, $routing_keys, $callback) {
try {
// 创建队列
$queue = new AMQPQueue($this->channel);
$queue->setName($queue_name);
$queue->setFlags(AMQP_DURABLE);
$queue->declare();
// 绑定路由键
if (is_array($routing_keys)) {
foreach ($routing_keys as $routing_key) {
$queue->bind($exchange, $routing_key);
}
} else {
$queue->bind($exchange, $routing_keys);
}
// 开始消费消息
$queue->consume(function($envelope, $queue) use ($callback) {
$message = json_decode($envelope->getBody(), true);
try {
// 执行回调处理
$result = call_user_func($callback, $message);
if ($result) {
$queue->ack($envelope->getDeliveryTag());
error_log("事件处理成功: " . $message['event_type']);
} else {
$queue->nack($envelope->getDeliveryTag());
error_log("事件处理失败,已拒绝: " . $message['event_type']);
}
} catch (Exception $e) {
$queue->nack($envelope->getDeliveryTag());
error_log("事件处理异常: " . $e->getMessage());
}
});
} catch (Exception $e) {
error_log("事件订阅失败: " . $e->getMessage());
}
}
/**
* 库存变更事件处理器
*/
public function handle_inventory_event($message) {
$event_type = $message['event_type'];
$data = $message['data'];
switch ($event_type) {
case 'inventory.updated':
// 更新本地缓存
$this->update_inventory_cache($data['product_id'], $data['new_quantity']);
// 触发相关操作
if ($data['new_quantity'] < $data['low_stock_threshold']) {
$this->trigger_low_stock_alert($data);
}
break;
case 'inventory.reserved':
// 处理库存预留
$this->update_reserved_inventory($data);
break;
case 'inventory.released':
// 处理库存释放
$this->release_inventory($data);
break;
}
return true;
}
/**
* 更新库存缓存
*/
private function update_inventory_cache($product_id, $quantity) {
$cache_key = "inventory_{$product_id}";
wp_cache_set($cache_key, $quantity, 'supply_chain', 3600);
}
}
// 初始化事件驱动架构
$event_system = new EventDrivenArchitecture();
?>
## 数据库设计与数据一致性
### 多服务数据同步策略
<?php
/**
- 分布式事务管理
- 使用Saga模式处理跨服务事务
*/
class DistributedTransactionManager {
/**
* 创建订单Saga事务
*/
public function createOrderSaga($order_data) {
$saga_id = uniqid('saga_', true);
$steps = [
'reserve_inventory' => [
'service' => 'inventory',
'endpoint' => '/api/inventory/reserve',
'compensation' => '/api/inventory/release'
],
'create_order' => [
'service' => 'order',
'endpoint' => '/api/orders',
'compensation' => '/api/orders/cancel'
],
'notify_customer' => [
'service' => 'notification',
'endpoint' => '/api/notifications/order-confirmation'
]
];
// 执行Saga步骤
$this->executeSagaSteps($saga_id, $steps, $order_data);
return $saga_id;
}
/**
* 执行Saga步骤
*/
private function executeSagaSteps($saga_id, $steps, $data) {
$completed_steps = [];
foreach ($steps as $step_name => $step_config) {
try {
// 执行步骤
$result = $this->callMicroservice(
$step_config['service'],
$step_config['endpoint'],
array_merge($data, ['saga_id' => $saga_id])
);
if (!$result['success']) {
// 执行失败,开始补偿
$this->compensateSteps(array_reverse($completed_steps), $data);
throw new Exception("Saga步骤失败: {$step_name}");
}
$completed_steps[] = [
'name' => $step_name,
'config' => $step_config,
'result' => $result
];
// 记录步骤完成
$this->logSagaStep($saga_id, $step_name, 'completed');
} catch (Exception $e) {
$this->logSagaStep($saga_id, $step_name, 'failed', $e->getMessage());
throw $e;
}
}
// 所有步骤完成
$this->logSagaStep($saga_id, 'all', 'completed');
}
/**
* 补偿已完成的步骤
*/
private function compensateSteps($steps, $data) {
foreach ($steps as $step) {
if (isset($step['config']['compensation'])) {
try {
$this->callMicroservice(
$step['config']['service'],
$step['config']['compensation'],
$data
);
} catch (Exception $e) {
error_log("补偿步骤失败: " . $e->getMessage());
}
}
}
}
/**
* 调用微服务
*/
private function callMicroservice($service, $endpoint, $data) {
$service_url = $this->getServiceUrl($service) . $endpoint;
$response = wp_remote_post($service_url, [
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/json',
'X-Saga-ID' => $data['saga_id']
],
'body' => json_encode($data)
]);
if (is_wp_error($response)) {
throw new Exception("服务调用失败: " . $response->get_error_message());
}
return json_decode(wp_remote_retrieve_body($response), true);
}
/**
* 记录Saga步骤
*/
private function logSagaStep($saga_id, $step, $status, $error = null) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'supply_chain_saga_logs',
[
'saga_id' => $saga_id,
'step' => $step,
'status' => $status,
'error_message' => $error,
'created_at' => current_time('mysql')
]
);
}
}
/**
- 数据同步服务
- 保持WordPress与微服务数据一致性
*/
class DataSynchronizationService {
/**
* 双向同步产品数据
*/
public function syncProductData($product_id, $direction = 'both') {
$local_data = $this->getLocalProductData($product_id);
$remote_data = $this->getRemoteProductData($product_id);
if ($direction === 'both' || $direction === 'local_to_remote') {
// 本地到远程同步
$this->syncToRemote($product_id, $local_data);
}
if ($direction === 'both' || $direction === 'remote_to_local') {
// 远程到本地同步
$this->syncToLocal($product_id, $remote_data);
}
}
/**
* 获取本地产品数据
*/
private function getLocalProductData($product_id) {
$product = wc_get_product($product_id);
if (!$product) {
return null;
}
return [
'id' => $product_id,
'sku' => $product->get_sku(),
'name' => $product->get_name(),
'price' => $product->get_price(),
'stock_quantity' => $product->get_stock_quantity(),
'manage_stock' => $product->get_manage_stock(),
'last_updated' => $product->get_date_modified()->format('Y-m-d H:i:s')
];
}
/**
* 获取远程产品数据
*/
private function getRemoteProductData($product_id) {
$response = wp_remote_get(
"http://inventory-service:3000/api/products/{$product_id}",
['timeout' => 10]
);
if (is_wp_error($response)) {
return null;
}
return json_decode(wp_remote_retrieve_body($response), true);
}
/**
* 同步到远程服务
*/
private function syncToRemote($product_id, $data) {
if (empty($data)) {
return;
}
wp_remote_post(
'http://inventory-service:3000/api/products/sync',
[
'method' => 'POST',
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data)
]
);
}
/**
* 同步到本地
*/
private function syncToLocal($product_id, $data) {
if (empty($data)) {
return;
}
$product = wc_get_product($product_id);
if ($product && isset($data['stock_quantity'])) {
// 更新库存数量
wc_update_product_stock($product_id, $data['stock_quantity']);
// 更新最后同步时间
update_post_meta($product_id, '_last_sync_time', current_time('mysql'));
}
}
/**
* 批量同步
*/
public function batchSync($product_ids) {
$results = [];
foreach ($product_ids as $product_id) {
try {
$this->syncProductData($product_id, 'both');
$results[$product_id] = 'success';
} catch (Exception $e) {
$results[$product_id] = 'failed: ' . $e->getMessage();
}
}
return $results;
}
}
?>
## 监控与日志系统
### 分布式追踪实现
<?php
/**
- 分布式追踪系统
- 用于监控微服务调用链
*/
class DistributedTracing {
private static $instance;
private $current_trace_id;
private $current_span_id;
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 开始新的追踪
*/
public function startTrace($name) {
$this->current_trace_id = $this->generateTraceId();
$this->current_span_id = $this->generateSpanId();
$this->logSpan([
'trace_id' => $this->current_trace_id,
'span_id' => $this->current_span_id,
'parent_span_id' => null,
'name' => $name,
'start_time' => microtime(true),
'service' => 'wordpress',
'type' => 'entry'
]);
return [
'trace_id' => $this->current_trace_id,
'span_id' => $this->current_span_id
];
}
/**
* 创建子跨度
*/
public function createChildSpan($name, $service = null) {
$parent_span_id = $this->current_span_id;
$this->current_span_id = $this->generateSpanId();
$span_data = [
'trace_id' => $this->current_trace_id,
'span_id' => $this->current_span_id,
'parent_span_id' => $parent_span_id,
'name' => $name,
'start_time' => microtime(true),
'service' => $service ?: 'wordpress',
'type' => 'internal'
];
$this->logSpan($span_data);
return $this->current_span_id;
}
/**
* 结束当前跨度
*/
public function endCurrentSpan($tags = []) {
$this->logSpanEnd($this->current_span_id, $tags);
}
/**
* 记录微服务调用
*/
public function logServiceCall($service, $endpoint, $duration, $status) {
$span_id = $this->createChildSpan("call:{$service}:{$endpoint}", $service);
$this->logSpanEnd($span_id, [
'service' => $service,
'endpoint' => $endpoint,
'duration_ms' => $duration * 1000,
'status' => $status,
'http_method' => 'POST'
]);
}
/**
* 生成追踪ID
*/
private function generateTraceId() {
return bin2hex(random_bytes(16));
}
/**
* 生成跨度ID
*/
private function generateSpanId() {
return bin2hex(random_bytes(8));
}
/**
* 记录跨度开始
*/
private function logSpan($span_data) {
// 发送到追踪系统(如Jaeger)
$this->sendToCollector('span_start', $span_data);
// 本地日志
error_log(json_encode([
'type' => 'trace_span_start',
'data' => $span_data,
'timestamp' => date('Y-m-d H:i:s')
]));
}
/**
* 记录跨度结束
*/
private function logSpanEnd($span_id, $tags) {
$span_data = [
'span_id' => $span_id,
'end_time' => microtime(true),
'tags' => $tags
];
$this->sendToCollector('span_end', $span_data);
}
/**
* 发送到收集器
*/
private function sendToCollector($type, $data) {
// 实际实现中应该发送到Jaeger或Zipkin
$collector_url = getenv('TRACING_COLLECTOR_URL') ?: 'http://jaeger:14268/api/traces';
wp_remote_post($collector_url, [
'timeout' => 2,
'blocking' => false,
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode([
'type' => $type,
'data' => $data,
'timestamp' => time()
])
]);
}
/**
* 获取追踪头信息
*/
public function getTraceHeaders() {
return [
'X-Trace-ID' => $this->current_trace_id,
'X-Span-ID' => $this->current_span_id,
'X-Parent-Span-ID' => $this->getParentSpanId()
];
}
}
/**
- 性能监控
*/
class PerformanceMonitor {
/**
* 监控API响应时间
*/
public static function monitorApiCall($endpoint, $callback) {
$start_time = microtime(true);
try {
$result = call_user_func($callback);
$duration = microtime(true) - $start_time;
// 记录成功调用
self::logApiMetrics($endpoint, $duration, true);
return $result;
} catch (Exception $e) {
$duration = microtime(true) - $start_time;
// 记录失败调用
self::logApiMetrics($endpoint, $duration, false, $e->getMessage());
throw $e;
}
}
/**
* 记录API指标
*/
private static function logApiMetrics($endpoint, $duration, $success, $error = null) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'supply_chain_metrics',
[
'endpoint' => $endpoint,
'duration' => $duration,
'success' => $success ? 1 : 0,
'error_message' => $error,
'timestamp' => current_time('mysql'),
'memory_usage' => memory_get_usage(true)
]
);
// 发送到监控系统
if ($duration > 1.0) { // 超过1秒的调用
self::alertSlowCall($endpoint, $duration);
}
}
/**
* 慢调用告警
*/
private static function alertSlowCall($endpoint, $duration) {
// 发送到监控系统(如Prometheus + Alertmanager)
error_log("慢调用告警: {$endpoint} 耗时 {$duration}秒");
}
/**
* 生成性能报告
*/
public static function generatePerformanceReport($start_date, $end_date) {
global $wpdb;
$table_name = $wpdb->prefix . 'supply_chain_metrics';
$results = $wpdb->get_results($wpdb->prepare(
"SELECT
endpoint,
COUNT(*) as total_calls,
AVG
