Jyrone Parker

Create A Real-Time Microservice With Lumen

[callaction url=”https://www.youtube.com/user/JPlaya01″ background_color=”#333333″ text_color=”#ffffff” button_text=”Go Now” button_background_color=”#e64429″]Subscribe To My Youtube Page[/callaction]

What Is Lumen?

Lumen is microframework provided by Laravel. I use it all the time when I need to create standalone APIs and microservices. Today I will show you how to create a microservice for a chat app that will be used in a later tutorial. The microservice will take messages and push them out to all clients listening setting the ground for push notifications. Without further ado, let’s get started!

Getting Started

Because I want to focus on development, and not system administration, please follow this guide to getting your environment up and running, after doing so, go to your terminal, cd into an empty directory and type in this command:

lumen new messenger-service

cd into your newly created app. First thing we are going to do is define our events. This microservice will give us real-time updates from those who sent messages to it. In order to provide this, we will leverage the broadcasting paradigm included in the Event class. If you are interested in a deeper understanding on how broadcasting works check here, but in short you tell the event what channel to broadcast on and you give it a driver (Redis, Pusher, log). We will being using Redis with a Node.js implementation. Before we can do any of that, we have to add a dependency or two:

For Composer:

predis/predis ~1.0 illuminate/redis ~5.1

For NPM:

socket.io ioredis

Now open up app/Providers/EventServiceProvider.php and change  the array to this:

protected $listen = [
'App\Events\MessageCreatedEvent' => [
'App\Listeners\MessageCreatedEventListener',
],
;

Now create those corresponding classes in the app/Events and app/Listeners directories respectively. In the MessageCreatedEvent add this code:

<?php

namespace App\Events;
use App\Todo;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\BroadcastingShouldBroadcast;
class MessageCreatedEvent extends Event implements ShouldBroadcast
{
use SerializesModels;

public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($message)
{
//set variables
$this->message = $message;
}

/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return ['message'];
}
}

That’s it for that part, be sure to add BROADCAST_DRIVER=redis to your .env file. Next we need to create queue jobs, go to the root of the project and type in this command :

php artisan queue:table && php artisan migrate
That has to be done since all broadcasted events are queued. Next let’s create our node server. Create a directory called node and in it add a file called server.js with the following contents:


var app = require('http').createServer(handler);
var io = require('socket.io')(app);

var Redis = require('ioredis');
var redis = new Redis();

app.listen(6001, function() {
console.log('Server is running!');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
//
console.log('New Connection!');

});
io.on('disconnect',function(socket){
console.log('Connection Dropped!');
});

redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
console.log(channel);
console.log(message);
message = JSON.parse(message);
io.emit(channel, message.data);
});

Next we need to create a controller. In the app/Http/Controllers folder add a MessageController.php file, in it add the following:

<?php
namespace App\Http\Controllers;
use App\Events\MessageCreatedEvent;
use Illuminate\Http\Request;
class MessageController extends Controller
{

/**
* Store a new message.
*
* @param  Request  $request
* @return Response
*/
public function store(Request $request)
{

$message = $request->message;
event(new MessageCreatedEvent($message));
return $message;
}
}

Super simple all we are doing is grabbing the post data and injecting it into the event, letting that run and returning our message. Only 2 things left to do.

Open up the routes.php file located at app/Http/routes.php and add this route:

$app->post('message','MessageController@store'); Lastly we need to add a global CORS middleware, open bootstrap/app.php and add this to the $app->middleware array:

App\Http\Middleware\CorsMiddleware::class,

And that is it folks. If you want to run it type in node node/server.js and watch the connections come in! Next build the ionic mobile app to interact with it!

Leave a Reply

Instagram

Follow Me!

%d bloggers like this: