Saturday, 20 May 2023

How to use repl in Adonisjs

>> Official Guide

* use node ace repl

.ls
loadModels()
const users = await models.User.all()
console.log(users)
 

Thank you.  

Wednesday, 10 May 2023

Understand about how Nodejs work

 * Nodejs use 

+ Single-threaded with Event Loop: when a request is made, it is added to the event loop, which is a queue of pending requests. Node.js then continues executing the remaining code, rather than waiting for the request to be completed. When the request is completed, Node.js retrieves it from the event loop and returns the result to the client.

+ Event-driven, non-blocking I/O: allows it to handle multiple requests and connections concurrently without blocking the execution of other code.

 

Three ways to use asynchronous in nodejs

* There are 3 ways to use asynchronous in nodejs: callback, promises, async/await

1. Callbacks functions

- Callbacks are functions that are passed as arguments to other functions and are executed when the operation completes.

- Callbacks are commonly used to handle asynchronous operations.

const fs = require('fs');
fs.readFile('myfile.txt', function(err, data) {
if (err) {
console.error(err);
} else {
console.log(data.toString());
}
});

* function(err, data): is callback (is the second parameter of readFile() method)

2. Promises

- Promises represent a value that may not be avaiable

const fs = require('fs/promises');

fs.readFile('myfile.txt')
.then((data) => {
console.log(data.toString());
})
.catch((err) => {
console.error(err);
});

* (data) is promises (is return by method readFile())

3. Async/await syntax

- Async/await is a syntax allows to write asynchronous code that looks and behaves like synchronous code

const fs = require('fs/promises');

async function readFile() {
try {
const data = await fs.readFile('myfile.txt');
console.log(data.toString());
} catch (err) {
console.error(err);
}
}

readFile();

Thank you 


 





Tuesday, 9 May 2023

How to install Supervisor on Ubuntu

1. Install Supervisor  

sudo apt update
sudo apt install supervisor 
sudo systemctl status supervisor 
sudo systemctl start supervisor
sudo systemctl stop supervisor
sudo systemctl restart supervisor 

2. To add programs to Supervisor

- way 1:  configure it by editing the configuration file located at /etc/supervisor/supervisord.conf.

- way 2: create a new configuration file with a .conf extension in the /etc/supervisor/conf.d/ directory. 

* reload supervisor

sudo supervisorctl reread
sudo supervisorctl update 

3. example supervisor.conf for laravel

[supervisord]
nodaemon=true
loglevel = info
logfile=/var/log/supervisord.log
pidfile=/var/run/supervisord.pid

[group:laravel-worker]
priority=999
programs=nginx,php8-fpm,laravel-schedule,laravel-queue,chatgpt-python-handle-data

[program:nginx]
priority=10
autostart=true
autorestart=true
stderr_logfile_maxbytes=0
stdout_logfile_maxbytes=0
stdout_events_enabled=true
stderr_events_enabled=true
command=/usr/sbin/nginx -g 'daemon off;'
stderr_logfile=/var/log/nginx/error.log
stdout_logfile=/var/log/nginx/access.log

[program:php8-fpm]
priority=5
autostart=true
autorestart=true
stderr_logfile_maxbytes=0
stdout_logfile_maxbytes=0
command=/usr/local/sbin/php-fpm -R
stderr_logfile=/var/log/nginx/php-error.log
stdout_logfile=/var/log/nginx/php-access.log

[program:laravel-queue]
numprocs=5
autostart=true
autorestart=true
redirect_stderr=true
process_name=%(program_name)s_%(process_num)02d
stdout_logfile=/var/log/nginx/worker.log
command=php /var/www/artisan queue:work

[program:laravel-schedule]
numprocs=1
autostart=true
autorestart=true
redirect_stderr=true
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/artisan schedule:work
stdout_logfile=/var/log/nginx/schedule.log
 
[program:chatgpt-python-handle-data]
numprocs=1
autostart=true
autorestart=true
redirect_stderr=true
process_name=%(program_name)s_%(process_num)02d
command=/bin/bash -c 'cd /var/www/chatgpt-python/ && python3 /var/www/chatgpt-python/main.py'
stdout_logfile=/var/log/nginx/chatgpt-python.log 


