在开发一个需要与 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 的交互,还提供了异步和同步两种处理方式,以及缓存功能,极大地优化了项目的性能和可维护性。如果你也面临类似的需求,不妨尝试使用这个库,它将会是你的得力助手。