<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Behzad Babaei on Medium]]></title>
        <description><![CDATA[Stories by Behzad Babaei on Medium]]></description>
        <link>https://medium.com/@behzadbabaei?source=rss-e41eb158da0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ytVwuMqt-FHSjYtYZ40jVQ.jpeg</url>
            <title>Stories by Behzad Babaei on Medium</title>
            <link>https://medium.com/@behzadbabaei?source=rss-e41eb158da0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:26:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@behzadbabaei/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Developing Microservices by using Lumen & RabbitMQ — Part 3]]></title>
            <link>https://behzadbabaei.medium.com/developing-microservices-by-using-lumen-rabbitmq-part-3-4dc039d2b3c8?source=rss-e41eb158da0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dc039d2b3c8</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[lumen]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[message-broker]]></category>
            <dc:creator><![CDATA[Behzad Babaei]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 12:14:01 GMT</pubDate>
            <atom:updated>2021-06-22T08:42:44.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developing Microservices by using Lumen &amp; RabbitMQ — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai_oaAL60fzhovwclrgtcg.png" /></figure><p>In the previous articles, we have covered the basics and also the fanout exchange, in this article we are going to explore the direct exchange and also develop two services that use this exchange. As it was explained in the first part of the series, A direct exchange delivers messages to queues based on a message routing key and the message goes to the queues whose binding key exactly matches the routing key of the message.</p><h4>What we are up to in this article?</h4><p>Now we are going to create two email services in which each one might have a different functionality or the same (it’s not our main focus to discuss it). Consider the situation that we need to email the order information to two different mail services, we are only going to focus on our direct exchange capabilities.</p><p>One of our main purpose in providing this series was how to interact with RabbitMQ in Lumen or Laravel project or how to use RabbitMQ to send messages to other applications in the SOA or Microservice architecture.</p><p>Just to make sure that we are on the same page, I need to go over the workflow once again. In the previous articles, our workflow was like this, when one order is created we simply sent the order information to the warehouse and sale service by using a fanout exchange, and now when the order is shipped we want to notify the user by sending him/her an email by using one of our email services, we are accomplishing this task by using a DIRECT Exchange.</p><p>I have added the repository links for references.</p><p>Email-service1 repository:</p><p><a href="https://github.com/behzadbabaei/lumen-microservice-email1.git">https://github.com/behzadbabaei/lumen-microservice-email1.git</a></p><p>Email-service2 repository:</p><p><a href="https://github.com/behzadbabaei/lumen-microservice-email2.git">https://github.com/behzadbabaei/lumen-microservice-email2.git</a></p><p>So first of all we need to configure the RabbitMQ, go to your RabbitMQ dashboard, create a direct exchange, name it “email.direct”, then create two queues named “email.service1” and ”email.service2”, then bind the queue “email.service1” with routing keys of “email1” to “email.direct” exchange, and finally, bind the queue “email.service2” with routing keys of “email2” to “email.direct” exchange too. we are done with configuring the RabbitMQ for now.</p><p>First of all, we need to configure our E-Store project. We are going through the process step by step.</p><p>First configuring the RabbitMq for direct exchange. In the config/queue.php file in the ‘connections’ array add the code below:</p><pre><strong>&#39;rabbitmq_direct&#39; </strong>=&gt; [<br>    <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;rabbitmq&#39;</strong>,<br>    <strong>&#39;queue&#39; </strong>=&gt; <strong>&#39;email.service1&#39;</strong>,<br>    <strong>&#39;connection&#39; </strong>=&gt; PhpAmqpLib\Connection\AMQPLazyConnection::<strong>class</strong>,<br>    <strong>&#39;hosts&#39; </strong>=&gt; [<br>        [<br>            <strong>&#39;host&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_HOST&#39;</strong>, <strong>&#39;127.0.0.1&#39;</strong>),<br>            <strong>&#39;port&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PORT&#39;</strong>, 15672),<br>            <strong>&#39;user&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_USER&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;password&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PASSWORD&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;vhost&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_VHOST&#39;</strong>, <strong>&#39;/&#39;</strong>),<br>        ],<br>    ],<br>    <strong>&#39;options&#39; </strong>=&gt; [<br>        <strong>&#39;queue&#39; </strong>=&gt; [<br>            <strong>&#39;exchange&#39; </strong>=&gt; <strong>&#39;email.direct&#39;</strong>,<br>            <strong>&#39;exchange_type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>            <strong>&#39;exchange_routing_key&#39; </strong>=&gt; <strong>&quot;email1&quot;</strong>,<br>            <strong>&#39;prioritize_delayed_messages&#39; </strong>=&gt;  <strong>false</strong>,<br>            <strong>&#39;queue_max_priority&#39; </strong>=&gt; 10,<br>        ],<br>        <strong>&#39;exchange&#39; </strong>=&gt; [<br>            <strong>&#39;name&#39; </strong>=&gt; <strong>&#39;email.service&#39;</strong>,<br>            <strong>&#39;declare&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DECLARE&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>            <strong>&#39;passive&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_PASSIVE&#39;</strong>, <strong>false</strong>),<br>            <strong>&#39;durable&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DURABLE&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;auto_delete&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_AUTODELETE&#39;</strong>, <strong>false</strong>),<br>            <strong>&#39;arguments&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_ARGUMENTS&#39;</strong>),<br>        ],<br>        <strong>&#39;ssl_options&#39; </strong>=&gt; [<br>            <strong>&#39;cafile&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_CAFILE&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_cert&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALCERT&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_key&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALKEY&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;verify_peer&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_VERIFY_PEER&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;passphrase&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_PASSPHRASE&#39;</strong>, <strong>null</strong>),<br>        ],<br>    ],<br>    <strong>&#39;worker&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_WORKER&#39;</strong>, <strong>&#39;default&#39;</strong>),<br>],</pre><p>In the config above we just created a new connection that uses the direct exchange, we also have set the default queue with routing key which is “email.service1” with the routing key of “email1”.</p><p>Now it is time to create the required events and handler. Create an event and name it OrderShipped in the app/Events folder and put the code below in this class:</p><pre><strong>namespace </strong>App\Events;<br><strong>use </strong>App\Order;<br><strong>class </strong>OrderShipped <strong>extends </strong>Event<br>{<br>    <strong>public $order</strong>;<br>    <strong>public function </strong>__construct(Order $order)<br>    {<br>        $this-&gt;<strong>order </strong>= $order;<br>    }<br>}</pre><p>Then create an event listener in the app/Listeners and name it OrderShippedListener, then put the content below in this class:</p><pre><strong>namespace </strong>App\Listeners;<br><strong>use </strong>Illuminate\Contracts\Queue\ShouldQueue;<br><strong>use </strong>Log;<br><strong>class </strong>OrderShippedListener <strong>implements </strong>ShouldQueue<br>{<br>    <strong>public $connection </strong>= <strong>&#39;rabbitmq_direct&#39;</strong>;<br><br>    <strong>public function </strong>__construct()<br>    {<br>       <br>$randomNumber = <em>rand</em>(0, 1);<br>$queueKeys = [<strong>&#39;email.service1&#39;</strong>, <strong>&#39;email.service2&#39;</strong>];<br>$routingKeys = [<strong>&#39;email1&#39;</strong>, <strong>&#39;email2&#39;</strong>];<br><br>config([ <strong>&#39;queue.connections.rabbitmq_direct.queue&#39; </strong>=&gt; $queueKeys[$randomNumber],<br>   <strong>&#39;queue.connections.rabbitmq_direct.options.queue.exchange_routing_key&#39; </strong>=&gt; $routingKeys[$randomNumber]<br>]);<br><br>    }<br>    <em>/**</em><br>     <em>* Handle the event.</em><br>     <em>*</em><br>     <em>* </em><strong><em>@param  </em></strong><em>$event</em><br>     <em>* </em><strong><em>@return </em></strong><em>void</em><br>     <em>*/</em><br>    <strong>public function </strong>handle($event)<br>    {<br>        Log::<em>info</em>(<strong>&#39;Order shipped from e-store:&#39; </strong>. <em>json_encode</em>($event));<br>    }<br>}</pre><p>As you might have noticed we have set the default connection to the “rabbitmq_direct” we have created few step backs by the code below:</p><pre><strong>public $connection </strong>= <strong>&#39;rabbitmq_direct&#39;</strong>;</pre><p>We also created a mechanism for selecting random email service at the time, for sending an email by them.</p><pre>$randomNumber = <em>rand</em>(0, 1);<br>$queueKeys = [<strong>&#39;email.service1&#39;</strong>, <strong>&#39;email.service2&#39;</strong>];<br>$routingKeys = [<strong>&#39;email1&#39;</strong>, <strong>&#39;email2&#39;</strong>];<br><br>config([<strong>&#39;queue.connections.rabbitmq_direct.queue&#39; </strong>=&gt; $queueKeys[$randomNumber], <strong>&#39;queue.connections.rabbitmq_direct.options.queue.exchange_routing_key&#39; </strong>=&gt; $routingKeys[$randomNumber]<br>]);</pre><p>In the app/Providers/EventServiceProvider class add the below code in the $listen array</p><pre>\App\Events\OrderShipped::<strong>class </strong>=&gt; [<br>    \App\Listeners\OrderShippedListener::<strong>class</strong>,<br>],</pre><p>For testing our functionality we need to test our project, for that, we create a command which triggers our OrderShipped event.<br>Create a command in the app/Console/Commands and name it “ShipOrder” and put the content below in this class:</p><pre><strong>namespace </strong>App\Console\Commands;<br><strong>use </strong>App\Order;<br><strong>use </strong>Illuminate\Console\Command;<br><strong>class </strong>ShipOrder <strong>extends </strong>Command<br>{<br>    <strong>protected $signature </strong>= <strong>&#39;order:ship&#39;</strong>;<br><br>    <strong>protected $description </strong>= <strong>&#39;Ship a order&#39;</strong>;<br><br>    <strong>public function </strong>__construct()<br>    {<br>        <strong>parent</strong>::<em>__construct</em>();<br>    }<br>    <strong>public function </strong>handle()<br>    {<br>        $order = Order::<em>with</em>(<strong>&#39;user&#39;</strong>)-&gt;inRandomOrder()-&gt;first();<br>        event(<strong>new </strong>\App\Events\OrderShipped($order));<br>        <strong>return </strong>0;<br>    }<br>}</pre><p>In the code above we simply select one order randomly and pass it to the event.<br>Now it’s time to create and configure our email services. create and new lumen project and name it “email-service1”.<br>- install the RabbitMQ package by running</p><pre>Composer require vladimir-yuldashev/laravel-queue-rabbitmq:v10.2.2</pre><p>Then after installation, add the code below in bootstrap/app.php and also uncomment the EventServiceProvider registration line.</p><pre>$app→register(App\Providers\EventServiceProvider::class);<br>$app-&gt;register(VladimirYuldashev\LaravelQueueRabbitMQ\LaravelQueueRabbitMQServiceProvider::<strong>class</strong>);</pre><p>Now we need to configure our .env. In the created project put the config below in the .env file.</p><pre><strong>QUEUE_CONNECTION=rabbitmq</strong><br><strong>RABBITMQ_HOST</strong>=<strong>localhost</strong><br><strong>RABBITMQ_PORT</strong>=<strong>5672</strong><br><strong>RABBITMQ_VHOST</strong>=<strong>/</strong><br><strong>RABBITMQ_LOGIN</strong>=<strong>guest</strong><br><strong>RABBITMQ_PASSWORD</strong>=<strong>guest</strong><br><strong>RABBITMQ_QUEUE</strong>=<strong>email.service1</strong><br><strong>RABBITMQ_EXCHANGE_NAME</strong>=<strong>email.direct</strong><br><strong>RABBITMQ_EXCHANGE_DECLARE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_TYPE</strong>=<strong>fanout</strong><br><strong>RABBITMQ_EXCHANGE_PASSIVE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_DURABLE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_AUTODELETE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_ARGUMENTS</strong>=<strong>default</strong></pre><p>Since the project is new, we need to create a config file for the queue, So, Create a file and name it “queue.php” in the config folder then put the content below in this file.</p><pre><strong>&lt;?php</strong><br><strong>return </strong>[<br>  <br>    <strong>&#39;default&#39; </strong>=&gt; env(<strong>&#39;QUEUE_CONNECTION&#39;</strong>, <strong>&#39;sync&#39;</strong>),<br><br>    <strong>&#39;connections&#39; </strong>=&gt; [<br>        <strong>&#39;sync&#39; </strong>=&gt; [<br>            <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;sync&#39;</strong>,<br>        ],<br>        <strong>&#39;database&#39; </strong>=&gt; [<br>            <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;database&#39;</strong>,<br>            <strong>&#39;table&#39; </strong>=&gt; env(<strong>&#39;QUEUE_TABLE&#39;</strong>, <strong>&#39;jobs&#39;</strong>),<br>            <strong>&#39;queue&#39; </strong>=&gt; <strong>&#39;default&#39;</strong>,<br>            <strong>&#39;retry_after&#39; </strong>=&gt; 90,<br>        ],<br>        <strong>&#39;beanstalkd&#39; </strong>=&gt; [<br>            <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;beanstalkd&#39;</strong>,<br>            <strong>&#39;host&#39; </strong>=&gt; <strong>&#39;localhost&#39;</strong>,<br>            <strong>&#39;queue&#39; </strong>=&gt; <strong>&#39;default&#39;</strong>,<br>            <strong>&#39;retry_after&#39; </strong>=&gt; 90,<br>        ],<br>        <strong>&#39;sqs&#39; </strong>=&gt; [<br>            <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;sqs&#39;</strong>,<br>            <strong>&#39;key&#39; </strong>=&gt; env(<strong>&#39;SQS_KEY&#39;</strong>, <strong>&#39;your-public-key&#39;</strong>),<br>            <strong>&#39;secret&#39; </strong>=&gt; env(<strong>&#39;SQS_SECRET&#39;</strong>, <strong>&#39;your-secret-key&#39;</strong>),<br>            <strong>&#39;prefix&#39; </strong>=&gt; env(<strong>&#39;SQS_PREFIX&#39;</strong>, <strong>&#39;https://sqs.us-east-1.amazonaws.com/your-account-id&#39;</strong>),<br>            <strong>&#39;queue&#39; </strong>=&gt; env(<strong>&#39;SQS_QUEUE&#39;</strong>, <strong>&#39;your-queue-name&#39;</strong>),<br>            <strong>&#39;region&#39; </strong>=&gt; env(<strong>&#39;SQS_REGION&#39;</strong>, <strong>&#39;us-east-1&#39;</strong>),<br>        ],<br>        <strong>&#39;redis&#39; </strong>=&gt; [<br>            <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;redis&#39;</strong>,<br>            <strong>&#39;connection&#39; </strong>=&gt; env(<strong>&#39;QUEUE_REDIS_CONNECTION&#39;</strong>, <strong>&#39;default&#39;</strong>),<br>            <strong>&#39;queue&#39; </strong>=&gt; <strong>&#39;default&#39;</strong>,<br>            <strong>&#39;retry_after&#39; </strong>=&gt; 90,<br>            <strong>&#39;block_for&#39; </strong>=&gt; <strong>null</strong>,<br>        ],<br>        <strong>&#39;rabbitmq&#39; </strong>=&gt; [<br>            <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;rabbitmq&#39;</strong>,<br>            <strong>&#39;queue&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_QUEUE&#39;</strong>, <strong>&#39;email.service1&#39;</strong>),<br>            <strong>&#39;connection&#39; </strong>=&gt; PhpAmqpLib\Connection\AMQPLazyConnection::<strong>class</strong>,<br>            <strong>&#39;hosts&#39; </strong>=&gt; [<br>                [<br>                    <strong>&#39;host&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_HOST&#39;</strong>, <strong>&#39;127.0.0.1&#39;</strong>),<br>                    <strong>&#39;port&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PORT&#39;</strong>, 15672),<br>                    <strong>&#39;user&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_USER&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>                    <strong>&#39;password&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PASSWORD&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>                    <strong>&#39;vhost&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_VHOST&#39;</strong>, <strong>&#39;/&#39;</strong>),<br>                ],<br>            ],<br>            <strong>&#39;options&#39; </strong>=&gt; [<br>                <strong>&#39;queue&#39; </strong>=&gt; [<br>                    <strong>&#39;exchange&#39; </strong>=&gt; <strong>&#39;email.direct&#39;</strong>,<br>                    <strong>&#39;exchange_type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>                    <strong>&#39;exchange_routing_key&#39; </strong>=&gt; <strong>&#39;email1&#39;</strong>,<br>                    <strong>&#39;prioritize_delayed_messages&#39; </strong>=&gt;  <strong>false</strong>,<br>                    <strong>&#39;queue_max_priority&#39; </strong>=&gt; 10,<br>                ],<br>                <strong>&#39;exchange&#39; </strong>=&gt; [<br>                    <strong>&#39;name&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_NAME&#39;</strong>, <strong>&#39;email.service&#39;</strong>),<br>                    <strong>&#39;declare&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DECLARE&#39;</strong>, <strong>true</strong>),<br>                    <strong>&#39;type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>                    <strong>&#39;passive&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_PASSIVE&#39;</strong>, <strong>false</strong>)<br>                ],<br>                <strong>&#39;ssl_options&#39; </strong>=&gt; [<br>                    <strong>&#39;cafile&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_CAFILE&#39;</strong>, <strong>null</strong>),<br>                    <strong>&#39;local_cert&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALCERT&#39;</strong>, <strong>null</strong>),<br>                    <strong>&#39;local_key&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALKEY&#39;</strong>, <strong>null</strong>),<br>                    <strong>&#39;verify_peer&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_VERIFY_PEER&#39;</strong>, <strong>true</strong>),<br>                    <strong>&#39;passphrase&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_PASSPHRASE&#39;</strong>, <strong>null</strong>),<br>                ],<br>            ],<br>            <strong>&#39;worker&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_WORKER&#39;</strong>, <strong>&#39;default&#39;</strong>),<br>        ],<br>    ],<br><br>    <strong>&#39;failed&#39; </strong>=&gt; [<br>        <strong>&#39;database&#39; </strong>=&gt; env(<strong>&#39;DB_CONNECTION&#39;</strong>, <strong>&#39;mysql&#39;</strong>),<br>        <strong>&#39;table&#39; </strong>=&gt; env(<strong>&#39;QUEUE_FAILED_TABLE&#39;</strong>, <strong>&#39;failed_jobs&#39;</strong>),<br>    ],<br>];</pre><p>As you can see above we simply have set the exchange and default queue name with default routing key value in the following array.</p><pre><strong>‘queue’ </strong>=&gt; [</pre><pre><strong>    &#39;exchange&#39; </strong>=&gt; <strong>&#39;email.direct&#39;</strong>,<br>    <strong>&#39;exchange_type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>    <strong>&#39;exchange_routing_key&#39; </strong>=&gt; <strong>&#39;email1&#39;</strong>,<br>    <strong>&#39;prioritize_delayed_messages&#39; </strong>=&gt;  <strong>false</strong>,<br>    <strong>&#39;queue_max_priority&#39; </strong>=&gt; 10,</pre><pre>],</pre><p>We are going to work with jobs and queues, so the job_failed is handled by the database so we need the job failed migration, so for adding that run command below in the terminal in the main project folder.</p><pre>php artisan queue:failed-table</pre><p>When the order in the E-store is shipped the “OrderShipped” is triggered, then our handler serializes the order information and sends it to the RabbitMQ direct queues accompanied with routing key. In this new service, we should listen for that event, we are also bound to the “email.direct” exchange and “email.service1” queue with the routing key of “email1”.By doing the configuration we are now capturing the corresponding events.</p><p>Now we need to add our listener for that capturing the events, So create a listener and name it OrderShippedListener in the app/Listeners folder (just the same in the E-store Project), then put the content below in this class.</p><pre><strong>namespace </strong>App\Listeners;<br><strong>use </strong>Illuminate\Contracts\Queue\ShouldQueue;<br><strong>use </strong>Log;<br><strong>class </strong>OrderShippedListener <strong>implements </strong>ShouldQueue<br>{<br><br>    <strong>public function </strong>__construct()<br>    {<br>    }<br><br>     <strong>public function </strong>handle($event)<br>    {<br>        Log::<em>info</em>(<strong>&#39;Order shipped from Email service 1:&#39; </strong>. <em>json_encode</em>($event));<br>    }<br>}</pre><p>In this Listener class, we get the $event object which contains the required information which is sent by the publisher or the producer which is the E-store app. In the real project, you would probably follow your work to do whatever you want with $event object, but for now, we only Log the event just to show we have successfully captured the events.</p><p>We are done with Email Service 1.</p><p>Now we should develop a second email service. For easing the process just copy the “email-servic1” project and rename it to “email-service2”.</p><p>We need to reconfigure the .env file and queue.php file as well.</p><p>In the .env file delete the configuration for RabbitMQ from the previous project and put the content below in the .env file (or replace them).</p><pre><strong>QUEUE_CONNECTION</strong>=<strong>rabbitmq</strong></pre><pre><strong>RABBITMQ_HOST</strong>=<strong>localhost</strong><br><strong>RABBITMQ_PORT</strong>=<strong>5672</strong><br><strong>RABBITMQ_VHOST</strong>=<strong>/</strong><br><strong>RABBITMQ_LOGIN</strong>=<strong>guest</strong><br><strong>RABBITMQ_PASSWORD</strong>=<strong>guest</strong><br><strong>RABBITMQ_QUEUE</strong>=<strong>email.service2</strong><br><strong>RABBITMQ_EXCHANGE_NAME</strong>=<strong>email.direct</strong><br><strong>RABBITMQ_EXCHANGE_DECLARE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_TYPE</strong>=<strong>fanout</strong><br><strong>RABBITMQ_EXCHANGE_PASSIVE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_DURABLE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_AUTODELETE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_ARGUMENTS</strong>=<strong>default</strong></pre><p>As you see we reconfigure the queue name for listening to the new queue named “email.service2” and replace the configuration below with “rabbitmq” in the connections array in the config/queue.php file.</p><pre><strong>&#39;rabbitmq&#39; </strong>=&gt; [<br>    <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;rabbitmq&#39;</strong>,<br>    <strong>&#39;queue&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_QUEUE&#39;</strong>, <strong>&#39;email.service2&#39;</strong>),<br>    <strong>&#39;connection&#39; </strong>=&gt; PhpAmqpLib\Connection\AMQPLazyConnection::<strong>class</strong>,<br>    <strong>&#39;hosts&#39; </strong>=&gt; [<br>        [<br>            <strong>&#39;host&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_HOST&#39;</strong>, <strong>&#39;127.0.0.1&#39;</strong>),<br>            <strong>&#39;port&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PORT&#39;</strong>, 15672),<br>            <strong>&#39;user&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_USER&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;password&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PASSWORD&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;vhost&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_VHOST&#39;</strong>, <strong>&#39;/&#39;</strong>),<br>        ],<br>    ],<br>    <strong>&#39;options&#39; </strong>=&gt; [<br>        <strong>&#39;queue&#39; </strong>=&gt; [<br>            <strong>&#39;exchange&#39; </strong>=&gt; <strong>&#39;email.direct&#39;</strong>,<br>            <strong>&#39;exchange_type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>            <strong>&#39;exchange_routing_key&#39; </strong>=&gt; <strong>&#39;email2&#39;</strong>,<br>            <strong>&#39;prioritize_delayed_messages&#39; </strong>=&gt;  <strong>false</strong>,<br>            <strong>&#39;queue_max_priority&#39; </strong>=&gt; 10,<br>        ],<br>        <strong>&#39;exchange&#39; </strong>=&gt; [<br>            <strong>&#39;name&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_NAME&#39;</strong>, <strong>&#39;email.service&#39;</strong>),<br>            <strong>&#39;declare&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DECLARE&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>            <strong>&#39;passive&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_PASSIVE&#39;</strong>, <strong>false</strong>)<br>        ],<br>        <strong>&#39;ssl_options&#39; </strong>=&gt; [<br>            <strong>&#39;cafile&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_CAFILE&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_cert&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALCERT&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_key&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALKEY&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;verify_peer&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_VERIFY_PEER&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;passphrase&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_PASSPHRASE&#39;</strong>, <strong>null</strong>),<br>        ],<br>    ],<br>    <strong>&#39;worker&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_WORKER&#39;</strong>, <strong>&#39;default&#39;</strong>),<br>],</pre><p>As you see we also reconfigured the queue name along with the routing key.</p><pre><strong>‘queue’ </strong>=&gt; [</pre><pre><strong>            &#39;exchange&#39; </strong>=&gt; <strong>&#39;email.direct&#39;</strong>,<br>            <strong>&#39;exchange_type&#39; </strong>=&gt; <strong>&#39;direct&#39;</strong>,<br>            <strong>&#39;exchange_routing_key&#39; </strong>=&gt; <strong>&#39;email2&#39;</strong>,<br>            <strong>&#39;prioritize_delayed_messages&#39; </strong>=&gt;  <strong>false</strong>,<br>            <strong>&#39;queue_max_priority&#39; </strong>=&gt; 10,<br>],</pre><p>Since we have copied the project “email.service1”, we don&#39;t need to create a new listener class for this service.<br>We are done with the configuration now it’s time to test our services.</p><p>In the terminal route to the email-service1 project directory and in the terminal and run the below command:</p><pre>php artisan rabbitmq:consume</pre><p>Then open a new terminal and route to the email-service app and run the following command:</p><pre>php artisan rabbitmq:consume</pre><p>Now in both, email-service1 and email-service2, we are listening to the corresponding queues.</p><p>Now open a new terminal and route to the E-store app and run the following command to raise an OrderShipped event:</p><pre>php artisan order:ship</pre><p>Now you should have successfully received the message information in the warehouse and sales app.</p><p>By now, We are done with part 3 and the final part of our series.</p><p>In the end, I would be happy to take any suggestions about the article and the content as well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dc039d2b3c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Microservices by using Lumen & RabbitMQ —  Part 2]]></title>
            <link>https://behzadbabaei.medium.com/developing-microservices-by-using-lumen-rabbitmq-part-2-d78a0f7083d3?source=rss-e41eb158da0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d78a0f7083d3</guid>
            <category><![CDATA[lumen]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Behzad Babaei]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 21:43:11 GMT</pubDate>
            <atom:updated>2021-09-14T06:50:29.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developing Microservices by using Lumen &amp; RabbitMQ — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai_oaAL60fzhovwclrgtcg.png" /></figure><p>In the previous article, we have tested our event and now we will follow with bringing the RabbitMQ in our workflow to successfully send messages from the e-store to the warehouse and sales app.</p><p>As described in the first part of this series, when one order is created in our store, we will send the order information to the warehouse and sales app to start the process of the order.<br>We will raise an event in the e-store, then the event listener listens for that event, after capturing the event, the handler sends the message to the exchange, then the exchange sends the copy of the message to the queues that are bind to it, then consumers which are our warehouse and sales apps receives those messages and process the data.</p><p>I have added the repository links for references.<br>Estore repository:<br><a href="https://github.com/behzadbabaei/lumen-microservice-estore">https://github.com/behzadbabaei/lumen-microservice-estore</a></p><p>Warehouse repository:<br><a href="https://github.com/behzadbabaei/-lumen-microservice-warehouse.git">https://github.com/behzadbabaei/lumen-microservice-warehouse.git</a></p><p>Sales repository:<br><a href="https://github.com/behzadbabaei/-lumen-microservice-sales.git">https://github.com/behzadbabaei/lumen-microservice-sales.git</a></p><p>The first step is to configure the RabbitMQ exchanges and queues for our apps.</p><p>Once again, I assume that you have a basic understanding of RabbitMQ, And know how to create the exchanges and binding the queues to them.</p><p>Go to the RabbitMQ dashboard, then creates one fanout exchange and name it “order.fanout”, Then creates two queues named “order1.fanout”,”order2.fanout” and bind them to the “order.fanout” exchange. We created two queues because we want to bind the “order1.fanout” to the sales app and “order2.fanout” to the warehouse app.</p><p>The second step is to install the RabbitMQ package in our e-store project, for that, install the following package which is compatible with our lumen version.</p><p>Package github repository:<br><a href="https://github.com/vyuldashev/laravel-queue-rabbitmq">https://github.com/vyuldashev/laravel-queue-rabbitmq</a></p><pre>composer require vladimir-yuldashev/laravel-queue-rabbitmq:v10.2.2</pre><p>Add the following lines in the project .env file</p><pre><strong>RABBITMQ_HOST</strong>=<strong>localhost</strong><br><strong>RABBITMQ_PORT</strong>=<strong>5672</strong><br><strong>RABBITMQ_VHOST</strong>=<strong>/</strong><br><strong>RABBITMQ_LOGIN</strong>=<strong>guest</strong><br><strong>RABBITMQ_PASSWORD</strong>=<strong>guest</strong><br><strong>RABBITMQ_QUEUE</strong>=<strong>order1.fanout</strong><br><strong>RABBITMQ_EXCHANGE_NAME</strong>=<strong>order.fanout</strong><br><strong>RABBITMQ_EXCHANGE_DECLARE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_TYPE</strong>=<strong>fanout</strong><br><strong>RABBITMQ_EXCHANGE_PASSIVE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_DURABLE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_AUTODELETE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_ARGUMENTS</strong>=<strong>default</strong></pre><p>Then in the config/queue.php in the connections section add the below code( this is the RabbitMQ config)</p><pre><strong>&#39;rabbitmq&#39; </strong>=&gt; [<br>    <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;rabbitmq&#39;</strong>,<br>    <strong>&#39;queue&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_QUEUE&#39;</strong>, <strong>&#39;order1.fanout&#39;</strong>),<br>    <strong>&#39;connection&#39; </strong>=&gt; PhpAmqpLib\Connection\AMQPLazyConnection::<strong>class</strong>,<br>    <strong>&#39;hosts&#39; </strong>=&gt; [<br>        [<br>            <strong>&#39;host&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_HOST&#39;</strong>, <strong>&#39;127.0.0.1&#39;</strong>),<br>            <strong>&#39;port&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PORT&#39;</strong>, 15672),<br>            <strong>&#39;user&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_USER&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;password&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PASSWORD&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;vhost&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_VHOST&#39;</strong>, <strong>&#39;/&#39;</strong>),<br>        ],<br>    ],<br>    <strong>&#39;options&#39; </strong>=&gt; [<br>        <strong>&#39;queue&#39; </strong>=&gt; [<br>            <strong>&#39;exchange&#39; </strong>=&gt; <strong>&#39;order.fanout&#39;</strong>,<br>            <strong>&#39;exchange_type&#39; </strong>=&gt; <strong>&#39;fanout&#39;</strong>,<br>            <strong>&#39;prioritize_delayed_messages&#39; </strong>=&gt;  <strong>false</strong>,<br>            <strong>&#39;queue_max_priority&#39; </strong>=&gt; 10,<br>        ],<br>        <strong>&#39;exchange&#39; </strong>=&gt; [<br>            <strong>&#39;name&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_NAME&#39;</strong>, <strong>&#39;order.fanout&#39;</strong>),<br>            <strong>&#39;declare&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DECLARE&#39;</strong>, <strong>true</strong>),<br><br>            <strong>&#39;type&#39; </strong>=&gt; <strong>&#39;fanout&#39;</strong>,<br>            <strong>&#39;passive&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_PASSIVE&#39;</strong>, <strong>false</strong>),<br>            <strong>&#39;durable&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DURABLE&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;auto_delete&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_AUTODELETE&#39;</strong>, <strong>false</strong>),<br>            <strong>&#39;arguments&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_ARGUMENTS&#39;</strong>),<br>        ],<br>        <strong>&#39;ssl_options&#39; </strong>=&gt; [<br>            <strong>&#39;cafile&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_CAFILE&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_cert&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALCERT&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_key&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALKEY&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;verify_peer&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_VERIFY_PEER&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;passphrase&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_PASSPHRASE&#39;</strong>, <strong>null</strong>),<br>        ],<br>    ],</pre><p>Then in the bootstrap/app.php add the following line:</p><pre>$app-&gt;register(VladimirYuldashev\LaravelQueueRabbitMQ\LaravelQueueRabbitMQServiceProvider::class);</pre><p>one more step is that we need to change the default queue driver of our project, for that, we change the following config in the .env</p><pre>QUEUE_CONNECTION=rabbitmq</pre><p>by above config, we set our queue driver to RabbitMQ that we defined in the config/queue.php</p><p>we are done now with the e-store and it’s time to create the warehouse and sales app.</p><p>Warehouse app.<br>For avoiding wasting time on new lumen installation, just copy the e-store project and name it warehouse and follow the steps</p><p>- delete the OrderCreate command in the app/Console/Commands folder, then update the Kernel.php file in the app/Console and delete the command from $commands array.</p><pre>protected $commands = [ ];</pre><p>the $commands should be empty because in the consumer app we don’t need that commands</p><p>- delete the OrderCreated event in the app/Events folder we don’t need that event in the consumer project</p><p>- delete the user and order migrations from this project two we don’t need them in these apps too.</p><p>We are going to work with jobs and queues, so the job_failed is handled by the database so we need the job failed migration, so for adding that run command below in the terminal in the main project folder</p><pre>php artisan queue:failed-table</pre><p>by running that command, lumen adds the required migrations for us</p><p>then it’s time for adding the RabbitMQ configs. Since we have copied the e-store app, we don’t have to install the RabbitMQ package again, we only have to reconfigure our queue, so follow the below steps:</p><p>- add the following config in the sales .env file</p><pre><strong>RABBITMQ_HOST</strong>=<strong>localhost</strong><br><strong>RABBITMQ_PORT</strong>=<strong>5672</strong><br><strong>RABBITMQ_VHOST</strong>=<strong>/</strong><br><strong>RABBITMQ_LOGIN</strong>=<strong>guest</strong><br><strong>RABBITMQ_PASSWORD</strong>=<strong>guest</strong><br><strong>RABBITMQ_QUEUE</strong>=<strong>order1.fanout</strong><br><strong>RABBITMQ_EXCHANGE_NAME</strong>=<strong>order.fanout</strong><br><strong>RABBITMQ_EXCHANGE_DECLARE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_TYPE</strong>=<strong>fanout</strong><br><strong>RABBITMQ_EXCHANGE_PASSIVE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_DURABLE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_AUTODELETE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_ARGUMENTS</strong>=<strong>default</strong></pre><p>As you can see we assign the “order1.fanout” to this app</p><p>Now it’s time fo configuring the config/queue.php and please add the below config in the connections property in the queue.php</p><pre><strong>&#39;rabbitmq&#39; </strong>=&gt; [<br>    <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;rabbitmq&#39;</strong>,<br>    <strong>&#39;queue&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_QUEUE&#39;</strong>, <strong>&#39;order1.fanout&#39;</strong>),<br>    <strong>&#39;connection&#39; </strong>=&gt; PhpAmqpLib\Connection\AMQPLazyConnection::<strong>class</strong>,<br>    <strong>&#39;hosts&#39; </strong>=&gt; [<br>        [<br>            <strong>&#39;host&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_HOST&#39;</strong>, <strong>&#39;127.0.0.1&#39;</strong>),<br>            <strong>&#39;port&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PORT&#39;</strong>, 15672),<br>            <strong>&#39;user&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_USER&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;password&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PASSWORD&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;vhost&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_VHOST&#39;</strong>, <strong>&#39;/&#39;</strong>),<br>        ],<br>    ],<br>    <strong>&#39;options&#39; </strong>=&gt; [<br>        <strong>&#39;exchange&#39; </strong>=&gt; [<br>            <strong>&#39;name&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_NAME&#39;</strong>, <strong>&#39;order.fanout&#39;</strong>),<br>            <strong>&#39;declare&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DECLARE&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;type&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_TYPE&#39;</strong>, <strong><em>AMQP_EX_TYPE_FANOUT</em></strong>),<br>            <strong>&#39;passive&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_PASSIVE&#39;</strong>, <strong>false</strong>)<br>        ],<br>        <strong>&#39;ssl_options&#39; </strong>=&gt; [<br>            <strong>&#39;cafile&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_CAFILE&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_cert&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALCERT&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_key&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALKEY&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;verify_peer&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_VERIFY_PEER&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;passphrase&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_PASSPHRASE&#39;</strong>, <strong>null</strong>),<br>        ],<br>    ],<br>    <strong>&#39;worker&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_WORKER&#39;</strong>, <strong>&#39;default&#39;</strong>),<br>],</pre><p>and after all, you need to configure the sales app database connections( you might need to specify the database connection and DB or username and pass)</p><p>after doing the above configuration run the below commands</p><pre>php artisan cache:clear</pre><pre>composer dumpa</pre><p>we are done with the sales app and now it’s time to configure the warehouse app.<br>Configuring the warehouse app is exactly like the sale app with small changes. So just copy the sales app and name it warehouse.</p><p>Change the RabbitMQ configuration in the .env file to code below</p><pre><strong>RABBITMQ_HOST</strong>=<strong>localhost</strong><br><strong>RABBITMQ_PORT</strong>=<strong>5672</strong><br><strong>RABBITMQ_VHOST</strong>=<strong>/</strong><br><strong>RABBITMQ_LOGIN</strong>=<strong>guest</strong><br><strong>RABBITMQ_PASSWORD</strong>=<strong>guest</strong><br><strong>RABBITMQ_QUEUE</strong>=<strong>order2.fanout</strong><br><strong>RABBITMQ_EXCHANGE_NAME</strong>=<strong>order.fanout</strong><br><strong>RABBITMQ_EXCHANGE_DECLARE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_TYPE</strong>=<strong>fanout</strong><br><strong>RABBITMQ_EXCHANGE_PASSIVE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_DURABLE</strong>=<strong>true</strong><br><strong>RABBITMQ_EXCHANGE_AUTODELETE</strong>=<strong>false</strong><br><strong>RABBITMQ_EXCHANGE_ARGUMENTS</strong>=<strong>default</strong></pre><p>As you can see we have set the RabbitMQ default queue name to “order2.fanout” and now it’s bound to that queue.</p><p>Then configure the config/queue.php and the below config in the connections property</p><pre><strong>&#39;rabbitmq&#39; </strong>=&gt; [<br>    <strong>&#39;driver&#39; </strong>=&gt; <strong>&#39;rabbitmq&#39;</strong>,<br>    <strong>&#39;queue&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_QUEUE&#39;</strong>, <strong>&#39;order2.fanout&#39;</strong>),<br>    <strong>&#39;connection&#39; </strong>=&gt; PhpAmqpLib\Connection\AMQPLazyConnection::<strong>class</strong>,<br>    <strong>&#39;hosts&#39; </strong>=&gt; [<br>        [<br>            <strong>&#39;host&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_HOST&#39;</strong>, <strong>&#39;127.0.0.1&#39;</strong>),<br>            <strong>&#39;port&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PORT&#39;</strong>, 15672),<br>            <strong>&#39;user&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_USER&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;password&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_PASSWORD&#39;</strong>, <strong>&#39;guest&#39;</strong>),<br>            <strong>&#39;vhost&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_VHOST&#39;</strong>, <strong>&#39;/&#39;</strong>),<br>        ],<br>    ],<br>    <strong>&#39;options&#39; </strong>=&gt; [<br>        <strong>&#39;exchange&#39; </strong>=&gt; [<br>            <strong>&#39;name&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_NAME&#39;</strong>, <strong>&#39;order.fanout&#39;</strong>),<br>            <strong>&#39;declare&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_DECLARE&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;type&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_TYPE&#39;</strong>, <strong><em>AMQP_EX_TYPE_FANOUT</em></strong>),<br>            <strong>&#39;passive&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_EXCHANGE_PASSIVE&#39;</strong>, <strong>false</strong>)<br>        ],<br>        <strong>&#39;ssl_options&#39; </strong>=&gt; [<br>            <strong>&#39;cafile&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_CAFILE&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_cert&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALCERT&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;local_key&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_LOCALKEY&#39;</strong>, <strong>null</strong>),<br>            <strong>&#39;verify_peer&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_VERIFY_PEER&#39;</strong>, <strong>true</strong>),<br>            <strong>&#39;passphrase&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_SSL_PASSPHRASE&#39;</strong>, <strong>null</strong>),<br>        ],<br>    ],<br>    <strong>&#39;worker&#39; </strong>=&gt; env(<strong>&#39;RABBITMQ_WORKER&#39;</strong>, <strong>&#39;default&#39;</strong>),<br>],</pre><p>After doing the above configuration run the below commands</p><pre>php artisan cache:clear</pre><pre>composer dumpa</pre><p>we have configured the RabbitMq in our e-store and warehouse and sales app, so it’s time to test them.</p><p>In the terminal route to the sales project director and in run the terminal and run the below commands</p><pre>php artisan rabbitmq:consume</pre><p>the open new terminal and route to the warehouse app and run the following commands:</p><pre>php artisan rabbitmq:consume</pre><p>Now in the both, warehouse and the sales app, we are listening to the corresponding queues.<br>Now open a new terminal and route to the e-store app and run the following command to raise an event</p><pre>php artisan order:create</pre><p>Now you should have successfully received the message information in the warehouse and sales app.</p><p>By now, We are done with part 2 of our series, In the following article, we will cover the direct exchange and develop our email services.</p><p>In the end, I would be happy to take any suggestions about the article and the content as well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d78a0f7083d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Microservices by using Lumen & RabbitMQ — Part 1]]></title>
            <link>https://behzadbabaei.medium.com/developing-microservices-by-using-lumen-rabbitmq-part-1-ad6a77f0e812?source=rss-e41eb158da0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6a77f0e812</guid>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[lumen]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Behzad Babaei]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 21:25:30 GMT</pubDate>
            <atom:updated>2021-09-15T11:41:36.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developing Microservices by using Lumen &amp; RabbitMQ — Part 1</h3><p>In the following series, I would present the way to develop a simple microservice architecture by using Lumen and RabbitMQ Message broker.</p><p>To grasp the purpose of these series, understanding the basics of lumen, events, and also RabbitMQ is required.</p><h4>What is RabbitMQ?</h4><p>RabbitMQ is the most widely deployed open-source message broker. This message broker can be used for sending and receiving messages from one application to the other applications.</p><p>For more information please visit:</p><p><a href="https://www.rabbitmq.com/">https://www.rabbitmq.com/</a></p><h4>RabbitMQ Fundamentals:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*H4iY5e9eWzkzJex8E0tMpQ.png" /></figure><p>Producer: A producer is a user application that sends messages to the consumers.</p><h4>Consumer:</h4><p>A consumer is a user application that receives messages.</p><h4>Message:</h4><p>It’s a simple serialized object from the producer!</p><h4>Exchange:</h4><p>An exchange is a very simple thing. On one side it receives messages from producers and the other side pushes them to queues. This is a place that messages come first and its main purpose is to decide which consumer application, the message should go to!</p><h4>Queue:</h4><p>A queue is a buffer that stores messages. Basically, the exchange routes the message to queues, then the consumer clients receive messages from the queue. we have queues as many as the consumer’s applications!</p><p>As it’s depicted in the image above, the producers send the message to the exchange first, the exchange decides which queues, the message should go. The RabbitMQ works between the producer and consumers.</p><h4>Types of exchanges in RabbitMQ:</h4><h4>Fanout</h4><p>Fanout exchange basically sends a copy of messages to all the queues it knows. (in the dashboard every queue should be bonded to one exchange)</p><h4>Direct</h4><p>A direct exchange delivers messages to queues based on a message routing key. The routing key is a message attribute added to the message header by the producer. Think of the routing key as an “address” that the exchange is using to decide how to route the message.</p><h4>Topic</h4><p>Topic exchanges route messages to one or many queues based on matching between a message routing key and the pattern that was used to bind a queue to an exchange</p><h4>Headers</h4><p>A header exchange is an exchange that route messages to queues based on message header values instead of routing key. … If a match is found, it routes the message to the queue whose binding value is matched and if a match is not found, it ignored the message.</p><h4>What we are going to do?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai_oaAL60fzhovwclrgtcg.png" /></figure><p>We are going to cover the fanout and direct exchange in this series.</p><p>We are going to develop a simple microservice architecture that consists of 4 microservice, in which these services are covering the one eCommerce store functionalities.</p><p>On our store we assume that one user creates an order, then one event is raised that events handle the sending the required information to other microservices like the warehouse app, sales app, email notification services. In this approach, we are sending the messages to other apps in an asynchronous manner and one benefit of this approach is, the user does not have to wait for the response for the other apps and This is the power that rabbitMq gives us.</p><p>We assume one user has purchased one product on our website, then we have to notify the corresponding apps or APIs like the warehouse app and the sales app, we do this by raising the OrderCreated event, then the event handler sends the order information to other application by using RabbitMQ. For this purpose, we are going to use the Fanout exchange. When the order is shipped, then we are going to send the notification to the user by email, for this task, we are going to use Direct exchange with email service.</p><p>In the beginning, we are going to create a simple service using lumen version 7.0 which simply raises an event then logs the data, later on, we step by step change our services to use RabbitMQ to achieve our goal.</p><h3>Let’s start!</h3><p>I assumed you have installed the RabbitMQ on your systems or you have cloud service for following up with these series!</p><ul><li>Create a lumen project and name it E-Store.</li></ul><pre>composer create-project — prefer-dist laravel/lumen estore</pre><ul><li>After installation is completed, in the bootstrap/app.php file uncomment the line</li></ul><pre>$app→register(App\Providers\EventServiceProvider::class);</pre><ul><li>Then create two migrations for Order and User Model</li><li>run the below command:</li></ul><pre>php artisan make:migration create_users_table</pre><ul><li>Then put the below code in the migration file</li></ul><pre>$table-&gt;id();<br>$table-&gt;string(<strong>&#39;name&#39;</strong>);<br>$table-&gt;string(<strong>&#39;email&#39;</strong>)-&gt;<strong>unique</strong>();<br>$table-&gt;timestamp(<strong>&#39;email_verified_at&#39;</strong>)-&gt;<strong>nullable</strong>();<br>$table-&gt;string(<strong>&#39;password&#39;</strong>);<br>$table-&gt;rememberToken();<br>$table-&gt;timestamps();</pre><ul><li>Run the below command:</li></ul><pre>php artisan make:migration create_orders_table</pre><ul><li>Then put the below code in the migration file</li></ul><pre>$table-&gt;id();<br>$table-&gt;unsignedInteger(<strong>&#39;user_id&#39;</strong>)-&gt;<strong>default</strong>(1);<br>$table-&gt;string(<strong>&#39;product_name&#39;</strong>)-&gt;<strong>default</strong>(<strong>&#39;item 1&#39;</strong>);<br>$table-&gt;decimal(<strong>&#39;quantity&#39;</strong>)-&gt;<strong>default</strong>(1);<br>$table-&gt;decimal(<strong>&#39;total_price&#39;</strong>)-&gt;<strong>default</strong>(1);<br>$table-&gt;timestamps();</pre><ul><li>The migration for failed jobs also requires so run following command</li></ul><pre>php artisan queue:failed-table</pre><ul><li>And finally, run:</li></ul><pre>php artisan migrate</pre><ul><li>populates the tables with some dummy data or you could create a seeder for this task.</li></ul><p>Now we should configure our first event</p><p>In the app/Providers/EventServiceProvider</p><ul><li>Add the below code in the $listen array</li></ul><pre>\App\Events\OrderCreated::<strong>class </strong>=&gt; [<br>    \App\Listeners\OrderCreatedListener::<strong>class</strong>,<br>],</pre><ul><li>Create a class named OrderCreated (extends Event class) in the app/Events folder and put the below code in it</li></ul><pre><strong>class </strong>OrderCreated <strong>extends </strong>Event<br>{<br>    <strong>public $order</strong>;<br>    <strong>public function </strong>__construct(Order $order)<br>    {<br>        $this-&gt;<strong>order </strong>= $order;<br>    }<br>}</pre><ul><li>Then we should create a listener class for our event. In the app/Listeners create one class and name it OrderCreatedListener and put the below code in that class.</li></ul><pre><strong>namespace </strong>App\Listeners;<br><strong>use </strong>Illuminate\Contracts\Queue\ShouldQueue;<br><strong>use </strong>Log;<br><strong>class </strong>OrderCreatedListener <strong>implements </strong>ShouldQueue<br>{<br>    <br>    <strong>public function </strong>__construct()<br>    {<br>    <br>    }<br>        <br>    <strong>public function </strong>handle($event)<br>    {<br>        Log::<em>info</em>(<strong>&#39;Order created on estore:&#39; </strong>. <em>json_encode</em>($event));<br>    }<br>}</pre><p>We just simply are logging the event data nothing fancy in it.<br>For testing our event and listener I’m going to create a command(you could do whatever is convenient for you, perhaps creating one controller to test it).</p><p>In the app/Console/Commands creates a class named CreateOrder,<br>then put the content below in it.</p><pre><strong>namespace </strong>App\Console\Commands;<br><strong>use </strong>App\Order;<br><strong>use </strong>Illuminate\Console\Command;<br><strong>class </strong>CreateOrder <strong>extends </strong>Command<br>{<br>    <strong>protected $signature </strong>= <strong>&#39;order:create&#39;</strong>;<br>    <br>    <strong>protected $description </strong>= <strong>&#39;Create an order&#39;</strong>;<br>    <br>    <strong>public function </strong>__construct()<br>    {<br>        <strong>parent</strong>::<em>__construct</em>();<br>    }<br>    <br>    <strong>public function </strong>handle()<br>    {<br>        $order = Order::<em>with</em>(<strong>&#39;user&#39;</strong>)-&gt;inRandomOrder()-&gt;first();<br>        event(<strong>new </strong>\App\Events\OrderCreated($order));<br>        <strong>return </strong>0;<br>    }<br>}</pre><p>Now we should add our command to the available commands handler in our project. For this in the Kernel.php file in the app/Console folder put the line below in the $commands array like below (also import the class)</p><pre><strong>protected $commands </strong>= [<br>    CreateOrder::<strong>class</strong><br>];</pre><p>For the beginning of this project, you can use any queue driver like( we are going to change it and use rabbit in the future)<br>For configuring the queue copy the vendor/laravel/config/queue.php to config/queue.php (if config folder does not exist in your project creates it);</p><ul><li>Now in the bootstrapp/app.php file, add the below line</li></ul><pre>$app→configure(&#39;queue&#39;);</pre><p>Everything is ready, now we can test our event. First, in your project open the terminal and run:</p><pre>php artisan queue:work</pre><ul><li>Then run the below code in another terminal:</li></ul><pre>php artisan order:create </pre><p>In the line above we running our order to create a command that we created a few steps back. Now look at the log file and it should be working fine!<br><br>Until now we were just setting up everything necessary for starting our main task, Now we are ready for stepping forward and creates our microservices.</p><p>By now, We are done with part 1 of our series, In the following article, we will cover the fanout exchange and develop our warehouse and sales app.</p><p>In the end, I would be happy to take any suggestions about the article and the content as well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6a77f0e812" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a microservices & Api gateway by using Lumen]]></title>
            <link>https://behzadbabaei.medium.com/creating-a-microservices-api-gateway-by-using-lumen-efdb63212e18?source=rss-e41eb158da0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/efdb63212e18</guid>
            <category><![CDATA[lumen]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Behzad Babaei]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 14:43:34 GMT</pubDate>
            <atom:updated>2020-03-28T14:43:34.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wlrVzmhOioc3PFbuic2tg.png" /></figure><p>In this article, I will explain a simple api gateway architecture in the microservice environment, this article shows how we can use this pattern for exposing our services to external consumers.</p><p>Api gateway is not a new term, but it‘s still a little fuzzy for new starters to grasp the terminology or how they could really use this pattern to solve their problem.</p><p>But What is an API Gateway?</p><p>I have come across many definitions and you might have your own definition too, So I would say: API Gateways is a single, unified API entry point across one or more internal APIs, that’s it!</p><p>You may have many internal microservice in which each one has some responsibility and actually do something in your echo systems, but you dont want them to be exposed to the outside world, instead, you want one single entry point which talks and interact with the internal services, and clients talks to that entry point which is the API gateway.</p><p>And Why Do Microservices Need an API Gateway?</p><p>- Using api gateways will help us to prevent the exposure of our internal services to the external world and clients.</p><p>- By using api gateways we could provide routing for the external request to internal microservices</p><p>- Api gateway adds one layer so it helps to prevent malicious attacks like SQL Injection, DoS attacks. Api gateways can also be used as an authorization layer to control the clients over the resources.</p><p>- Using api gateways will decrease the complexity, for example, every service might need and authorization or access control which it adds more time for development.using gateway can remove these concerns.</p><p>by unifying all entry points to the internal services, you can have many capabilities such as analytics, lifecycle management, auditing and many other capabilities.</p><p>Let‘s talk about what we are going to build.</p><p>All of the projects are developed using Lumen micro-framework version 5.7. I will not explain or train the Lumen and I assume you are already familiar with Lumen and have hands on it!</p><p>I have put all the source code on git so you could clone the projects and follow the article with the project samples for better understanding the article and project that we are trying to build.</p><p>Products Api</p><p><a href="https://gitlab.com/behzadbabaei69/microserviceproductsapi.git">https://gitlab.com/behzadbabaei69/microserviceproductsapi.git</a></p><p>Orders Api</p><p><a href="https://gitlab.com/behzadbabaei69/microserviceordersapi.git">https://gitlab.com/behzadbabaei69/microserviceordersapi.git</a></p><p>API gateway</p><p><a href="https://gitlab.com/behzadbabaei69/microserviceapigateway.git">https://gitlab.com/behzadbabaei69/microserviceapigateway.git</a></p><p>take look at the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wlrVzmhOioc3PFbuic2tg.png" /></figure><p>In this scenario, we have some internal microservices on the right which includes 2 microservice, product &amp; order service.in the middle, we have an api gateway which we use for authorization and also routing the request to the internal microservices, by doing so, we have also access control layer over the client’s requests and what has requested. On the left side, we have a different client who will consume our APIs. A client could be any sort of application web or mobile app.</p><p>This is a very simple scenario, we want to accomplish two things here:</p><p>1.exposeing our desired services to the outside world</p><p>2. protect our internal microservices from external clients</p><p>All the clients for consuming our services would interact with our api gateway. For authorize request in api gateway, we use oAuth2 and for this purpose, we would use a lumen passport package.</p><p>Now our internal services are not protected, so for that, we would implement a secret key mechanism. It means when an api gateway wants to call one internal microservice, it has to embed a secret key in the request header as Authorization and that key has to be among allowed secret keys in that service, in that manner we authorize the request from api gateway to internal microservices.</p><p>Let’s start building our services first, we start with the Product service.</p><p>We use lumen version 5.7 for developing all the services and for simplicity, our services perform only CRUD operations.</p><p>Let’s walk throughout the process of creating the ProductsApi.</p><p>Product Service:</p><p>Step 1: create a project lumen for product api name it ProductsApi (for this use lumen official website)</p><p>Step 2: uncomment the below 2 lines in bootstrap/app.php file for using Facades and Eloquent.</p><pre>$app-&gt;withFacades();<br>$app-&gt;withEloquent();</pre><p>Step 3: add all routes in web.php in routes/web.php for crud operations</p><pre>$router-&gt;group([<strong>&#39;prefix&#39; </strong>=&gt; <strong>&#39;api&#39;</strong>], <strong>function </strong>() <strong>use </strong>($router) {<br>    $router-&gt;group([<strong>&#39;prefix&#39; </strong>=&gt; <strong>&#39;product&#39;</strong>], <strong>function </strong>() <strong>use </strong>($router) {<br>        $router-&gt;get(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@index&#39;</strong>]);<br>        $router-&gt;post(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@store&#39;</strong>]);<br>        $router-&gt;get(<strong>&#39;/{product}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@show&#39;</strong>]);<br>        $router-&gt;patch(<strong>&#39;/{product}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@update&#39;</strong>]);<br>        $router-&gt;delete(<strong>&#39;/{product}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@destroy&#39;</strong>]);<br>    });<br>});</pre><p>We would create one trait for unifying responses in our api, so in the app folder, create a “Traits” folder, then create one trait and name it ApiResponse and put below code in these traits (Do not forget about namespaces).</p><pre><strong>trait </strong>ApiResponse<br>{<br>    <strong>public function </strong>successResponse($data, $statusCode = Response::<strong><em>HTTP_OK</em></strong>)<br>    {<br>        <strong>return </strong>response()-&gt;json([<strong>&#39;data&#39; </strong>=&gt; $data], $statusCode);<br>    }<br>    <strong>public function </strong>errorResponse($errorMessage, $statusCode)<br>    {<br>        <strong>return </strong>response()-&gt;json([<strong>&#39;error&#39; </strong>=&gt; $errorMessage, <strong>&#39;error_code&#39; </strong>=&gt; $statusCode], $statusCode);<br>    }<br>}</pre><p>After creating traits, use it in the Controller.php class in the app/Http/Controllers folder.</p><pre><strong>class </strong>Controller <strong>extends </strong><em>BaseController</em><br>{<br>    <strong>use </strong>ApiResponse;<br>}</pre><p>Just Like That!<br>Step 4: now its time for database configuration and our tables migrations.<br>We only have one model in this microservice which is named Product, first create a database and set the required credential in .env file for accessing the database. I would use MySQL as my database.<br>so first create a migration for Product table by executing the following command:<br>php artisan make:migration --create=products create_products_table<br>our product has a simple scheme and has only two fields: name, price.</p><pre>Schema::<em>create</em>(<strong>&#39;products&#39;</strong>, <strong>function </strong>(Blueprint $table) {<br>    $table-&gt;increments(<strong>&#39;id&#39;</strong>);<br>    $table-&gt;string(<strong>&#39;name&#39;</strong>)-&gt;nullable();<br>    $table-&gt;decimal(<strong>&#39;price&#39;</strong>)-&gt;nullable();<br>    $table-&gt;timestamps();<br>});</pre><p>We also need seed data for testing our APIs so for that we use Factory facade in the lumen.in database/factories/ModelFactory.php file edit the factory as below:</p><pre>$factory-&gt;define(App\Product::<strong>class</strong>, <strong>function </strong>(Faker\Generator $faker) {<br>    <strong>return </strong>[<br>        <strong>&#39;name&#39; </strong>=&gt; $faker-&gt;<strong>userName</strong>,<br>        <strong>&#39;price&#39; </strong>=&gt; $faker-&gt;numberBetween(10,200),<br>    ];<br>});</pre><p>then in database/seeds/DatabaseSeeder.php class add the following code for creating 50 sample records for our product tables (you can edit it as you desire)!</p><pre>factory(\App\Product::<strong>class</strong>, 50)-&gt;create();</pre><p>Step 5: create a model named Product and in the app folder (there is a User model as default so remove it!).please add fillable fields too.</p><pre><strong>protected $fillable </strong>= [<br>    <strong>&#39;name&#39;</strong>, <strong>&#39;price&#39;</strong><br>];</pre><p>Step 6:create a controller named ProductController and create all the functions required for mentioned routes in step 3</p><pre><strong>public function </strong>index(){...}<br><br><strong>public function </strong>show($product){...}<br><br><strong>public function </strong>store(Request $request){...}<br><br><strong>public function </strong>update(Request $request, $product){...}<br><br><strong>public function </strong>destroy($product){...}</pre><p>Step 7: test all the mentioned routes in step 3 using postman or any other test tools which you are fine with.</p><p>Our product service is complete now we procced to Order Service and creation of order service is like Product service.</p><p>Repeat step 1&amp;2 but name this service OrdersService</p><p>Step 3: for creating a required route in our microservice, put the below code in the routes/web.php</p><pre>$router-&gt;group([<strong>&#39;prefix&#39; </strong>=&gt; <strong>&#39;api&#39;</strong>], <strong>function </strong>() <strong>use </strong>($router) {<br>    $router-&gt;group([<strong>&#39;prefix&#39; </strong>=&gt; <strong>&#39;order&#39;</strong>], <strong>function </strong>() <strong>use </strong>($router) {<br>        $router-&gt;get(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@index&#39;</strong>]);<br>        $router-&gt;post(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@store&#39;</strong>]);<br>        $router-&gt;get(<strong>&#39;/{order}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@show&#39;</strong>]);<br>        $router-&gt;patch(<strong>&#39;/{order}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@update&#39;</strong>]);<br>        $router-&gt;delete(<strong>&#39;/{order}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@destroy&#39;</strong>]);<br>    });<br>});</pre><p>For a response just copy the ApiResponse trait we created in the previous microservice and put it in the app folder and then use that trait in Controller class.</p><p>Step 4: Create a migration for the orders table and then create the seed data and change the factory too.</p><p>php artisan make:migration — create=orders create_orders_table</p><pre>Schema::<em>create</em>(<strong>&#39;orders&#39;</strong>, <strong>function </strong>(Blueprint $table) {<br>    $table-&gt;increments(<strong>&#39;id&#39;</strong>);<br>    $table-&gt;integer(<strong>&#39;quantity&#39;</strong>)-&gt;unsigned();<br>    $table-&gt;decimal(<strong>&#39;total_price&#39;</strong>)-&gt;unsigned();<br>    $table-&gt;decimal(<strong>&#39;discount&#39;</strong>)-&gt;unsigned()-&gt;default(0);<br>    $table-&gt;integer(<strong>&#39;product_id&#39;</strong>)-&gt;unsigned();<br>    $table-&gt;timestamps();<br>});</pre><p>Step 5: create a model named Order in the app folder (there is a User model as default so remove it!) then add the fillable fields too.</p><pre><strong>protected $fillable </strong>= [<br>    <strong>&#39;quantity&#39;</strong>,<br>    <strong>&#39;discount&#39;</strong>,<br>    <strong>&#39;total_price&#39;</strong>,<br>    <strong>&#39;product_id&#39;</strong><br>];</pre><p>Step 6:create a controller named ProductController and create all the functions for mentioned routes in step 3</p><pre><strong>public function </strong>index(){...}<br><br><strong>public function </strong>show($order){...}<br><br><strong>public function </strong>store(Request $request){...}<br><br><strong>public function </strong>update(Request $request, $order){...}<br><br><strong>public function </strong>destroy($order){…}</pre><p>Step 7: test all the mentioned routes in step 3 using postman or any other test tools which you are fine with.</p><p>Until this moment we had only developed two services which work separate and we have tested all the functionality that we needed! (I hope you have tested your Api&#39;s).<br>Now it‘s time to explain the API gateway.</p><p>Repeat steps 1 &amp; 2 in the previous microservices but name this project ApiGateway. Our api gateway can be used for authorization too so for that, we would use a lumen passport package.</p><p>Install the lumen passport package in the ApiGateway project and after installing the package and its configuration, we could proceed with our api gateway.<br><br>step 3:<br>Step 3 is a little long so please bear with me till the end. I explained earlier for protecting our internal services, api gateway has to use the secret key mechanism, in this approach, api gateway for consuming each one of our internal services would have to provide a secret key as Authorization param in request headers.</p><p>We would like to authorize the request from clients in our gateways so in bootstrap/app.php add the following code for route middleware.</p><pre>$app-&gt;routeMiddleware([<br>    <strong>&#39;auth&#39; </strong>=&gt; App\Http\Middleware\Authenticate::<strong>class</strong>,<br>    <strong>&#39;client.credentials&#39; </strong>=&gt; \Laravel\Passport\Http\Middleware\CheckClientCredentials::<strong>class</strong>,<br>]);</pre><p>As we said before, our gateway would also route the requests to the internal microservices, so in routes/web.php add following routes:</p><pre>$router-&gt;group([<strong>&#39;prefix&#39; </strong>=&gt; <strong>&#39;api&#39;</strong>, <strong>&#39;middleware&#39; </strong>=&gt; [<strong>&#39;client.credentials&#39;</strong>]], <strong>function </strong>() <strong>use </strong>($router) {<br>    $router-&gt;group([<strong>&#39;prefix&#39; </strong>=&gt; <strong>&#39;product&#39;</strong>], <strong>function </strong>() <strong>use </strong>($router) {<br>        $router-&gt;get(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@index&#39;</strong>]);<br>        $router-&gt;post(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@store&#39;</strong>]);<br>        $router-&gt;get(<strong>&#39;/{product}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@show&#39;</strong>]);<br>        $router-&gt;patch(<strong>&#39;/{product}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@update&#39;</strong>]);<br>        $router-&gt;delete(<strong>&#39;/{product}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;ProductController@destroy&#39;</strong>]);<br>    });<br>    $router-&gt;group([<strong>&#39;prefix&#39; </strong>=&gt; <strong>&#39;order&#39;</strong>], <strong>function </strong>() <strong>use </strong>($router) {<br>        $router-&gt;get(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@index&#39;</strong>]);<br>        $router-&gt;post(<strong>&#39;/&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@store&#39;</strong>]);<br>        $router-&gt;get(<strong>&#39;/{order}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@show&#39;</strong>]);<br>        $router-&gt;patch(<strong>&#39;/{order}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@update&#39;</strong>]);<br>        $router-&gt;delete(<strong>&#39;/{order}&#39;</strong>, [<strong>&#39;uses&#39; </strong>=&gt; <strong>&#39;OrderController@destroy&#39;</strong>]);<br>    });<br>});</pre><p>We would use ApiResponse that we created in previous services but with a little change to get the Errors from internal services and returning them to the clients.</p><pre><strong>trait </strong>ApiResponse<br>{<br>    <strong>public function </strong>successResponse($data, $statusCode = Response::<strong><em>HTTP_OK</em></strong>)<br>    {<br>        <strong>return </strong>response($data, $statusCode)-&gt;header(<strong>&#39;Content-Type&#39;</strong>, <strong>&#39;application/json&#39;</strong>);<br>    }<br>    <strong>public function </strong>errorResponse($errorMessage, $statusCode)<br>    {<br>        <strong>return </strong>response()-&gt;json([<strong>&#39;error&#39; </strong>=&gt; $errorMessage, <strong>&#39;error_code&#39; </strong>=&gt; $statusCode], $statusCode);<br>    }<br>    <strong>public function </strong>errorMessage($errorMessage, $statusCode)<br>    {<br>        <strong>return </strong>response($errorMessage, $statusCode)-&gt;header(<strong>&#39;Content-Type&#39;</strong>, <strong>&#39;application/json&#39;</strong>);<br>    }<br>}</pre><p>As every microservice should be independent and they reside in their own server, so for interacting with them, we need to know where they reside. We would basically run our microservices on a different port like product service on localhost:8100 and order service on localhost:8200 and API gateway on localhost:8000.every internal microservice is protected with a secret key, it means when api gateway wants to call an api on any internal microservice, it should imbed that secret key as Authorization header on request, so in that way we authorize the requests from API gateway to internal microservices.so here we put the address of microservices and their secret_key in .env files.<br><br>Create 4 parameters on the .env file in api gateways. Like bellow:</p><pre><strong>PRODUCTS_SERVICE_BASE_URI</strong>=<strong>http://localhost:8100/api</strong><br><strong>PRODUCTS_SERVICE_SECRET</strong>=mysecret1<br><strong>ORDERS_SERVICE_BASE_URI</strong>=<strong>http://localhost:8200/api</strong><br><strong>ORDERS_SERVICE_SECRET</strong>=mysecret2</pre><p>Now we create one config file for getting settings via lumen config facades. So in the root directory of the project create a config folder and then create a file named services.php and put the content below on it.</p><pre><strong>return </strong>[<br>    <strong>&#39;products&#39; </strong>=&gt; [<br>        <strong>&#39;base_uri&#39; </strong>=&gt; env(<strong>&#39;PRODUCTS_SERVICE_BASE_URI&#39;</strong>),<br>        <strong>&#39;secret&#39; </strong>=&gt; env(<strong>&#39;PRODUCTS_SERVICE_SECRET&#39;</strong>)<br>    ],<br>    <strong>&#39;orders&#39; </strong>=&gt; [<br>        <strong>&#39;base_uri&#39; </strong>=&gt; env(<strong>&#39;ORDERS_SERVICE_BASE_URI&#39;</strong>),<br>        <strong>&#39;secret&#39; </strong>=&gt; env(<strong>&#39;ORDERS_SERVICE_SECRET&#39;</strong>),<br>    ]<br>];</pre><p>on the bootstrap/app.php file add the following code</p><pre>$app-&gt;configure(<strong>&#39;services&#39;</strong>);</pre><p>after the line:</p><pre>$app-&gt;withEloquent();</pre><p>This was one side of the configuration, we need a mechanism for authorization on the internal microservices side, For that, we create a middleware and enforce every route to go through this middleware and every request that comes in from api gateway too, So in both Product and Order microservices, create a middleware named AuthenticateAccess inside the app/Http/Middleware folder and then put the content below on those class &quot;handle&quot; function.</p><pre><strong>public function </strong>handle($request, Closure $next)<br>{<br>    $allowedSecrets = <em>explode</em>(<strong>&#39;,&#39;</strong>, env(<strong>&#39;ALLOWED_SECRETS&#39;</strong>));<br>    <strong>if </strong>(<em>in_array</em>($request-&gt;header(<strong>&#39;Authorization&#39;</strong>), $allowedSecrets)) {<br>        <strong>return </strong>$next($request);<br>    }<br>    abort(Response::<strong><em>HTTP_UNAUTHORIZED</em></strong>);<br>}</pre><p>In Api gateway we had a secret for every service on .env file, now on every microservice, we have to keep that secret somewhere to check if secret matches, so in Product service, we add one parameter named ALLOWED_SECRETS in .env file. as it‘s an array, we could have multiple secrets, as you see we here, we check if the Authorization is set on the header and we compare it against the allowed secrets in .env file, and if they match we would proceed with to next part.</p><p>Remember that the allowed secret should match the secret keys in the Api gateway .env file parameters (PRODUCTS_SERVICE_SECRET, ORDERS_SERVICE_SECRET).</p><p>We should have this middleware for both Order and Product service. After adding middlewares, we need to activate them. So in product service on bootstrap/app.php uncomment the middleware part and add code below. by using app-&gt;middleware we would enforce every request to go through this authorization middleware.</p><pre>$app-&gt;middleware([<br>    App\Http\Middleware\AuthenticateAccess::<strong>class</strong><br>]);</pre><p>Now it‘s time to create our services in api gateway which are responsible for interacting with internal microservices. Their job is to consume the internal microservices and get the result from those services and return them to the clients. We have to create one trait and by using that, we can make a request to internal services. Create a trait named RequestService and put the content below on that trait:</p><pre><strong>public function </strong>request($method, $requestUrl, $formParams = [], $headers = [])<br>{<br>    $client = <strong>new </strong>Client([<br>        <strong>&#39;base_uri&#39; </strong>=&gt; $this-&gt;<strong>baseUri</strong><br>    ]);<br>    <strong>if </strong>(<strong>isset</strong>($this-&gt;<strong>secret</strong>)) {<br>        $headers[<strong>&#39;Authorization&#39;</strong>] = $this-&gt;<strong>secret</strong>;<br>    }<br>    $response = $client-&gt;request($method, $requestUrl,<br>        [<br>            <strong>&#39;form_params&#39; </strong>=&gt; $formParams,<br>            <strong>&#39;headers&#39; </strong>=&gt; $headers<br>        ]<br>    );<br>    <strong>return </strong>$response-&gt;getBody()-&gt;getContents();<br>}</pre><p>We have two microservices so here we would create two services named OrderService, ProductService inside the app/Services folder. inside the Product, service add code below in that class.</p><pre><strong>class </strong>ProductService<br>{<br>    <strong>use </strong>RequestService;<br>    <strong>public $baseUri</strong>;<br>    <strong>public $secret</strong>;<br>    <strong>public function </strong>__construct()<br>    {<br>        $this-&gt;<strong>baseUri </strong>= config(<strong>&#39;services.products.base_uri&#39;</strong>);<br>        $this-&gt;<strong>secret </strong>= config(<strong>&#39;services.products.secret&#39;</strong>);<br>    }<br>    <strong>public function </strong>fetchProducts()<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;GET&#39;</strong>, <strong>&#39;/api/product&#39;</strong>);<br>    }<br>    <strong>public function </strong>fetchProduct($product)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;GET&#39;</strong>, <strong>&quot;/api/product/</strong>{$product}<strong>&quot;</strong>);<br>    }<br>    <strong>public function </strong>createProduct($data)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;POST&#39;</strong>, <strong>&#39;/api/product&#39;</strong>, $data);<br>    }<br>    <strong>public function </strong>updateProduct($product, $data)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;PATCH&#39;</strong>, <strong>&quot;/api/product/</strong>{$product}<strong>&quot;</strong>, $data);<br>    }<br>    <strong>public function </strong>deleteProduct($product)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;DELETE&#39;</strong>, <strong>&quot;/api/product/</strong>{$product}<strong>&quot;</strong>);<br>    }<br>}</pre><p>Now we would also need to create another service for OrderService, so create another class named OrderService and put the code below in that class:</p><pre><strong>class OrderService</strong><br>{<br>    <strong>use </strong>RequestService;<br>    <strong>public $baseUri</strong>;<br>    <strong>public $secret</strong>;<br>    <strong>public function </strong>__construct()<br>    {<br>        $this-&gt;<strong>baseUri </strong>= config(<strong>&#39;services.orders.base_uri&#39;</strong>);<br>        $this-&gt;<strong>secret </strong>= config(<strong>&#39;services.orders.secret&#39;</strong>);<br>    }<br>    <strong>public function </strong>fetchOrders()<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;GET&#39;</strong>, <strong>&#39;/api/order&#39;</strong>);<br>    }<br>    <strong>public function </strong>fetchOrder($order)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;GET&#39;</strong>, <strong>&quot;/api/order/</strong>{$order}<strong>&quot;</strong>);<br>    }<br>    <strong>public function </strong>createOrder($data)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;POST&#39;</strong>, <strong>&#39;/api/order&#39;</strong>, $data);<br>    }<br>    <strong>public function </strong>updateOrder($order, $data)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;PATCH&#39;</strong>, <strong>&quot;/api/order/</strong>{$order}<strong>&quot;</strong>, $data);<br>    }<br>    <strong>public function </strong>deleteOrder($order)<br>    {<br>        <strong>return </strong>$this-&gt;request(<strong>&#39;DELETE&#39;</strong>, <strong>&quot;/api/order/</strong>{$order}<strong>&quot;</strong>);<br>    }<br>}</pre><p>As you see, we are only calling the different internal APIs and returning the result from them by using RequestService trait.</p><p>We are almost done. we have created all the required services and we also have set all the configuration required on the API gateway and internal microservices as well.</p><p>The last step is creating the controllers on the API gateway for Order and Product routes.so we start with the Product controller.<br>Create a controller named Product controller and put the content below on that controller:</p><pre><strong>class ProductController extends Controller</strong><br>{<br>    <strong>private $productService</strong>;<br>    <strong>public function </strong>__construct(ProductService $productService)<br>    {<br>        $this-&gt;<strong>productService </strong>= $productService;<br>    }<br>    <strong>public function </strong>index()<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>productService</strong>-&gt;fetchProducts());<br>    }<br>    <strong>public function </strong>show($product)<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>productService</strong>-&gt;fetchProduct($product));<br>    }<br>    <strong>public function </strong>store(Request $request)<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>productService</strong>-&gt;createProduct($request-&gt;all()));<br>    }<br>    <strong>public function </strong>update(Request $request, $product)<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>productService</strong>-&gt;updateProduct($product, $request-&gt;all()));<br>    }<br>    <strong>public function </strong>destroy($product)<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>productService</strong>-&gt;deleteProduct($product));<br>    }<br>}</pre><p>As you see nothing fancy about the code, we are only using the services in api gateway that we created earlier and those services call the internal microservices and return the result. for order, please create another controller named OrderController and put the content below in that controller:</p><pre><strong>class OrderController extends Controller</strong><br>{<br>    <strong>private $orderService</strong>;<br>    <strong>private $productService</strong>;<br>    <strong>public function </strong>__construct(OrderService $orderService, ProductService $productService)<br>    {<br>        $this-&gt;<strong>orderService </strong>= $orderService;<br>        $this-&gt;<strong>productService </strong>= $productService;<br>    }<br>    <strong>public function </strong>index()<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>orderService</strong>-&gt;fetchOrders());<br>    }<br>    <strong>public function </strong>show($order)<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>orderService</strong>-&gt;fetchOrder($order));<br>    }<br>    <strong>public function </strong>store(Request $request)<br>    {<br>        $result = $this-&gt;<strong>productService</strong>-&gt;fetchProduct($request-&gt;<strong>product_id</strong>);<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>orderService</strong>-&gt;createOrder($request-&gt;all()));<br>    }<br>    <strong>public function </strong>update(Request $request, $order)<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>orderService</strong>-&gt;updateOrder($order, $request-&gt;all()));<br>    }<br>    <strong>public function </strong>destroy($order)<br>    {<br>        <strong>return </strong>$this-&gt;successResponse($this-&gt;<strong>orderService</strong>-&gt;deleteOrder($order));<br>    }<br>}</pre><p>Note: As you see on the store function we check if the product exists in the product and if it does not exist we would return and appropriate error for the client.</p><p>At this point our architecture is complete and we are ready to test our api gateway. There is nothing fancy about this approach, we are only creating one api gateway which is responsible for redirecting the api calls from outside to correspondent internal microservices or return the result from those microservices to the clients.</p><p>Perhaps the business in the real world is more complex than what i presented here. Authorization might be much more complicated in gateways. I think this article would help to grasp the idea behind the concept of api gateways and microservices.<br><br>In the end, I would be happy to take any suggestions about the article and the content as well!</p><p>Thanks for your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efdb63212e18" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>