feat : Proxy Remote Fail
This commit is contained in:
@@ -18,3 +18,80 @@
|
|||||||
- MyBatis:Mapper接口的代理实现
|
- MyBatis:Mapper接口的代理实现
|
||||||
- RPC框架:远程服务调用的本地代理
|
- RPC框架:远程服务调用的本地代理
|
||||||
- 图片懒加载:先显示缩略图代理,点击再加载原图
|
- 图片懒加载:先显示缩略图代理,点击再加载原图
|
||||||
|
|
||||||
|
|
||||||
|
```php
|
||||||
|
//error remote service
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// 订单服务接口
|
||||||
|
interface OrderService {
|
||||||
|
public function createOrder(array $data): array;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 本地服务实现
|
||||||
|
class LocalOrderService implements OrderService {
|
||||||
|
public function createOrder(array $data): array {
|
||||||
|
// 本地创建订单逻辑
|
||||||
|
return ['order_id' => 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user