PHP的NATS客户端。

安装: 189

依赖项: 0

建议者: 0

安全: 0

星标: 6

关注者: 5

分支: 0

开放问题: 0

类型:neos-package

dev-master 2019-04-02 16:22 UTC

This package is auto-updated.

Last update: 2024-08-29 04:49:02 UTC


README

MIT license Packagist

NATS PHP客户端

这是一个NATS客户端的PHP实现。

🚧 请注意,此包目前正在开发中,尚未准备好供通用使用。

使用

使用composer安装此包

composer require flownative/nats

在PHP中,使用以下方式打开新的连接

use Flownative\Nats\Connection;

// Connect to a server
$nats = new Connection(
    'nats://localhost:4222',
    [
        'username' => 'nats',
        'password' => 'password',
        'debug' => true
    ]
);

// Simple publisher
$nats->publish('foo', 'Hello World');

// Simple asynchronous subscriber
$nats->subscribe('foo', function($message) {
    printf("\nReceived a message: %s\n", $message->getBody());
});

这将打开一个新的套接字连接,并发送CONNECT和PING到指定的NATS服务器,并执行简单的PUB / SUB运行

 🚀  Connecting with server via nats://localhost:4222 ...
>>>> CONNECT {"lang":"php","version":"dev-master@7dd6908c3e9f26e1094873a510547cd950bcb2c7","verbose":false,"pedantic":false,"user":"nats","pass":"password"}
<<<< INFO {"server_id":"MKfYbh2u0ZDgZrI5B1UaAv","version":"1.4.1","proto":1,"git_commit":"3e64f0b","go":"go1.11.5","host":"0.0.0.0","port":4222,"auth_required":true,"max_payload":1048576,"client_id":69} 
>>>> PING
<<<< PONG
>>>> SUB foo vjxX30gfutwGDBxfLuKR
>>>> PUB foo 11
Hello World
<<<< MSG foo vjxX30gfutwGDBxfLuKR 11
<<<< Hello World
Received a message via sid vjxX30gfutwGDBxfLuKR: Hello World

您可以在订阅处理程序中这样回复消息

// New subscribe which replies to a given message:
$nats->subscribe('hello', function (Message $message) {
    $message->reply(sprintf('Hello, %s!', $message->getBody()));
});

// Send a request which will be answered by the "hello" subscriber:
$nats->request(
    'hello',
    'Robert',
    function (Message $message) {
        printf("Request returned: %s\n", $message->getBody());
    }
);

开发

测试

可以使用PhpUnit执行单元测试。主目录中包含一个配置文件。单元测试是自包含的,不需要实际运行的NATS服务器。

NATS流协议缓冲区模式

由于NATS流使用Google的协议缓冲区作为其消息,我们需要根据给定的模式创建相应的PHP类。这是通过一个.proto文件定义的,该文件可以从GitHub上的Go Nats Streaming项目获取。根据此文件,您可以使用协议缓冲区编译器自动创建相应的PHP代码。

https://developers.google.com/protocol-buffers/docs/downloads下载编译器(称为"protoc")

致谢

此包由Robert Lemke在Flownative工作期间开发。它是从头开始编写的,但受到了Raül Pérez的工作的很大启发。

许可证

此包采用MIT许可证。

贡献

欢迎Pull-Requests。请确保阅读行为准则