Aug 4, 2016

Laravel5 - AWS DynamoDB as session storage.

This post help you to create custom session service provider in your laravel application. Since, many application now a days uses one endpoint session storage for all their servers(A production application with multiple server behind a load balance).

In your laravel home project directory Issue artisan command.

php artisan make:provider MyDynamoDBServiceProvider

The command will generate file in app/Provider/MyDynamoDBServiceProvider.php
1. Add libraries below, just put just after use Illuminate\Support\ServiceProvider;

use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Session\SessionHandler;
use Aws\Credentials\Credentials;
use Session;
use Log;

2. Put code below in you register method.
Log:info(__METHOD__);
Session::extend('dynamodb', function ($app) {
    // Get a shortcut to config data            
    $cfg = $app['config']->get('session');
    
    // Do the real work of hooking up Dynamo as session handler
    $credential = new Credentials('YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY');
    $dynamoDb = DynamoDbClient::factory([
        'region' => 'ap-northeast-1',
        'version' => '2012-08-10',
        'credentials' => $credential,
    ]);

    $sessionHandler = $dynamoDb->registerSessionHandler([
        'table_name'               => $cfg['table'],
        'hash_key'                 => 'key',
        'session_lifetime'         => 60 * $cfg['lifetime'],   // minutes to seconds
        'consistent_read'          => true,
        'locking_strategy'         => null,
        'automatic_gc'             => true,
        'gc_batch_size'            => 25,
        'max_lock_wait_time'       => 10,
        'min_lock_retry_microtime' => 10000,
        'max_lock_retry_microtime' => 50000
    ]);

    // Set the start of the session id to the cookie name - optional
    $sessionHandler->open('', $cfg['cookie']);
    
    return $sessionHandler;
    
});


3. Full Code will look like this.
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Session\SessionHandler;
use Aws\Credentials\Credentials;
use Session;
use Log;

class MyDynamoDBServiceProvider extends ServiceProvider{
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
        Log:info(__METHOD__);
        Session::extend('dynamodb', function ($app) {
            // Get a shortcut to config data            
            $cfg = $app['config']->get('session');
            
            // Do the real work of hooking up Dynamo as session handler
            $credential = new Credentials('YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY');
            $dynamoDb = DynamoDbClient::factory([
                'region' => 'ap-northeast-1',
                'version' => '2012-08-10',
                'credentials' => $credential,
            ]);

            $sessionHandler = $dynamoDb->registerSessionHandler([
                'table_name'               => $cfg['table'],
                'hash_key'                 => 'key',
                'session_lifetime'         => 60 * $cfg['lifetime'],
                'consistent_read'          => true,
                'locking_strategy'         => null,
                'automatic_gc'             => true,
                'gc_batch_size'            => 25,
                'max_lock_wait_time'       => 10,
                'min_lock_retry_microtime' => 10000,
                'max_lock_retry_microtime' => 50000
            ]);

            // Set the start of the session id to the cookie name - optional
            $sessionHandler->open('', $cfg['cookie']);
            
            return $sessionHandler;
            
        });
    }
}

4. Add it in you app provider config. Edit config/app.php and find providers section.

'providers' => [
.... some other provider list here

App\Providers\MyDynamoDBServiceProvider::class
];

NOTE: Please don't Use DynamoDBServiceProvider or DynamoServiceProvider name if you dont like some have ache.


Happy Reading



Reference:

To get more idea about AWS credential
Service Providers
Adding Custom Session Drivers

1 comment:

Online Training said...

very informative blog and useful article thank you for sharing with us , keep posting learn more about aws with cloud computing

AWS Training

AWS Online Training