From cb7e8842d60bd793636be2fbfdcc81e763eccb95 Mon Sep 17 00:00:00 2001 From: ctexthuang Date: Sun, 7 Sep 2025 14:23:44 +0800 Subject: [PATCH] feat : Proxy Remote Fail --- document/proxy.md | 77 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/document/proxy.md b/document/proxy.md index e8577c8..9880ff2 100644 --- a/document/proxy.md +++ b/document/proxy.md @@ -18,3 +18,80 @@ - MyBatis:Mapper接口的代理实现 - RPC框架:远程服务调用的本地代理 - 图片懒加载:先显示缩略图代理,点击再加载原图 + + +```php +//error remote service + uniqid(), 'status' => 'created']; + } +} + +// 远程服务代理 +class RemoteOrderServiceProxy implements OrderService { + private $rpcClient; + + public function __construct() { + $this->rpcClient = ApplicationContext::getContainer() + ->get(\Hyperf\RpcClient\Proxy\AbstractProxyService::class); + } + + public function createOrder(array $data): array { + // 添加额外的元数据 + $data['request_id'] = uniqid(); + $data['timestamp'] = time(); + + // 记录请求日志 + $logger = ApplicationContext::getContainer() + ->get(\Hyperf\Logger\LoggerFactory::class) + ->get('rpc'); + $logger->info('Sending order creation request', $data); + + // 调用远程服务 + try { + $response = $this->rpcClient->__call('OrderService.createOrder', [$data]); + $logger->info('Order created successfully', ['response' => $response]); + return $response; + } catch (\Throwable $e) { + $logger->error('Order creation failed', ['error' => $e->getMessage()]); + throw $e; + } + } +} + +// 配置依赖 +// config/autoload/dependencies.php +return [ + OrderService::class => RemoteOrderServiceProxy::class, // 使用远程代理 + // 或者 + // OrderService::class => LocalOrderService::class, // 使用本地服务 +]; + +// 在控制器中使用 +class OrderController extends AbstractController +{ + /** + * @Inject + * @var OrderService + */ + private $orderService; + + public function create() + { + $data = $this->request->all(); + $result = $this->orderService->createOrder($data); + return $this->response->json($result); + } +} + +``` \ No newline at end of file