如何解決PHP與ConfluentSchemaRegistry的集成問題?使用Composer可以輕松搞定!

可以通過一下地址學習composer學習地址

在開發一個需要與 confluent schema registry 進行集成的 php 項目時,我遇到了一個難題:如何高效地與 schema registry 的 rest api 進行交互。最初,我嘗試直接使用 guzzle 庫進行 http 請求,但發現這種方式不僅繁瑣,而且容易出錯。每次需要處理請求和響應的細節時,都會耗費大量時間和精力。

為了解決這個問題,我決定尋找一個專門處理這類任務的庫。經過一番搜索,我發現了 mateusjunges/confluent-schema-registry-api 這個庫,它專門為 PHP 7.4+ 設計,用于與 Confluent Schema Registry 進行交互。使用 composer 安裝這個庫非常簡單,只需運行以下命令:

composer require "flix-tech/confluent-schema-registry-api=^7.4"

這個庫提供了兩種主要的 API:異步 API 和同步 API。異步 API 通過 PromisingRegistry 類實現,使用 Guzzle 庫的 promise 功能,可以異步地處理請求。以下是一個使用異步 API 的例子:

use GuzzleHttpClient; use FlixTechSchemaRegistryApiRegistryPromisingRegistry; use FlixTechSchemaRegistryApiExceptionSchemaRegistryException;  $registry = new PromisingRegistry(     new Client(['base_uri' => 'registry.example.com']) );  $schema = AvroSchema::parse('{"type": "string"}');  $promise = $registry->register('test-subject', $schema);  $promise = $promise->then(     static function ($schemaidOrSchemaRegistryException) {         if ($schemaIdOrSchemaRegistryException instanceof SchemaRegistryException) {             throw $schemaIdOrSchemaRegistryException;         }          return $schemaIdOrSchemaRegistryException;     } );  $schemaId = $promise->wait();

同步 API 通過 BlockingRegistry 類實現,它會自動解析 Promise,從而簡化了代碼:

use FlixTechSchemaRegistryApiRegistryBlockingRegistry; use FlixTechSchemaRegistryApiRegistryPromisingRegistry; use GuzzleHttpClient;  $registry = new BlockingRegistry(     new PromisingRegistry(         new Client(['base_uri' => 'registry.example.com'])     ) );  $schema = AvroSchema::parse('{"type": "string"}');  $schemaId = $registry->register('test-subject', $schema);

此外,這個庫還支持緩存功能,通過 CachedRegistry 類,可以減少對 Schema Registry 的請求次數,提高性能:

立即學習PHP免費學習筆記(深入)”;

use FlixTechSchemaRegistryApiRegistryBlockingRegistry; use FlixTechSchemaRegistryApiRegistryPromisingRegistry; use FlixTechSchemaRegistryApiRegistryCachedRegistry; use FlixTechSchemaRegistryApiRegistryCacheAvroObjectCacheAdapter; use FlixTechSchemaRegistryApiRegistryCacheDoctrineCacheAdapter; use DoctrineCommonCacheArrayCache; use GuzzleHttpClient;  $asyncApi = new PromisingRegistry(     new Client(['base_uri' => 'registry.example.com']) );  $syncApi = new BlockingRegistry($asyncApi);  $doctrineCachedSyncApi = new CachedRegistry(     $asyncApi,     new DoctrineCacheAdapter(         new ArrayCache()     ) );  $avroObjectCachedAsyncApi = new CachedRegistry(     $syncApi,     new AvroObjectCacheAdapter() );

使用 mateusjunges/confluent-schema-registry-api 庫后,我的項目開發效率大大提升,不再需要手動處理繁瑣的 HTTP 請求和響應細節。這個庫不僅簡化了與 Schema Registry 的交互,還提供了異步和同步兩種處理方式,以及緩存功能,極大地優化了項目的性能和可維護性。如果你也面臨類似的需求,不妨嘗試使用這個庫,它將會是你的得力助手。

? 版權聲明
THE END
喜歡就支持一下吧
點贊14 分享