Using Redis cache and Session backend in Magento

Find below the steps to use Redis cache and Session backend in Magento

We’ll assume Magento is already installed and that you are installing this on www.yourdomain.com

Step 1. First go to your website’s root directly where your magento files.

cd /home/username/public_html/

 Then  install the redis cache extension by running the following commands.

git clone https://github.com/colinmollenhour/Cm_Cache_Backend_Redis.git
mkdir -p  app/code/community/Cm/
rsync -vPpar --delete Cm_Cache_Backend_Redis/Cm/ app/code/community/Cm/
rm -rf Cm_Cache_Backend_Redis

Also install the redis session extension by running the following commands.

git clone https://github.com/colinmollenhour/credis.git
mkdir -p lib/Credis/ app/code/community/Cm/RedisSession/
rsync -vPpar --delete credis/ lib/Credis/
git clone https://github.com/colinmollenhour/Cm_RedisSession.git
rsync -vPpar --delete Cm_RedisSession/code/ app/code/community/Cm/RedisSession/
rsync -vPpar Cm_RedisSession/Cm_RedisSession.xml app/etc/modules/Cm_RedisSession.xml
rm -rf Cm_RedisSession

Now both the extensions are installed,  you just need to add the respective configuration to the Magento ./app/etc/local.xml

Just after  <global> tag, add below both the code , change persistent and db to suit.

  • For Redis Cache Storage
<config>
    <global> 
        <!-- other configuration nodes --> 
        <cache>
          <backend>CACHE_BACKEND_CLASS_NAME</backend>
          <backend_options>
            <server>127.0.0.1</server>              <!-- or absolute path to unix socket -->
            <port>6379</port>
            <persistent></persistent>               <!-- Specify a unique string like "cache-db0" to enable persistent connections. -->
            <database>0</database>
            <password></password>
            <force_standalone>0</force_standalone>  <!-- 0 for phpredis, 1 for standalone PHP -->
            <connect_retries>1</connect_retries>    <!-- Reduces errors due to random connection failures -->
            <read_timeout>10</read_timeout>         <!-- Set read timeout duration -->
            <automatic_cleaning_factor>0</automatic_cleaning_factor> <!-- Disabled by default -->
            <compress_data>1</compress_data>        <!-- 0-9 for compression level, recommended: 0 or 1 -->
            <compress_tags>1</compress_tags>        <!-- 0-9 for compression level, recommended: 0 or 1 -->
            <compress_threshold>20480</compress_threshold>  <!-- Strings below this size will not be compressed -->
            <compression_lib>gzip</compression_lib> <!-- Supports gzip, lzf and snappy -->
          </backend_options>
        </cache>
        <!-- other configuration nodes -->
    </global>
</config>

After enabling Redis as cache backend, var/cache directory of your Magento installation can be emptied and should stay empty. If you are using Magento Enterprise edition and cache backend that supports tagging for full page cache, similar thing goes for core_cache/core_cache_tag tables from your Magento database because in this case these tables can be truncated and should stay empty. To check is Redis backend being used for storing cache you can run redis-cli tool and query database 1 using following Redis commands:

SELECT 0
KEYS *

When placed inside app/etc/local.xml, following code configures Redis cache backend to use database with index 1 to hold full page cache:

<full_page_cache>
          <backend>Cm_Cache_Backend_Redis</backend>
          <backend_options>
            <server>redis31.i</server>
            <port>6380</port>
            <persistent></persistent>
            <database>2</database>
            <password></password>
            <force_standalone>0</force_standalone>
            <connect_retries>1</connect_retries>
            <lifetimelimit>57600</lifetimelimit>
            <compress_data>0</compress_data>
          </backend_options>
</full_page_cache>

After enabling Redis as full page cache backend, var/full_page_cache directory of your Magento Enterprise Edition installation can be emptied and should stay empty. If you are using cache backend that supports tagging for cache, similar thing goes for core_cache/core_cache_tag tables from your Magento database because in this case these tables can be truncated and should stay empty. To check is Redis backend being used for storing full page cache you can run redis-cli tool and query database 1 using following Redis commands:

SELECT 1
KEYS *

Cache tags cleanup cron

Redis solves most problems that affect other cache backends, but cleaning up old cache tags manually is still required. Luckily, Magento provides garbage cleanup PHP script designed to be run by cron daily to remedy this issue.

FIrst clone the GitHub repository that hosts garbage cleanup PHP script on path accessible to user that will be running this script from it’s crontab