Thank you

Thursday, 4 May 2023

Using RabbitMQ in Laravel

1. Install packages

- Install RabbitMQ Queue driver for Laravel

composer require vladimir-yuldashev/laravel-queue-rabbitmq

- Install PHP client for RabbitMQ to work between PHP and rabbitmq

composer require enqueue/amqp-bunny

2. Update queue.php config

'connections' => [
 
'rabbitmq' => [

'driver' => 'rabbitmq',

/*
* Set to "horizon" if you wish to use Laravel Horizon.
*/
'worker' => env('RABBITMQ_WORKER', 'default'),

'dsn' => env('RABBITMQ_DSN', null),

/*
* Could be one a class that implements \Interop\Amqp\AmqpConnectionFactory for example:
* - \EnqueueAmqpExt\AmqpConnectionFactory if you install enqueue/amqp-ext
* - \EnqueueAmqpLib\AmqpConnectionFactory if you install enqueue/amqp-lib
* - \EnqueueAmqpBunny\AmqpConnectionFactory if you install enqueue/amqp-bunny
*/

// 'factory_class' => \Enqueue\AmqpBunny\AmqpConnectionFactory::class,

'host' => env('RABBITMQ_HOST', '127.0.0.1'),
'port' => env('RABBITMQ_PORT', 5672),

'vhost' => env('RABBITMQ_VHOST', '/'),
'login' => env('RABBITMQ_LOGIN', 'guest'),
'password' => env('RABBITMQ_PASSWORD', 'guest'),

'queue' => env('RABBITMQ_QUEUE', 'default'),

'options' => [

'exchange' => [

'name' => env('RABBITMQ_EXCHANGE_NAME'),

/*
* Determine if exchange should be created if it does not exist.
*/

'declare' => env('RABBITMQ_EXCHANGE_DECLARE', true),

/*
* Read more about possible values at https://www.rabbitmq.com/tutorials/amqp-concepts.html
*/

// 'type' => env('RABBITMQ_EXCHANGE_TYPE', \Interop\Amqp\AmqpTopic::TYPE_DIRECT),
'passive' => env('RABBITMQ_EXCHANGE_PASSIVE', false),
'durable' => env('RABBITMQ_EXCHANGE_DURABLE', true),
'auto_delete' => env('RABBITMQ_EXCHANGE_AUTODELETE', false),
'arguments' => env('RABBITMQ_EXCHANGE_ARGUMENTS'),
],

'queue' => [

/*
* Determine if queue should be created if it does not exist.
*/

'declare' => env('RABBITMQ_QUEUE_DECLARE', true),

/*
* Determine if queue should be binded to the exchange created.
*/

'bind' => env('RABBITMQ_QUEUE_DECLARE_BIND', true),

/*
* Read more about possible values at https://www.rabbitmq.com/tutorials/amqp-concepts.html
*/

'passive' => env('RABBITMQ_QUEUE_PASSIVE', false),
'durable' => env('RABBITMQ_QUEUE_DURABLE', true),
'exclusive' => env('RABBITMQ_QUEUE_EXCLUSIVE', false),
'auto_delete' => env('RABBITMQ_QUEUE_AUTODELETE', false),
'arguments' => env('RABBITMQ_QUEUE_ARGUMENTS'),
],
],

/*
* Determine the number of seconds to sleep if there's an error communicating with rabbitmq
* If set to false, it'll throw an exception rather than doing the sleep for X seconds.
*/

'sleep_on_error' => env('RABBITMQ_ERROR_SLEEP', 5),

/*
* Optional SSL params if an SSL connection is used
* Using an SSL connection will also require to configure your RabbitMQ to enable SSL. More details can be founds here: https://www.rabbitmq.com/ssl.html
*/

'ssl_params' => [
'ssl_on' => env('RABBITMQ_SSL', false),
'cafile' => env('RABBITMQ_SSL_CAFILE', null),
'local_cert' => env('RABBITMQ_SSL_LOCALCERT', null),
'local_key' => env('RABBITMQ_SSL_LOCALKEY', null),
'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true),
'passphrase' => env('RABBITMQ_SSL_PASSPHRASE', null),
],
],
        
],

