创建一个通用类,该类可以将作业排队等待将数据推送到外部API

时间:2019-02-15 03:31:45

标签: php laravel lumen

我从一开始就开发Laravel项目,并且我想创建一个通用类,该类可以将作业排队,以便将数据推送到外部API。我怎样才能做到这一点?我是队列和工作的新手。

以下代码是我尝试的。我创建了以下Job类,并在需要将数据推送到外部API的地方调用了它。这对我有用。但是我愿意接受其他解决方案。

    class ApiPushService implements ShouldQueue
{

    use InteractsWithQueue, SerializesModels, Queueable;

    protected $endpoint;
    protected $data;

    /**
     * ApiPushService constructor.
     * @param $endpoint
     * @param $data
     */
    public function __construct($endpoint, $data)
    {
        $this->endpoint = $endpoint;
        $this->data = $data;
    }


    /**
     * @param Client $guzzleClient
     */
    public function handle(Client $guzzleClient)
    {
        //get external api url
        $url = $this->endpoint;

        try {
            $response = $guzzleClient->request('POST', $url, [
                'headers' => array("Content-Type" => "application/json"),
                'json' => $this->data
            ]);
        } catch (BadResponseException $e) {
            Log::error("ApiPushService (handle): Guzzle Bad Response Exception : " . $e->getMessage());
        } catch (RequestException $e) {
            Log::error("ApiPushService (handle): Guzzle Request Exception : " . $e->getMessage());
        } catch (GuzzleException $e) {
            Log::error("ApiPushService (handle): Guzzle  Exception : " . $e->getMessage());
        }

        if ($response->getStatusCode() != 200) {
            Log::info("ApiPushService (handle): Endpoint Response : ",
                json_decode((string)$response->getBody(), true));
        } else {
            Log::error("ApiPushService (handle): Guzzle Request error : ",
                json_decode((string)$response->getBody(), true));
        }
    }


}

0 个答案:

没有答案