基础适配器Adapter的使用方法详解

  • 系统对接顾问

基础适配器Adapter的使用方法

我们在所有适配器中都需要引入基础适配器Adapter,并使用其提供的继承方法。命名空间是:useDomain\Datahub\Instance\Adapter\Adapter;

日志记录方法

要记录日志,可以使用 $this->getLogStorage()->insertOne([$content],$status); 其中 $content 是日志内容(数组形式),$status 是日志错误类型。如果 $status 为错误,需要引入命名空间 LogStatus,调用方法为 $this->getLogStorage()->insertOne([$content], LogStatus::RECORD);

获取数据方法

写入调度者时,需要从数据管理中获取一条数据,并根据配置的 metaData 中的 operation 参数。代码如下:

$operation = null;
if (isset($this->metaData['operation'])) {
    $operation = $this->metaData['operation'];
}
$data = $this->getDataStorage()->fetch($operation);

其中, $this->metaData 保存了请求调度者和写入调度者的配置参数,包括对应的 $api 接口地址。

生成参数方法

此方法主要用于将请求调度者和写入调度者的配置参数转换为接口所需的参数。可以直接调用父类(Adapter)的 generateRequestParams 方法。代码如下:

$request = $this->generateRequestParams();
$request = $this->generateRequestParams($data);

实际过程中,我们可以使用以下代码:

try {
    $request = $this->generateRequestParams($data);
} catch (\Throwable $th) {
    $this->getLogStorage()->insertOne(['text' => LogMessage::DISPATCH_SOURCE_FAIL, 'response' => $th->getMessage(), 'data' => $data], LogStatus::ERROR);
    $this->getDataStorage()->setFetchStatus(DataStatus::CONTINUE);
    return $this->dispatch();
}

插入源平台请求队列方法

用上一步得到的 $request, 向请求队列中插入任务数据,并获取任务ID。代码如下:

$jobId = $this->getAsynSourceJobStorage()->insertOne($this->metaData['api'], $request);

源平台排队方法

调用父类的 asynSourceJob 方法, $time 表示多少秒后执行队列任务(0表示立即执行), $jobId 表示任务ID。代码如下:

$this->asynSourceJob($time, $jobId);

目标平台写入队列方法

调用 Adapter 父类的 asynTargetJob 方法, $this->metaData['api'] 表示方案设置的接口地址, $request 表示请求参数, $this->getDataStorage()->ids 表示数据ID, $this->getDataStorage()->dataRange() 表示数据范围。代码如下:

$jobId = $this->getAsynTargetJobStorage()->insertOne($this->_metaData['api'], _request, _ids, _range);

更新数据状态

调用 getDataStorage() 中的 setFetchStatus() 方法,标记数剧状态为队列中。 `$jobId_表示任务ID。代码如xia:

$this->$getDataStoage()->setFetchStatu(DataStatus::QUEUE,null,null,new\MongoDB\BSON\ObjectId($jobId));

目标平台排队方法

调用父类的 asynTargetJob() 方法, _time_表示多少秒后执行队列任务(0表示立即执行),_jobId_表示任务ID。代码如下:

$this->$asynTargetJob(round(_times), _id_);

数据存储写入数据方法

在查询适配器中,如果得到正确结果集,则调用 getDataStoage() 中 的 insertOne() 方法,将数剧写入数剧管理系统里去. `_id为主键字段, _number为业务编码字段, _response表示接口返回结果集, job_id_代表任务ID. 代ma如下:

$this->$geetDatastorage()->inserone(_id_,_num_,_respon_, false,_jid_);

重试操作

处理响应时,如guo响应结果不正确,则调用父类de reQueue() fang法进行重试. dai ma:

$this->$reQueue(); 

异常错误处理

在适配器定义了一个 handleError() fang法用于处理异常. dai ma 如下:


 public function handleError( response,$jid=null){
   throw=new HuidinhuoThrowable(this);throw->handle(jid,response); this-> get Asyn Source Job Storage()->updateResponse(jid, Data Status:ERROR,response,0,this->active); this-> get Log Storage()-> insert One(['text'=> Log Messa