Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use Redis and what is the right way to implement Redis with MySql in PHP?

Tags:

mysql

redis

I have large amount data in database, sometimes server not responding when execution of result is more than the server response time. So, is there any way to reduce the load of mysql server with redis and how to implement it with right way.

like image 347
astha Avatar asked Sep 01 '16 07:09

astha


People also ask

When should I use Redis and when to use MySQL?

Redis offers memory efficiency, fast operating speed, high availability and provides some features like tenability, replication, clustering, etc. 2. MySQL : MySQL is an open-source relational database management system (RDBMS) based on Structured Query Language (SQL).

What is Redis and why use it?

Redis enables you to write traditionally complex code with fewer, simpler lines. With Redis, you write fewer lines of code to store, access, and use data in your applications. The difference is that developers who use Redis can use a simple command structure as opposed to the query languages of traditional databases.

Can we use Redis with MySQL?

Redis is an open-source and in-memory data structure store that can be used for caching, real-time analytics, searching, and machine learning. Integrate Redis with PHP and MySQL will improve your application performance because Redis stores data in RAM. You can use it with databases like MySQL or MariaDB.


2 Answers

Redis supports a range of datatypes and you might wonder what a NOSQL key-value store has to do with datatypes? Well, these datatypes help developers store data in a meaningful way and can make data retrieval faster.

Connect with Redis in PHP

1) Download or get clone of predis library from github

2) We will require the Redis Autoloader and register it. Then we’ll wrap the client in a try catch block. The connection setting for connecting to Redis on a local server is different from connecting to a remote server.

require "predis/autoload.php";
PredisAutoloader::register();

try {
    $redis = new PredisClient();

    // This connection is for a remote server
    /*
        $redis = new PredisClient(array(
            "scheme" => "tcp",
            "host" => "153.202.124.2",
            "port" => 6379
        ));
    */
}
catch (Exception $e) {
    die($e->getMessage());
}

Now that we have successfully connected to the Redis server, let’s start using Redis.

Datatypes of Redis

Here are some of the datatypes supported by Redis:

  • String: Similar to Strings in PHP.
  • List: Similar to a single dimensional array in PHP. You can push, pop, shift and unshift, the elements that are placed in order or insertion FIFO (first in, first out).
  • Hash: Maps between string fields and string values. They are the perfect data type to represent objects (e.g.: A User with a number of fields like name, surname, and so forth).
  • Set: Similar to list, except that it has no order and each element may appear only once.
  • Sorted Set: Similar to Redis Sets with a unique feature of values stored in set. The difference is that each member of a Sorted Set is associated with score, used to order the set from the smallest score to the largest. Others are bitmaps and hyperloglogs, but they will not be discussed in this article, as they are pretty dense.

Getter and Setter in PHP Redis (Predis)

In Redis, the most important commands are SET, GET and EXISTS. These commands are used to store, check, and retrieve data from a Redis server. Just like the commands, the Predis class can be used to perform Redis operations by methods with the same name as commands. For example:

// sets message to contian "Hello world"
$redis->set('message', 'Hello world');
// gets the value of message
$value = $redis->get('message');
// Hello world
print($value); 
echo ($redis->exists('message')) ? "Oui" : "please populate the message key";

INCR and DECR are commands used to either decrease or increase a value.

$redis->set("counter", 0);
$redis->incr("counter"); // 1
$redis->incr("counter"); // 2
$redis->decr("counter"); // 1


$redis->set("counter", 0);
$redis->incrby("counter", 15); // 15
$redis->incrby("counter", 5);  // 20
$redis->decrby("counter", 10); // 10

Working with List

There are a few basic Redis commands for working with lists and they are:

  • LPUSH: adds an element to the beginning of a list
  • RPUSH: add an element to the end of a list
  • LPOP: removes the first element from a list and returns it
  • RPOP: removes the last element from a list and returns it
  • LLEN: gets the length of a list
  • LRANGE: gets a range of elements from a list

Example as mentioned below

$redis->rpush("languages", "french"); // [french]
$redis->rpush("languages", "arabic"); // [french, arabic]
$redis->lpush("languages", "english"); // [english, french, arabic]
$redis->lpush("languages", "swedish"); // [swedish, english, french, arabic]
$redis->lpop("languages"); // [english, french, arabic]
$redis->rpop("languages"); // [english, french]
$redis->llen("languages"); // 2
$redis->lrange("languages", 0, -1); // returns all elements
$redis->lrange("languages", 0, 1); // [english, french]

How to Retrive data from Redis over to MySQL

You need to make Redis database as primary and Mysql database as slave, It means you have to fetch data first from Redis and if data not found/retrived then you have to get data from Mysql if data found then update Redis data so next time you can retrive data from redis. basic snapshot as mentioned below.

//Connect with Redis database
$data=get_data_redis($query_param);
if(empty($data))
{
  //connect with mysql
  $data=get_data_mysql($query_param);
  if(!empty($data))
  {
     // update data into redis for that data
    update_data_redis($data,$query_param);
  }
}

How to Manage data in MySQL and Redis

In case of manage data into databaseyou have to update data into mysql database first and then update it into Redis database.

//insert data in mysql
$inserted= insert_data_mysql($data);
if($inserted)
{
    insert_data_redis($data);
}

//update data in mysql
$updated= update_data_mysql($data,$query);
if($updated)
{
    insert_data_redis($data,$query);
}

//delete data in mysql
$deleted= delete_data_mysql($query);
if($deleted)
{
    delete_data_redis($query);
}
like image 78
Haresh Vidja Avatar answered Oct 20 '22 15:10

Haresh Vidja


Redis can be used as a caching layer over the MYSQL queries. Redis is an in-memory databases, which means, it will keep the data in memory and it can accessed faster as compare to query the data from MYSQL.

One sample use case would be:

Suppose you are creating a gaming listing site, and you have multiple games categories like, car games, bike games, kids games, etc. and to find the game mapping for each categories you have to query SQL database to get the list of the games for your game listing page. This is a scenario in which you can use Redis as a caching layer, and cache the SQL response in memcahce/Radis for X hours.

Exact steps:

  1. First GET from Redis
  2. if found return. if not found in redis, then do the MYSQL query and before returning save the response in redis cache for the next time.

This will offload a hell lot of queries from the MYSQL to in-memory redis db.

if(data in redis){
    step 1: return data;
}else{
    step 1: query MYSQL
    step 2: Save in redis
    step 3: return data
}

Some points to consider before choosing the queries to save in redis are:

  1. Only static queries should be choosen, means those whose data is not user specific.
  2. Choose the slow static queries to further improve the MYSQL performance.

Hope it will help.

like image 20
Nishant Avatar answered Oct 20 '22 13:10

Nishant