How to View Info in Redis and Clean Cache

Introduction

Have you ever needed to check what’s going on inside your Redis cache or clean it up to improve performance? Redis is a powerful in-memory data structure store used as a database, cache, and message broker. In this article, I will guide you through viewing information in Redis and cleaning the cache, using relevant commands and techniques to manage your Redis instances effectively.

Viewing Info in Redis

To begin with, you need to connect to your Redis instance. You can do this using the redis-cli command-line tool. Once connected, several commands allow you to view detailed information about your Redis server and the data it holds.

Connecting to Redis

First, let’s connect to your Redis server. Open your terminal and run:

redis-cli

Useful Commands to View Info

Once you’re connected, you can use several commands to view different types of information. Here are some key commands:

  1. INFO Command: This command provides a comprehensive overview of the Redis server’s status.
INFO

The output is divided into sections, including Server, Clients, Memory, Persistence, Stats, Replication, CPU, Keyspace, and more.

  1. KEYS Command: This command lists all the keys stored in the database.
KEYS *
  1. DBSIZE Command: This command returns the number of keys in the selected database.
DBSIZE
  1. TTL Command: This command returns the remaining time to live of a key that has a timeout.
TTL keyname
  1. TYPE Command: This command returns the data type of the value stored at the key.
TYPE keyname

Example INFO Command Output and Metrics Explanation

Here’s an example output of the INFO command and a detailed explanation of each metric:

# Server
redis_version:6.2.6
redis_git_sha1:00000000
redis_git_dirty:0
os:Linux 4.15.0-142-generic x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:9.3.0
process_id:1
run_id:cbf9b33fb912e7d5c5bb74f6a687f6c98d21c204
tcp_port:6379
uptime_in_seconds:2592000
uptime_in_days:30
hz:10
configured_hz:10
lru_clock:14749383

# Clients
connected_clients:10
client_recent_max_input_buffer:2
client_recent_max_output_buffer:0

# Memory
used_memory:1048576
used_memory_human:1M
used_memory_rss:2097152
used_memory_peak:5242880
used_memory_peak_human:5M
used_memory_lua:4096
mem_fragmentation_ratio:2.00
mem_allocator:jemalloc-5.1.0

# Persistence
loading:0
rdb_changes_since_last_save:10
rdb_bgsave_in_progress:0
rdb_last_save_time:1622727372
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:2
rdb_current_bgsave_time_sec:-1
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok

# Stats
total_connections_received:1000
total_commands_processed:5000
instantaneous_ops_per_sec:5
total_net_input_bytes:10485760
total_net_output_bytes:20971520
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:100
evicted_keys:10
keyspace_hits:4500
keyspace_misses:500

# Replication
role:master
connected_slaves:1
slave0:ip=192.168.1.10,port=6379,state=online,offset=28955816,lag=0

# CPU
used_cpu_sys:10.5
used_cpu_user:5.5
used_cpu_sys_children:0.1
used_cpu_user_children:0.1

# Keyspace
db0:keys=15,expires=0,avg_ttl=0

Explanation of Metrics

NameDescription
redis_versionVersion of the Redis server.
osOperating system Redis is running on.
uptime_in_secondsUptime of the Redis server in seconds.
connected_clientsNumber of client connections (excluding connections from replicas).
used_memoryTotal amount of memory allocated by Redis.
used_memory_humanHuman-readable format of the memory used.
used_memory_rssMemory allocated by the operating system.
mem_fragmentation_ratioRatio of memory allocated by the OS to the memory used by Redis.
total_connections_receivedTotal number of connections accepted by the server.
total_commands_processedTotal number of commands processed by the server.
instantaneous_ops_per_secNumber of commands processed per second.
expired_keysTotal number of key expiration events.
evicted_keysNumber of keys removed due to maxmemory limit.
keyspace_hitsNumber of successful lookups of keys.
keyspace_missesNumber of failed lookups of keys.
roleRole of the instance (master or replica).
connected_slavesNumber of connected replicas.
used_cpu_sysSystem CPU consumed by the Redis server.
used_cpu_userUser CPU consumed by the Redis server.
db0:keysNumber of keys in the database.
db0:expiresNumber of keys with expiration in the database.
db0:avg_ttlAverage time to live for keys in the database.

Tips for Using Metrics to Improve Performance and Resource Management

Memory Management:

  • used_memory: Monitor this to ensure your Redis instance isn’t using too much memory. If used_memory is high, consider deleting unnecessary keys or optimizing your data structures.
  • mem_fragmentation_ratio: A high ratio may indicate memory fragmentation. Consider using the MEMORY PURGE command to defragment memory or configuring Redis with a more efficient memory allocator.

Performance Optimization:

  • instantaneous_ops_per_sec: This helps in understanding the current load on your Redis server. If it’s consistently high, you might need to scale your Redis instances or optimize your commands.
  • keyspace_hits vs. keyspace_misses: A high number of misses compared to hits indicates inefficiency in your key access patterns. Optimize your key usage to improve cache hit rates.

Resource Management:

  • used_cpu_sys and used_cpu_user: These metrics help in understanding CPU usage. High CPU usage might require optimization of your Redis commands or offloading some tasks to other instances.
  • connected_clients: Keep an eye on the number of connected clients. Too many connections can overwhelm your server, requiring connection management or scaling.

Availability and Persistence:

  • rdb_last_save_time and rdb_last_bgsave_status: These metrics inform you about the last time Redis performed a snapshot. Ensure regular snapshots for data persistence.
  • connected_slaves: Monitoring connected replicas helps in ensuring high availability. Always have at least one replica for failover.

Cleaning Redis Cache

Sometimes, you might need to clear the cache to free up memory or reset the state. You can achieve this using a few simple commands.

Commands to Clean Cache

FLUSHDB Command: This command deletes all keys in the currently selected database.

FLUSHDB

FLUSHALL Command: This command deletes all keys in all databases.

FLUSHALL

DEL Command: This command deletes a specific key.

DEL keyname

Example Usage

If you want to clear the entire cache from the current database, you can use:

FLUSHDB

If you want to clear the entire cache from all databases, use:

FLUSHALL

Practical Usage

Viewing and cleaning your Redis cache can help you maintain optimal performance and resource usage. For instance, you can periodically check the memory usage and decide whether to clear specific keys or entire databases based on your application’s needs.

Example Scenario

Suppose you have a web application that uses Redis for session storage. Over time, the number of session keys might grow, consuming more memory. By using the DBSIZE command, you can monitor the number of session keys. If it exceeds a certain threshold, you might decide to use the FLUSHDB command during a maintenance window to clear the session data and start fresh.

Questions and Answers

Q: How can I monitor the memory usage of my Redis server?

A: You can use the INFO command to get detailed information about memory usage. Look for the used_memory field under the Memory section.

Q: What is the difference between `FLUSH

DBandFLUSHALL? A:FLUSHDBclears all keys in the currently selected database, whileFLUSHALL` clears all keys in all databases managed by the Redis server.

Q: How can I delete a specific key in Redis?

A: Use the DEL command followed by the key name. For example, DEL mykey deletes the key named mykey.

Q: Can I view the data type of a specific key in Redis?

A: Yes, you can use the TYPE command followed by the key name. For example, TYPE mykey returns the data type of the key mykey.

Q: How do I check the expiration time of a key in Redis?

A: Use the TTL command followed by the key name. It returns the remaining time to live of the key in seconds.

Related Subjects

Redis Data Types

Understanding the various data types supported by Redis, such as strings, lists, sets, and hashes, helps in utilizing Redis more effectively. For more information, you can visit the Redis Documentation.

Redis Persistence

Learn about different persistence mechanisms in Redis, like RDB snapshots and AOF logs, which ensure your data is safe even if the server restarts. Detailed information is available in the Redis Persistence Documentation.

Redis Pub/Sub

Redis also supports publish/subscribe messaging, allowing you to build real-time messaging applications. Check out the Redis Pub/Sub Documentation for more details.

Redis Security

Securing your Redis instance is crucial to prevent unauthorized access. Learn best practices for Redis security by visiting the Redis Security Documentation.

Conclusion

In this article, you’ve learned how to view information in Redis and clean the cache using various commands. These operations are essential for maintaining the health and performance of your Redis instance. I encourage you to try these commands and see how they work in your environment. If you have any questions, feel free to ask in the comments!

By understanding and managing your Redis server better, you can ensure it continues to serve your application’s needs efficiently. applications, you can effectively manage your Redis instance, ensuring smooth and efficient operations for your applications.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>