3. Update .env

##############################
QUEUE_CONNECTION=rabbitmq

RABBITMQ_HOST=rabbitmq
RABBITMQ_PORT=5672
RABBITMQ_VHOST=/
RABBITMQ_LOGIN=guest
RABBITMQ_PASSWORD=guest
RABBITMQ_QUEUE=hello-world

RABBITMQ_EXCHANGE_NAME=default
RABBITMQ_EXCHANGE_DECLARE=
RABBITMQ_EXCHANGE_TYPE=
RABBITMQ_EXCHANGE_PASSIVE=
RABBITMQ_EXCHANGE_DURABLE=
RABBITMQ_EXCHANGE_AUTODELETE=
RABBITMQ_EXCHANGE_ARGUMENTS=default

RABBITMQ_QUEUE_DECLARE=
RABBITMQ_QUEUE_DECLARE_BIND=
RABBITMQ_QUEUE_PASSIVE=
RABBITMQ_QUEUE_DURABLE=
RABBITMQ_QUEUE_EXCLUSIVE=
RABBITMQ_QUEUE_AUTODELETE=
RABBITMQ_QUEUE_ARGUMENTS=default

RABBITMQ_ERROR_SLEEP=5

RABBITMQ_SSL=
RABBITMQ_SSL_CAFILE=
RABBITMQ_SSL_LOCALCERT=
RABBITMQ_SSL_LOCALKEY=
RABBITMQ_SSL_VERIFY_PEER=
RABBITMQ_SSL_PASSPHRASE=

4. Create HelloWorldJob

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class HelloWorldJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

/**
* Create a new job instance.
*
* @return void
*/
protected $data;
public function __construct($data)
{
$this->data = $data;
}

/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
Log::info('Hello world job');
Log::info($this->data);
sleep(25);
}
}




* Call job

Route::get('/rabbitmq', function() {
HelloWorldJob::dispatch(['data' => 'Hello World']);
});

5. Show result

- access: http://localhost:15672/#/queues/%2F/default 


Thank you 

Monday, 1 May 2023

Examples of synchronous and asynchronous code in PHP

1. Using Synchronous 

The program waits for the current task to finish before starting the next task

<?php
$start = microtime(true);
echo 'start' . PHP_EOL;

function run() {
echo 'before' . PHP_EOL;
usleep(3000000); // equivalent of setTimeout in Node.js
echo 'wait 3 seconds' . PHP_EOL;
echo 'after' . PHP_EOL;
}

run();

echo 'end' . PHP_EOL;
$end = microtime(true);
$time_taken = $end - $start;
echo "Time taken: " . number_format($time_taken, 5) . " seconds";

output

start
before
wait 3 seconds
after
end
Time taken: 3.00017 seconds

Or

<?php
$start = microtime(true);
echo 'start' . PHP_EOL;

function run() {
echo 'before' . PHP_EOL;
// usleep(3000000); // equivalent of setTimeout in Node.js
echo 'wait 3 seconds' . PHP_EOL;
echo 'after' . PHP_EOL;
}

run();

echo 'end' . PHP_EOL;
$end = microtime(true);
$time_taken = $end - $start;
echo "Time taken: " . number_format($time_taken, 5) . " seconds";

output

start
before
wait 3 seconds
after
end
Time taken: 0.00004 seconds

2. Using Asynchronous 

The program can continue to execute while waiting for a task to complete

You have to install ReactPHP to use asynchronous in PHP

Thank you 


Examples of synchronous and asynchronous code in JS

1. Using Synchronous

The program waits for the current task to finish before starting the next task

// code
console.log('start');
function run() {
console.log('before');
setTimeout(function() {console.log('wait 3 seconds')}, 3000);
console.log('after');
}

run();

console.log('end');

output

start
before
after
end
wait 3 seconds

2. Using Asynchronous 

The program can continue to execute while waiting for a task to complete

// code 
console.log('start');
async function run() {
console.log('before');
await setTimeout(function() {console.log('wait 3 seconds')}, 3000);
console.log('after');
}

run();

console.log('end');

output

start
before
end
after
wait 3 seconds

Thank you 


Golang Advanced Interview Q&A