phpkafka
repository·master·Indexed 43 days ago
https://github.com/swoole/phpkafkaA high-compatibility PHP Kafka client supporting both PHP-FPM and Swoole runtimes. It implements over 50 Kafka APIs and supports features including message compression, SASL, and SSL. Requires PHP >= 7.1 and Kafka >= 1.0.0, with Swoole >= 4.5 optional for specific features.
What's inside phpkafka
- longlang/phpkafka is a PHP Kafka client designed for use in both PHP-FPM and Swoole environments. It implements the Kafka communication protocol based on the JSON format used in Java and supports 50 different Kafka APIs. The library currently provides implementations for both producing and consuming messages.
Overview of longlang/phpkafka features
masterlonglang/phpkafka is a PHP Kafka client designed to work in both PHP-FPM and Swoole environments. It is built based on the JSON protocol structures from the Java version, allowing it to support a wide range of Kafka APIs.
Key Features:
- API Support: Supports all 50 Kafka APIs.
- Compression: Supports
gzip,snappy,lz4, andzstdmessage compression. - Environment Compatibility: Intelligent detection and compatibility for both PHP-FPM and Swoole.
- Security: Supports SASL authentication and SSL encrypted communication.
- Core Components: Includes Producer and Consumer classes.
Understand the Kafka Message Protocol and Serialization
masterThe Kafka protocol is defined via JSON specification files that describe how clients and servers exchange information. The protocol relies on Requests and Responses, where each request is identified by a 16-bit api key.
Key concepts include:
- Versions: Each message has a unique 16-bit version number. The version of a response must always match the version of the corresponding request.
- validVersions: A top-level field in requests/responses specifying the range of protocol versions supported (e.g.,
"0-2"means versions 0, 1, and 2 are understood). - MessageData Objects: These are generated objects that represent all possible versions of a message, allowing a single code path to handle multiple versions.
- Flexible Versions: Newer versions that use more efficient serialization (e.g.,
COMPACT_STRINGinstead ofSTRING) to save space.
Define and Structure Message Fields
masterMessages consist of an array of fields. The order of fields is critical; changing the order is an incompatible change.
Field Types
- Primitives:
boolean,int8,int16,int32,int64,float64,string(UTF-8), andbytes(binary). - Arrays: Declared using
[]followed by the element type (e.g.,[]Foo).
Field Properties
- Version Specs: Fields can be version-specific. Use
"3+"for fields appearing in version 3 and later, or"0-2"to indicate a field is removed in version 3. - Nullable Fields:
string,bytes, andarrayscan be marked as nullable vianullableVersions. Booleans, ints, and floats cannot be null. - Tagged Fields: Optional data that can be attached to messages without breaking compatibility. They can only be added to "flexible" message versions and must have an open-ended
taggedVersionsrange. - mapKey: Setting
"mapKey": trueon an array element turns the array into a linked hash set, allowing $O(1)$ access via a generatedfindfunction while preserving order.
- Primitives:
How partitioning works in the Producer
masterThe producer uses a default partitioning strategy if no specific partition is provided in the message. The logic follows this hierarchy:
- Explicit Partition: If a
partitionis specified, that partition is used. - Key-based Partitioning: If
partitionisnullbut akeyis provided, the partition is selected usingcrc32(key) % partitions. - Round Robin: If both
partitionandkeyarenull, the producer uses a Round Robin strategy to select a partition.
- Explicit Partition: If a
Configure SSL connection settings
masterUse the
longlang\phpkafka\Config\SslConfigclass to enable and configure SSL/TLS encryption. Once configured, pass theSslConfiginstance to theConsumerConfigusingsetSsl().Key
SslConfigparameters:open: Boolean to enable SSL transmission encryption.verifyPeer: Whether to verify the remote certificate.allowSelfSigned: Whether to allow self-signed certificates.cafile: Path to the CA certificate.capath: Directory containing CA certificates (scans all .pem files).certFile: Path to the client certificate.keyFile: Path to the private key.passphrase: Password for the certificate.
use longlang\phpkafka\Consumer\Consumer; use longlang\phpkafka\Consumer\ConsumerConfig; use longlang\phpkafka\Config\SslConfig; $config = new ConsumerConfig(); // ... other config $sslConfig = new SslConfig(); $sslConfig->setOpen(true); $sslConfig->setVerifyPeer(true); $sslConfig->setAllowSelfSigned(true); $sslConfig->setCafile("/kafka-client/.github/kafka/cert/ca-cert"); $config->setSsl($sslConfig); $consumer = new Consumer($config);Install longlang/phpkafka via Composer
masterTo install the
longlang/phpkafkaclient, use Composer to add it to your project dependencies.composer require longlang/phpkafkaCheck environment requirements for longlang/phpkafka
masterBefore installing, ensure your environment meets the following requirements:
- PHP: >= 7.1
- Kafka: >= 1.0.0
- Swoole: >= 4.5 (optional, required if using Swoole-specific features)
Avoid Incompatible Protocol Changes
masterTo maintain compatibility between clients and servers, avoid the following changes to the message protocol:
- Modifying Released Versions: Never change a protocol version that has already been released. Correct mistakes by issuing a new version.
- Re-ordering Fields: You may add fields, but you must never change the relative order of existing fields.
- Changing Defaults: Never change the default value of an existing field.
- Changing Types: Never change the type of an existing field (except for converting an array of primitives to an array of single-field structures, which is binary-compatible).
Configure SASL authentication for Consumer
masterTo use SASL authentication, pass an array to
$config->setSasl(). Thetypefield should specify the SASL Authentication Type, such as\longlang\phpkafka\Sasl\PlainSasl::classfor PLAIN authentication.use longlang// use longlang// $config = new ConsumerConfig(); // .... Your Other Config $config->setSasl([ "type"=>\longlang\phpkafka\Sasl\PlainSasl::class, "username"=>"admin", "password"=>"admin-secret" ]); $consumer = new Consumer($config); // .... Your Business CodeEnable SASL authentication
masterTo authenticate with Kafka using SASL, pass a configuration array to
setSasl()inProducerConfig.Supported SASL types include
\longlang\phpkafka\Sasl\PlainSasl::classfor PLAIN authentication. You must provide thetype,username, andpassword.use longlang\phpkafka\Producer\ProducerConfig; use longlang\phpkafka\Producer\Producer; $config = new ProducerConfig(); $config->setSasl([ "type" => \longlang\phpkafka\Sasl\PlainSasl::class, "username" => "admin", "password" => "admin-secret" ]); $producer = new Producer($config);Enable SSL connection
masterUse
longlang\phpkafka\Config\SslConfigto configure SSL/TLS settings and pass it to theProducerConfigviasetSsl().use longlang\phpkafka\Producer\ProducerConfig; use longlang\phpkafka\Producer\Producer; use longlang\phpkafka\Config\SslConfig; $config = new ProducerConfig(); $sslConfig = new SslConfig(); $sslConfig->setOpen(true); $sslConfig->setVerifyPeer(true); $sslConfig->setAllowSelfSigned(true); $sslConfig->setCafile("/kafka-client/.github/kafka/cert/ca-cert"); $config->setSsl($sslConfig); $producer = new Producer($config);