REDIS in CodeIgniter 3 for caching web page

I was working on optimization of my project built on CodeIgniter 3 lately that includes optimizing sql queries, methods and caching. For caching, I’m using REDIS (Remote Dictionary Server) as cache server that I had been using in other projects as well for caching. Setting up redis cache in CodeIgniter 3 is quiet easy. We just need to create a config file for connecting to cache server and load cache driver with  adapter in our controller. We can also setup backup cache driver for backup.

Configure Redis

Create a config file application/config/redis.php with following content.

$config[‘socket_type’] = ‘tcp’; //`tcp` or `unix`
$config[‘socket’] = ‘/var/run/redis.sock’; // in case of `unix` socket type
$config[‘host’] = ‘127.0.0.1’; //change this to match your amazon redis cluster node endpoint
$config[‘password’] = NULL;
$config[‘port’] = 6379;
$config[‘timeout’] = 0;

Now load cache driver in constructor of controller ans set it as primary adapter and file cache driver as backup adapter. It’s always a good idea to have a backup plan.

$this->load->driver('cache', array('adapter' => 'redis','backup' => 'file')));

Finally we save to cache and get from cache server as follows.

if($this->cache->redis->is_supported()) {
	$cached = $this->cache->get('key')
	if($cached != null){
		echo $cached;
	}
	else{
		echo 'Some Value';
		$this->cache->save('key, 'Some Value');
	}
}

To set timeout on cache key, we can pass third parameter in save function in seconds (i.e. 60).

$this->cache->save('key, 'Some Value',300);

This will expire cache key in 5 minutes (300 seconds).
Find more info on CodeIgniter Caching Driver here.

You May Also Like