在开发一个需要与 confluent schema registry 进行集成的 php 项目时,我遇到了一个难题:如何高效地与 schema registry 的 rest api 进行交互。最初,我尝试直接使用 guzzle 库进行 http 请求,但发现这种方式不仅繁琐,而且容易出错。每次需要处理请求和响应的细节时,都会耗费大量时间和精力。
为了解决这个问题,我决定寻找一个专门处理这类任务的库。经过一番搜索,我发现了 mateusjunges/confluent-schema-registry-api 这个库,它专门为 PHP 7.4+ 设计,用于与 Confluent Schema Registry 进行交互。使用 Composer 安装这个库非常简单,只需运行以下命令:
<code>composer require "flix-tech/confluent-schema-registry-api=^7.4"</code>
这个库提供了两种主要的 API:异步 API 和同步 API。异步 API 通过 PromisingRegistry 类实现,使用 Guzzle 库的 Promise 功能,可以异步地处理请求。以下是一个使用异步 API 的例子:
<code class="php">use GuzzleHttp\Client;
use FlixTech\SchemaRegistryApi\Registry\PromisingRegistry;
use FlixTech\SchemaRegistryApi\Exception\SchemaRegistryException;
$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();</code>同步 API 通过 BlockingRegistry 类实现,它会自动解析 Promise,从而简化了代码:
<code class="php">use FlixTech\SchemaRegistryApi\Registry\BlockingRegistry;
use FlixTech\SchemaRegistryApi\Registry\PromisingRegistry;
use GuzzleHttp\Client;
$registry = new BlockingRegistry(
new PromisingRegistry(
new Client(['base_uri' => 'registry.example.com'])
)
);
$schema = AvroSchema::parse('{"type": "string"}');
$schemaId = $registry->register('test-subject', $schema);</code>此外,这个库还支持缓存功能,通过 CachedRegistry 类,可以减少对 Schema Registry 的请求次数,提高性能:
立即学习“PHP免费学习笔记(深入)”;
<code class="php">use FlixTech\SchemaRegistryApi\Registry\BlockingRegistry;
use FlixTech\SchemaRegistryApi\Registry\PromisingRegistry;
use FlixTech\SchemaRegistryApi\Registry\CachedRegistry;
use FlixTech\SchemaRegistryApi\Registry\Cache\AvroObjectCacheAdapter;
use FlixTech\SchemaRegistryApi\Registry\Cache\DoctrineCacheAdapter;
use Doctrine\Common\Cache\ArrayCache;
use GuzzleHttp\Client;
$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()
);</code>使用 mateusjunges/confluent-schema-registry-api 库后,我的项目开发效率大大提升,不再需要手动处理繁琐的 HTTP 请求和响应细节。这个库不仅简化了与 Schema Registry 的交互,还提供了异步和同步两种处理方式,以及缓存功能,极大地优化了项目的性能和可维护性。如果你也面临类似的需求,不妨尝试使用这个库,它将会是你的得力助手。
以上就是如何解决PHP与ConfluentSchemaRegistry的集成问题?使用Composer可以轻松搞定!的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号