git clone [email protected]:samm-git/cm_redis_tools.git
cd cm_redis_tools
git submodule update --init --recursive

Next step, edit crontab as this user:

crontab -e

and add this script to be started every night:

30 2 * * * /usr/bin/php /path to /cm_redis_tools/rediscli.php -s 127.0.0.1 -p 6379 -d 0,1

where -s parameter is Redis server host, -p port and -d coma separated list of databases to clean. If you remember, we’ve used 0 for cache and 1 for full page cache so adjust as necessary. Also, don’t forget to adjust /some/path/ into whatever path you’ve chosen before cloning the repository.

Using Redis session

Another thing worth mentioning is that following code snippet sets session storage to db.

With this in mind, here’s code that configures Redis session model to use database with index 2, when placed inside app/etc/local.xml.

  • For Redis Session Storage
<config>
    <global> 
        <!-- other configuration nodes -->
        <session_save>db</session_save>
        <redis_session>                       <!-- All options seen here are the defaults -->
            <host>127.0.0.1</host>            <!-- Specify an absolute path if using a unix socket -->
            <port>6379</port>
            <password></password>             <!-- Specify if your Redis server requires authentication -->
            <timeout>2.5</timeout>            <!-- This is the Redis connection timeout, not the locking timeout -->
            <persistent></persistent>         <!-- Specify unique string to enable persistent connections. -->
            <db>3</db>                        <!-- Redis database number; protection from accidental loss is improved by using a unique DB number for sessions -->
            <compression_threshold>2048</compression_threshold>  <!-- Set to 0 to disable compression (recommended when suhosin.session.encrypt=on); known bug with strings over 64k: https://github.com/colinmollenhour/Cm_Cache_Backend_Redis/issues/18 -->
            <compression_lib>gzip</compression_lib>              <!-- gzip, lzf or snappy -->
            <log_level>4</log_level>               <!-- 0 (emergency: system is unusable), 4 (warning; additional information, recommended), 5 (notice: normal but significant condition), 6 (info: informational messages), 7 (debug: the most information for development/testing) -->
            <max_concurrency>6</max_concurrency>                 <!-- maximum number of processes that can wait for a lock on one session; for large production clusters, set this to at least 10% of the number of PHP processes -->
            <break_after_frontend>5</break_after_frontend>       <!-- seconds to wait for a session lock in the frontend; not as critical as admin -->
            <break_after_adminhtml>30</break_after_adminhtml>
            <bot_lifetime>7200</bot_lifetime>                    <!-- Bots get shorter session lifetimes. 0 to disable -->
        </redis_session> 
        <!-- other configuration nodes --> 
    </global>
</config>

Migrate sessions to Redis

If you are implementing Redis on a live store, you should have to import current sessions before you proceed. This should be done with your store in maintenance mode. Cm_RedisSession project provides two scripts for this purpose. Which one you use depends on whether you’ve been using files or db session backend before implementing Redis.

Here’s procedure if you were previously using files for storing session data:

cd /var/www/
touch maintenance.flag
wget https://raw2.github.com/colinmollenhour/Cm_RedisSession/master/migrateSessions.php
php migrateSessions.php -y
rm maintenance.flag

And here’s procedure if you were previously using database for storing session data:

cd /path/to/magento/root
touch maintenance.flag
wget https://raw2.github.com/colinmollenhour/Cm_RedisSession/master/migrateSessions_mysql_redis.php
php migrateSessions_mysql_redis.php -y
rm maintenance.flag

After enabling Redis as session backend, var/sessions directory of your Magento installation can be emptied and should stay empty. Similar thing goes for core_session table from your Magento database because in this case this table can be truncated and should stay empty. To check is Redis model being used for storing sessions you can run redis-cli tool and query database 2 using following Redis commands:

SELECT 3
KEYS *

That’s all there is to implementing Redis with Magento. I hope you found this article useful and until next time, I wish you happy coding!

To check cache and session is working use the following commands.

redis-cli 
127.0.0.1:6379> FLUSHALL
OK
127.0.0.1:6379> FLUSHDB
OK
127.0.0.1:6379> SELECT 1          #Select your respective database for respective caching or session management.
OK
127.0.0.1:6379[1]> FLUSHALL
OK
127.0.0.1:6379[1]> FLUSHDB
OK
127.0.0.1:6379[1]> 

LinuxTweaks

Linuxtweaks Blog helping Server Admin to Manage their servers, Desktop users for making more friendly with linux. Tutorials , guides and tips for linux server maintenance. Here you can learn how to tweak linux servers with code and how to manage it properly.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *