List of Redis commands to perform crud Operation
Coding example of redis to improve query performance
Command to check performance before and after implementing Redis
List of Redis commands to perform crud Operation
SET
Sets a key with a string value.
Redis::set('name', 'John Doe');
Output
:
OK
GET
Retrieves the value of a key.
$name = Redis::get('name');
echo $name;
Output
:
John Doe
DEL
Deletes a key.
Redis::del('name');
Output
:
1
EXISTS
Checks if a key exists.
$exists = Redis::exists('name');
echo $exists;
Output
:
0 (if key does not exist)
1 (if key exists)
MSET
Sets multiple keys and values.
Redis::mset([
'user:1' => 'Alice',
'user:2' => 'Bob'
]);
Output
:
OK
MGET
Gets multiple keys’ values.
$users = Redis::mget(['user:1', 'user:2']);
print_r($users);
Output
:
Array
(
[0] => Alice
[1] => Bob
)
INCR
Increments the value of a key.
Redis::set('counter', 1);
Redis::incr('counter');
Output
:
2
DECR
Decrements the value of a key.
Redis::decr('counter');
Output
:
1
HSET
Sets a field in a hash.
Redis::hset('user:1', 'name', 'Alice');
Redis::hset('user:1', 'age', 30);
Output
:
1
HGET
Gets a field value from a hash.
$name = Redis::hget('user:1', 'name');
echo $name;
Output
:
Alice
HMSET
Sets multiple fields in a hash.
Redis::hmset('user:2', [
'name' => 'Bob',
'age' => 25
]);
Output
:
OK
HMGET
Gets multiple fields from a hash.
$userData = Redis::hmget('user:2', ['name', 'age']);
print_r($userData);
Output
:
Array
(
[0] => Bob
[1] => 25
)
HGETALL
Gets all fields and values from a hash.
$userData = Redis::hgetall('user:2');
print_r($userData);
Output
:
Array
(
[name] => Bob
[age] => 25
)
LPush
Pushes an element to the left of a list.
Redis::lpush('fruits', 'apple');
Redis::lpush('fruits', 'banana');
Output
:
2 (Length of the list)
LRange
Gets a range of elements from a list.
$fruits = Redis::lrange('fruits', 0, -1);
print_r($fruits);
Output
:
Array
(
[0] => banana
[1] => apple
)
SADD
Adds members to a set.
Redis::sadd('colors', 'red');
Redis::sadd('colors', 'blue');
Output
:
1 (Number of new elements added)
SMEMBERS
Gets all members of a set.
$colors = Redis::smembers('colors');
print_r($colors);
Output
:
Array
(
[0] => red
[1] => blue
)
ZADD
Adds members to a sorted set with scores.
Redis::zadd('scores', 100, 'Alice');
Redis::zadd('scores', 200, 'Bob');
Output
:
1 (Number of new elements added)
ZRANGE
Gets a range of members from a sorted set.
$scores = Redis::zrange('scores', 0, -1, ['WITHSCORES' => true]);
print_r($scores);
Output
:
Array
(
[Alice] => 100
[Bob] => 200
)
EXPIRE
Sets an expiration time for a key.
Redis::set('temp_key', 'temp_value');
Redis::expire('temp_key', 60); // Key expires in 60 seconds
Output
:
1 (If the timeout was set successfully)
Coding Example of Laravel
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;
class RedisController extends Controller
{
// 1. SET
public function setExample()
{
Redis::set('name', 'John Doe');
return response()->json(['message' => 'Key "name" set to "John Doe"']);
}
// 2. GET
public function getExample()
{
$name = Redis::get('name');
return response()->json(['name' => $name]);
}
// 3. DEL
public function delExample()
{
$deleted = Redis::del('name');
return response()->json(['deleted' => $deleted]);
}
// 4. EXISTS
public function existsExample()
{
$exists = Redis::exists('name');
return response()->json(['exists' => $exists ? true : false]);
}
// 5. MSET
public function msetExample()
{
Redis::mset([
'user:1' => 'Alice',
'user:2' => 'Bob',
]);
return response()->json(['message' => 'Multiple keys set']);
}
// 6. MGET
public function mgetExample()
{
$users = Redis::mget(['user:1', 'user:2']);
return response()->json(['users' => $users]);
}
// 7. INCR
public function incrExample()
{
Redis::set('counter', 1);
$counter = Redis::incr('counter');
return response()->json(['counter' => $counter]);
}
// 8. DECR
public function decrExample()
{
$counter = Redis::decr('counter');
return response()->json(['counter' => $counter]);
}
// 9. HSET
public function hsetExample()
{
Redis::hset('user:1', 'name', 'Alice');
Redis::hset('user:1', 'age', 30);
return response()->json(['message' => 'Hash fields set']);
}
// 10. HGET
public function hgetExample()
{
$name = Redis::hget('user:1', 'name');
return response()->json(['name' => $name]);
}
// 11. HMSET
public function hmsetExample()
{
Redis::hmset('user:2', [
'name' => 'Bob',
'age' => 25,
]);
return response()->json(['message' => 'Hash fields set for user:2']);
}
// 12. HMGET
public function hmgetExample()
{
$userData = Redis::hmget('user:2', ['name', 'age']);
return response()->json(['user' => $userData]);
}
// 13. HGETALL
public function hgetAllExample()
{
$userData = Redis::hgetall('user:2');
return response()->json(['user' => $userData]);
}
// 14. LPUSH
public function lpushExample()
{
Redis::lpush('fruits', 'apple');
Redis::lpush('fruits', 'banana');
return response()->json(['message' => 'Items pushed to the list']);
}
// 15. LRANGE
public function lrangeExample()
{
$fruits = Redis::lrange('fruits', 0, -1);
return response()->json(['fruits' => $fruits]);
}
// 16. SADD
public function saddExample()
{
Redis::sadd('colors', 'red');
Redis::sadd('colors', 'blue');
return response()->json(['message' => 'Items added to the set']);
}
// 17. SMEMBERS
public function smembersExample()
{
$colors = Redis::smembers('colors');
return response()->json(['colors' => $colors]);
}
// 18. ZADD
public function zaddExample()
{
Redis::zadd('scores', 100, 'Alice');
Redis::zadd('scores', 200, 'Bob');
return response()->json(['message' => 'Scores added to sorted set']);
}
// 19. ZRANGE
public function zrangeExample()
{
$scores = Redis::zrange('scores', 0, -1, ['WITHSCORES' => true]);
return response()->json(['scores' => $scores]);
}
// 20. EXPIRE
public function expireExample()
{
Redis::set('temp_key', 'temp_value');
Redis::expire('temp_key', 60);
return response()->json(['message' => 'Key "temp_key" set to expire in 60 seconds']);
}
}
OUTPUT
Output for Each Method
1. SET
Response:
{"message": "Key \"name\" set to \"John Doe\""}
2. GET
Response:
{"name": "John Doe"}
3. DEL
Response:
{"deleted": 1}
4. EXISTS
Response (if exists):
{"exists": true}
5. MSET
Response:
{"message": "Multiple keys set"}
6. MGET
Response:
{"users": ["Alice", "Bob"]}
7. INCR
Response:
{"counter": 2}
8. DECR
Response:
{"counter": 1}
9. HSET
Response:
{"message": "Hash fields set"}
10. HGET
Response:
{"name": "Alice"}
11. HMSET
Response:
{"message": "Hash fields set for user:2"}
12. HMGET
Response:
{"user": ["Bob", "25"]}
13. HGETALL
Response:
{"user": {"name": "Bob", "age": "25"}}
14. LPUSH
Response:
{"message": "Items pushed to the list"}
15. LRANGE
Response:
{"fruits": ["banana", "apple"]}
16. SADD
Response:
{"message": "Items added to the set"}
17. SMEMBERS
Response:
{"colors": ["red", "blue"]}
18. ZADD
Response:
{"message": "Scores added to sorted set"}
19. ZRANGE
Response:
{"scores": {"Alice": 100, "Bob": 200}}
20. EXPIRE
Response:
{"message": "Key \"temp_key\" set to expire in 60 seconds"}
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class RedisDatabaseController extends Controller
{
// 1. SET - Store user data in Redis
public function setUser($id)
{
$user = DB::table('users')->find($id);
if (!$user) {
return response()->json(['message' => 'User not found'], 404);
}
Redis::set("user:{$id}", json_encode($user));
return response()->json(['message' => "User {$id} cached successfully"]);
}
// 2. GET - Retrieve user data from Redis
public function getUser($id)
{
$user = Redis::get("user:{$id}");
if (!$user) {
return response()->json(['message' => "User {$id} not found in cache"], 404);
}
return response()->json(['user' => json_decode($user, true)]);
}
// 3. DEL - Delete user from Redis
public function deleteUser($id)
{
$deleted = Redis::del("user:{$id}");
return response()->json(['message' => $deleted ? "User {$id} removed from cache" : "User {$id} not found"]);
}
// 4. EXISTS - Check if user is in Redis cache
public function existsUser($id)
{
$exists = Redis::exists("user:{$id}");
return response()->json(['exists' => $exists ? true : false]);
}
// 5. MSET - Store multiple users in Redis
public function setMultipleUsers()
{
$users = DB::table('users')->limit(2)->get();
$userArray = [];
foreach ($users as $user) {
$userArray["user:{$user->id}"] = json_encode($user);
}
Redis::mset($userArray);
return response()->json(['message' => 'Multiple users cached successfully']);
}
// 6. MGET - Retrieve multiple users from Redis
public function getMultipleUsers($ids)
{
$keys = array_map(fn($id) => "user:{$id}", explode(',', $ids));
$users = Redis::mget($keys);
return response()->json(['users' => array_map('json_decode', $users)]);
}
// 7. INCR - Increment user's age in Redis
public function incrementUserAge($id)
{
$user = Redis::get("user:{$id}");
if (!$user) {
return response()->json(['message' => "User {$id} not found in cache"], 404);
}
$user = json_decode($user, true);
$user['age'] += 1;
Redis::set("user:{$id}", json_encode($user));
return response()->json(['message' => "User {$id}'s age incremented", 'user' => $user]);
}
// 8. DECR - Decrement user's age in Redis
public function decrementUserAge($id)
{
$user = Redis::get("user:{$id}");
if (!$user) {
return response()->json(['message' => "User {$id} not found in cache"], 404);
}
$user = json_decode($user, true);
$user['age'] -= 1;
Redis::set("user:{$id}", json_encode($user));
return response()->json(['message' => "User {$id}'s age decremented", 'user' => $user]);
}
// 9. HSET - Add a hash for user
public function hsetUser($id)
{
$user = DB::table('users')->find($id);
if (!$user) {
return response()->json(['message' => 'User not found'], 404);
}
Redis::hset("user:{$id}:hash", 'name', $user->name);
Redis::hset("user:{$id}:hash", 'email', $user->email);
Redis::hset("user:{$id}:hash", 'age', $user->age);
return response()->json(['message' => "User {$id} cached as a hash"]);
}
// 10. HGET - Retrieve a field from a hash
public function hgetUserField($id, $field)
{
$value = Redis::hget("user:{$id}:hash", $field);
if (!$value) {
return response()->json(['message' => "Field '{$field}' not found for user {$id}"], 404);
}
return response()->json([$field => $value]);
}
// 11. HMSET - Add multiple fields to hash
public function hmsetUser($id)
{
$user = DB::table('users')->find($id);
if (!$user) {
return response()->json(['message' => 'User not found'], 404);
}
Redis::hmset("user:{$id}:hash", [
'name' => $user->name,
'email' => $user->email,
'age' => $user->age,
]);
return response()->json(['message' => "User {$id}'s fields added to hash"]);
}
// 12. HMGET - Retrieve multiple fields from hash
public function hmgetUserFields($id)
{
$fields = Redis::hmget("user:{$id}:hash", ['name', 'email', 'age']);
return response()->json(['user' => array_combine(['name', 'email', 'age'], $fields)]);
}
// 13. HGETALL - Retrieve all fields from hash
public function hgetallUser($id)
{
$user = Redis::hgetall("user:{$id}:hash");
return response()->json(['user' => $user]);
}
// 14. LPUSH - Add data to a list
public function lpushUsers()
{
$users = DB::table('users')->limit(2)->get();
foreach ($users as $user) {
Redis::lpush('user_list', json_encode($user));
}
return response()->json(['message' => 'Users added to list']);
}
// 15. LRANGE - Retrieve data from list
public function lrangeUsers()
{
$users = Redis::lrange('user_list', 0, -1);
return response()->json(['users' => array_map('json_decode', $users)]);
}
// 16. SADD - Add data to a set
public function saddUsers()
{
$users = DB::table('users')->limit(2)->pluck('name');
foreach ($users as $name) {
Redis::sadd('user_set', $name);
}
return response()->json(['message' => 'Users added to set']);
}
// 17. SMEMBERS - Retrieve data from set
public function smembersUsers()
{
$names = Redis::smembers('user_set');
return response()->json(['names' => $names]);
}
// 18. ZADD - Add data to sorted set
public function zaddUsers()
{
$users = DB::table('users')->limit(2)->pluck('age', 'name');
foreach ($users as $name => $age) {
Redis::zadd('user_sorted_set', $age, $name);
}
return response()->json(['message' => 'Users added to sorted set']);
}
// 19. ZRANGE - Retrieve data from sorted set
public function zrangeUsers()
{
$scores = Redis::zrange('user_sorted_set', 0, -1, ['WITHSCORES' => true]);
return response()->json(['scores' => $scores]);
}
// 20. EXPIRE - Set expiration for user cache
public function expireUser($id)
{
Redis::expire("user:{$id}", 3600);
return response()->json(['message' => "User {$id} cache set to expire in 1 hour"]);
}
}
Coding example of redis to improve query performance
my existing Query
public function get_socialranking(Request $request)
{
$input = $request->all();
Log::info('get_socialranking get_urls data:', $request->all());
$slug_id = $request->org_user_id;
$id = $request->org_user_org_id;
$socialrank = Socialrank::where('slug_id',$id)->get();
$response = [
'success' => true,
'data' => SocialrankResource::collection($socialrank),
'message' => 'Socialrank retrieved successfully.',
'count' => count($socialrank)];
return response()->json($response, 200);
}
After Applying Redis commands
public function get_socialranking(Request $request)
{
$input = $request->all();
Log::info('get_socialranking get_urls data:', $input);
$slug_id = $request->org_user_id;
$id = $request->org_user_org_id;
// Create a unique cache key based on the parameters
$cacheKey = "socialrank:{$slug_id}:{$id}";
// Try to get the data from Redis
$socialrank = Redis::get($cacheKey);
if ($socialrank) {
// If data is found in Redis, return it (deserialize it)
$socialrank = json_decode($socialrank);
} else {
// If data is not found in Redis, fetch it from the database
$socialrank = Socialrank::where('slug_id', $id)->get();
// Cache the data in Redis for 60 minutes (adjust TTL as needed)
Redis::setex($cacheKey, 3600, json_encode($socialrank)); // 3600 seconds = 1 hour
}
// Prepare the response
$response = [
'success' => true,
'data' => SocialrankResource::collection($socialrank),
'message' => 'Socialrank retrieved successfully.',
'count' => count($socialrank)
];
return response()->json($response, 200);
}
Before Applying
public function update(Request $request){
Log::info($request ."update ka value aa gaya hai");
$rules = array(
// 'fb_likes' => 'required',
// 'yt_subs' => 'required',
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
$response = [
'success' => false,
'data' => 'Validation Error.',
'message' => $validator->errors()
];
return response()->json($response, 422);
}
$form_data = array(
'fb_likes' => $request->fb_likes,
'yt_subs' => $request->yt_subs,
'tw_follower' => $request->tw_follower,
'insta_follower' => $request->insta_follower,
);
Socialrank::whereId($request->hidden_id)->update($form_data);
$response = [
'success' => true,
'message' => 'Social Rank update successfully.'
];
return response()->json($response, 200);
}
After Applying
public function update(Request $request)
{
Log::info('Update request received: ', $request->all());
$rules = array(
// Define validation rules here
// 'fb_likes' => 'required',
// 'yt_subs' => 'required',
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$response = [
'success' => false,
'data' => 'Validation Error.',
'message' => $validator->errors()
];
return response()->json($response, 422);
}
// Prepare the data to update
$form_data = [
'fb_likes' => $request->fb_likes,
'yt_subs' => $request->yt_subs,
'tw_follower' => $request->tw_follower,
'insta_follower' => $request->insta_follower,
];
// Update the record in the database
Socialrank::whereId($request->hidden_id)->update($form_data);
// Cache key based on the record ID
$cacheKey = "socialrank:{$request->hidden_id}";
// Invalidate the cache: delete the old cached data for this record
Redis::del($cacheKey);
// Optionally, fetch the updated data and cache it again
$updatedSocialRank = Socialrank::find($request->hidden_id);
Redis::setex($cacheKey, 3600, json_encode($updatedSocialRank)); // Cache for 1 hour
$response = [
'success' => true,
'message' => 'Social Rank updated successfully.'
];
return response()->json($response, 200);
}
Command to check performance before and after implementing Redis
Benchmark Before Redis Implementation
Before implementing Redis, you need to measure the time taken to fetch data directly from the database.
How to Implement (Before Redis):
Step 1: In your index method, record the time before and after the database fetch.
public function indexWithoutRedis($id)
{
$startTime = microtime(true); // Start timer
// Direct database query
$data = $this->getDataFromDatabase($id); // Simulate fetching from DB
$endTime = microtime(true); // End timer
// Calculate execution time
$executionTime = $endTime - $startTime;
Log::info("Execution Time without Redis: {$executionTime} seconds");
return response()->json([
'success' => true,
'data' => UrlResource::collection($data['url']),
'url_count' => $data['url_count'],
'message' => 'URLs retrieved successfully',
]);
}
Benchmark After Redis Implementation
Now, after implementing Redis, you need to track the time it takes to fetch data either from Redis or the database, depending on the cache status.
How to Implement (After Redis):
Step 1: In your index method (after Redis implementation), record the time before and after the Redis/database fetch.
public function indexWithRedis($id)
{
$startTime = microtime(true); // Start timer
// Generate Redis key for caching
$redisKey = 'url_dashboard:' . $id;
// Get data from either Redis or Database
$data = $this->getData($redisKey, $id);
$endTime = microtime(true); // End timer
// Calculate execution time
$executionTime = $endTime - $startTime;
Log::info("Execution Time with Redis: {$executionTime} seconds");
return response()->json([
'success' => true,
'data' => UrlResource::collection($data['url']),
'url_count' => $data['url_count'],
'message' => 'URLs retrieved successfully',
]);
}
Another Example
private function getData($redisKey, $id)
{
if (Redis::exists($redisKey)) {
// Fetch from Redis
$startTime = microtime(true); // Start timer
$data = $this->getDataFromRedis($redisKey);
$endTime = microtime(true); // End timer
// Calculate execution time
$executionTime = $endTime - $startTime;
Log::info('Execution Time for DB Query: ' . $executionTime . ' seconds');
return $this->getDataFromRedis($redisKey);
} else {
// Fetch from Database and cache
$startTime = microtime(true); // Start timer
$data = $this->getDataFromDatabase($id, $redisKey); // Simulate fetching from DB
$endTime = microtime(true); // End timer
// Calculate execution time
$executionTimebefore = $endTime - $startTime;
Log::info('executionTimebefore Time for DB Query: ' . $executionTimebefore . ' seconds');
return $this->getDataFromDatabase($id, $redisKey);
}
}
Top comments (0)