bitninja / ninjarpc
Microservice RPC through message queues.
Requires
- php: ^7.2|^8.0
- bramus/monolog-colored-line-formatter: ^2.0|^3.0
- monolog/monolog: ^1.24|^2.0|^3.0
- php-amqplib/php-amqplib: ^3.1.1
Requires (Dev)
- edgedesign/phpqa: ~1.23.0
- overtrue/phplint: ~1.1.9
- phpunit/phpunit: ~6.5.14
- sensiolabs/security-checker: ~5.0.3
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-09 11:32:33 UTC
README
The easy to use queue based RPC library. You can use any queueing system and any ancoding to connect your server and client. With ninjaRPC you can setup your PHP based microservice stack.
Installation
composer require bitninja/ninjarpc ~2.1
Example Server
use BitNinja\NinjaRpc\Server;
use BitNinja\NinjaRpc\Encoders\JsonEncoder;
use BitNinja\NinjaRpc\QueueManagers\RabbitMQ;
// Target service
$ping = function($param1){
echo 'ping was called!';
};
// Set up a queue manager
$queueManager = new RabbitMQ();
// Set up an encoder
$encoder = new JsonEncoder();
// Set up a router
$router = new SimpleRouter([
'ping' => $ping
]);
// Create the server
$server = new Server('TestServer', $queueManager, $encoder, $router);
// Serve requests forever
while (1) {
$server->listen();
}
Example Client
use BitNinja\NinjaRpc\Client;
use BitNinja\NinjaRpc\Encoders\JsonEncoder;
use BitNinja\NinjaRpc\QueueManagers\RabbitMQ;
// Set up a queue manager
$queueManager = new RabbitMQ()
// Set up an encoder
$encoder = new JsonEncoder();
// Create the client
$client = new Client($queueManager, $encoder);
// Invoke an rpc call
$call = $client->asyncCall('TestServer', 'ping', ['param1' => 'pong']);
// Wait for the response
$call->wait();
// Debug dump the results
$call->dumpResult();
RabbitMQ delivery options
The RabbitMQ queue manager takes an options array as its 7th constructor
argument, or through setOptions(). Set them before creating the Server,
because the Server constructor connects. Leaving them unset keeps the original
behaviour: non-durable auto-delete queues, transient messages and no_ack consumers.
| Option | Default | Set on | Description |
|---|---|---|---|
durableQueues | false | Every server and client of the queue | Service queues are declared durable and not auto-delete. Response queues are not affected. Every service that declares the queue (servers, and clients before publishing) must use the same value, otherwise RabbitMQ closes the channel with 406 PRECONDITION_FAILED. An existing queue has to be deleted before its flags can change. |
durableQueueNames | [] | Every declarer of those queues | Same durable declare, but only for the listed service queue names. Other queues keep the old flags. |
persistentMessages | false | Clients (writers) | Calls are published with delivery_mode 2. Responses stay transient. Only survives a broker restart if the queue is durable too. |
noAck | true | Servers (readers) | false turns on manual ack for service queues. Server::listen() acks the message after it was handled, also when the handler threw, so it is only redelivered if the process dies or the connection drops before that. |
prefetch | null | Servers (readers) | Default max unacked messages per consumer, only used with noAck false. The server handles one message at a time, so 1 lets idle workers take the next message. |
prefetchByQueue | [] | Servers (readers) | Queue name to prefetch count. Wins over prefetch for that queue. basic_qos runs immediately before each consume, so one process can mix limits. |
expireCallsAfterTimeout | false | Clients (writers) | Service-queue messages expire after the client timeout (setTimeout(), default 60 seconds). Responses are unchanged. A queue dead-letter exchange is required, otherwise RabbitMQ drops the expired message. |
appId | unset | Clients and servers | Non-empty string. Set on every published message as the AMQP app-id, including replies. RabbitMQ does not read it. Use the sending service's name. |
RabbitMQ::getCurrentAppId() | Servers (readers) | App-id of the service message being handled. Empty when the publisher did not set one. Stays set until the next message is taken, so code that runs after listen() returns can still read it. |
use BitNinja\NinjaRpc\QueueManagers\RabbitMQ;
// Server side
$queueManager = new RabbitMQ($host, 5672, $user, $password, '/', 0, [
'durableQueues' => true,
'noAck' => false,
'prefetch' => 1,
]);
$server = new Server('TestServer', $queueManager, $encoder, $router);
// Client side
$queueManager = new RabbitMQ($host, 5672, $user, $password);
$queueManager->setOptions([
'durableQueues' => true,
'persistentMessages' => true,
]);
$client = new Client($queueManager, $encoder);
A fatal error that cannot be caught (e.g. running out of memory) leaves the message unacked, and RabbitMQ redelivers it to another worker. A message that crashes every worker keeps being redelivered on a classic queue.
Motivation
Recently microservices has more and more popularity, and one of the best way for your services to communicate with each other is throug message queues. There are a lot fo different queueing systems. The most famous general puprose queueing ssgem is RabbitMQ, but you can use redis, ActiveMQ, Kafka, etc.
NinjaRPC manages all the nasty details behind the scenes of an RPC call using a message queue. Doing an RPC call is not simply sending a message. You have to deal with the response too, take care of declaring the queues, handle timeouts, etc. This is where NinjaRPC helps you.
You can use the built in queue implementations or create your own implementation. (please send me a pull request if you implement new queuing systems)
Also you have the freedom to choose a coding. I have implemented some basic encoders like the PHP built in serialize and json, but you are free to implement any other encoders to us.
API Reference
Tests
Unit tests
You can run the unit tests using phpunit. Simply run it at the root of the git source tree, and it will run all the unit tests and generate shiny reports.
Integration tests
You can run a basic integration test. Make sure to set up a rabbitmq server with default configurations, or start a docker for it first.
$ docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:3
Then you can start the integration tests. Start with the server.
$ cd example
$ php ./server.php
Then in a new console start the client too.
$ cd example
$ php ./client.php
Contributors
Any contribution is very welcome! If you implement new queue drivers or encoders, please send a pull request.
License
MIT license.