Learn more about the intricacies of the basic messaging services available in PHP.
- Semaphores
- Gearman
- JMS with PHP via QUERCUS
- JMS with PHP via PHPMQ-> MANTARAY
1. Semaphores
Semaphore is a PHP module that actually consists of three extensions, which includes semaphores, shared memory, and interprocess messaging (IPC). This module provides wrappers for the System V IPC family of functions and to use it in PHP, you need to enable it, because it is not enabled by default, so to enable PHP System V support for semaphores use the option
--enable-sysvsem
; To enable System V shared memory support, compile PHP using the
--enable-sysvshm
; and to enable support for System V messages, compile PHP using the
--enable-sysvmsg
.
* Note: Semaphore module is not available on Windows platforms.')
To use the interprocess communication module (IPC) there is a set of functions listed below:
- msg_get_queue: Create or join a message queue.
resource msg_get_queue ( int $key [, int $perms = 0666 ] )
Returns an identifier that can be used to access the System V message queue with a given key. - msg_queue_exists: Checks for the existence of a message queue.
bool msg_queue_exists ( int $key)
- msg_receive: Receive a message from the message queue.
bool msg_receive ( resource $queue , int $desiredmsgtype , int &$msgtype , int $maxsize ,mixed &$message [, bool $unserialize = true [, int $flags = 0 [, int &$errorcode ]]] )
Receives the first message from the specified queue of the type specified in desiredmsgtype. - msg_remove_queue: Destroy message queue.
bool msg_remove_queue ( resource $queue )
Destroys the message queue specified in the queue. You should use this function only when all processes have completed their work with the message queue, and you must free up system resources. - msg_send: Send a message to the message queue.
bool msg_send ( resource $queue , int $msgtype , mixed $message [, bool $serialize = true [,bool $blocking = true [, int &$errorcode ]]] )
Sends a message of type MsgType (which must be greater than 0) to the message queue specified in the queue. - msg_set_queue: Set information to the message queue data structure.
bool msg_set_queue ( resource $queue , array $data )
Allows you to change the values ​​of msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes in areas of the main message queue data structure. - msg_stat_queue: Returns information from a message queue data structure.
array msg_stat_queue ( resource $queue )
Returns metadata for the message queue specified in queue
2. Gearman
Gearman is an application framework and is designed to work with multiple processes and allows programs to perform tasks in parallel and call functions between languages. Gearman can be used in a variety of applications: from high-availability websites to sending database replication events, and consists of two main components: a job server and a client / worker API. The client and the worker API can be used in a wide variety of languages, but the job server is only available as a C library or Perl library. This fact makes it difficult to run the server on Windows, mainly due to the unresolved dependency on other libraries.
You can install the Gearman app platform in two ways:
- Using a clean PHP wrapper called Net_Gearman using
pear install Net_Gearman
. - A specialized PHP extension. [
] . This extension offers an OOP interface for writing Gearman clients and workers.
3. JMS with PHP via Quercus
As you probably know, most of the features of
JMS are designed for message-driven services, which in the Java world are very suitable, but not suitable for PHP. In order to use these functions in PHP, you need to implement Java using various technologies, in this case, Quercus.
Java Message Service (JMS) is a messaging standard that allows application-based Java Enterprise Edition (Java EE) application components to create, send, receive, and read messages. Data exchange can be asynchronous (the JMS provider can deliver messages to the client as they arrive; clients do not need to request messages in order to receive them) or reliable (the JMS API can guarantee that the message will be delivered immediately and only once. Lower levels of reliability available for applications that can afford to skip messages or receive duplicate messages).
Quercus is a 100% PHP 5 implementation of Java Caucho Technology, released under the Open Source GPL license. Quercus comes with a large number of PHP modules and extensions, such as PDF, PDO, MySQL and JSON, and provides tight integration of Java services with PHP scripts, so using PHP with JMS is very convenient. Quercus also offers a convenient messaging interface using Java messaging, so it gives you the ability to send and receive messages using the Resin JMS implementation or any other messaging service that implements JMS, as you will see later in this section. You have two options for installing and using Quercus:
Resin Web server
Quercus is part of the
Resin Application Server 
and built into Resin - so there is no need for additional installation. To install Resin on Windows, follow the steps from
www.caucho.com/resin-3.1/doc/resin-web-server.xtp#GettingStarted . To check the Resin installation, go to
localhost : 8080 in the browser.
To use JMS in Quercus, configure JMS for PHP and JAVA, for this you need to install
ConnectionFactory and
Queue , both are in the resin-web.xml file in the WEB-INF directory.
resin-web.xml <web-app xmlns="http://caucho.com/ns/resin" xmlns:resin="urn:java:com.caucho.resin"> <resin:MemoryQueue> <Named>Queue</Named> </resin:MemoryQueue> <resin:JmsConnectionFactory/> <ejb-message-bean class="example.MyListener"> <destination>#{Queue}</destination> </ejb-message-bean> </web-app>
The Quercus interface programming model assumes an interface to access the queue using the
java_bean () call, which will find the named object in the resin-web.xml file, in this case, the queue. Precisely because Queue implements the
java.util.concurrent.BlockingQueue interface, the PHP script has the ability to immediately send data to the queue using
offer () and retrieve it using
poll () .
<?php if (array_key_exists("message", $_POST)) { $queue = java_bean("Queue"); if (! $queue) { echo "Unable to get message queue!\n"; } else { if ($queue->offer($_POST["message"]) == TRUE) { echo "Successfully sent message '" . $_POST["message"] . "'"; } else { echo "Unable to send message '" . $_POST["message"] . "'"; } } } ?>
The script checks the POST variable “message” and, if it is set, sends the value of this variable to the JMS queue. A message-driven object (MDB) receives these messages and records them. The entry is displayed by the servlet.
NetBeans IDE and GlassFish
The second way to use Quercus is to use NetBeans IDE and GlassFish as a server. To use Quercus in NetBeans, you must follow these steps:
- Unpack Quercus-4.0.39.war (http://quercus.caucho.com/) and copy the JAR files in the “WEB-INF / lib” directory into “GLASSFISH_HOME / domains / domain / lib”.
- Create a new web application project, “PHPexample”, using NetBeans IDE and select GlassFish as the server:
After you click Finish, a folder with the following structure will be created:
- In the WEB-INF directory, create a web.xml file (if it has not been created before): File> New> Empty. Paste the following text into it and save:
web.xmlweb.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <description>Caucho Technology's PHP Implementation, Running on GlassFish Java EE 5</description> <servlet> <servlet-name>Quercus Servlet</servlet-name> <servlet-class>com.caucho.quercus.servlet.QuercusServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Quercus Servlet</servlet-name> <url-pattern>\*.php</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.php</welcome-file> </welcome-file-list> </web-app>
So we declared a servlet from PHP.
- In the main project, PHPexample, create a PHP file called index.php with the context:
index.phpindex.php <?php echo " !"; phpinfo(); ?>
This page prints "Hello world!" In the browser and some PHP configuration options. The directory structure of the created project is as follows:
Please note that “index.jsp” is only a template file to get started with JSP, and it is not related to our tasks.
- Run the PHP application in GlassFish on localhost : 8080 / PHPexample / index.php / and you should get the output below:
As soon as you see that Quercus runs in NetBeans IDE and GlassFish as a server, you can try to use all the features of JMS and all other extensions that come with Quercus.
4. JMS with PHP through PHPMQ
PHPMQ is an open source peer-to-peer messaging toolkit for PHP, giving the PHP developer the ability to perform JMS operations, such as sending and receiving messages across queues and topics, while delivering and delivering constant messaging. This opens up new opportunities for PHP developers who can now access data from the so-called back office, which, as a rule, are available only to application servers and old messaging solutions.
PHPMQ (
) Mantaray (
) is a distributed, peer-to-peer, serverless system for solving messaging tasks for Java (JMS), C ++ and .NET applications, integrates with JBoss, WebLogic and WebSphere. It offers guaranteed delivery, security, and transactions, and supports TCP, SSL, and HTTP protocols.
Install PHPMQ:
→ Download and install the MantaRay messaging bus.
→ Configure MantaRay to enable the RMI API and create the RMI registry (See the RMI API documentation on the MantaRay project)
→ Run Mantaray as a separate application.
→ Enable PHP-Java extension in php.ini - current information available at
www.php.net/manual/en/ref.java.php→ Add phpmq.jar (located here in the zip archive) and manta.jar (located in the MantaRay.zip) in the php.ini "java.class.path" property
→ Run examples (chat.php for themes and queue_receiver.php, queue_sender.php for queues)
The PHPMQ messaging API includes the following functions:
- enqueue : sends a message to the queue with the name $ queueName (string); $ userId (string) is the identifier on the message bus.
enqueue($userId, $queueName, $message)
- dequeue : returns a text message from the $ queueName (string); $ userId (string) is the identifier on the message bus.
dequeue($userId, $queueName)
- getQueues : returns a list of queues that are available on the message bus.
array getQueues()
- getTopics : returns a list of topics that are available in the message bus.
array getTopics()
- subscribe : adds a listener to the topic $ topicName (string), which will receive no more than $ messagesToCash (number) messages; $ userId (string) is the identifier on the message bus.
subscribe($userKey $topicName, $messagesToCash)
- publishMessage : publishes a message with the text $ msg (string) with the topic $ topicName (string); $ userId (string) is the identifier on the message bus.
publishMessage($userKey, $topicName, $msg)
From translator
After the transfer began, it turned out that the material did not reach the level of the habr. I hope this does not prevent someone from benefiting from this material.
As usual, please report all inaccuracies to Habr-mail.