SoFunction
Updated on 2025-04-12

Check how redis caches

To view the time of Redis cache, there are two ways to:

1. Use the TTL command to get the remaining time of cache

Redis provides multiple commands to view the timestamp of cached data, the most commonly used command isttlandpttl

  • ttlIt returns time in seconds, indicating how long the key is still to expire. If -1 is returned, it means that the key has not set an expiration time; if -2 is returned, it means that the key does not exist.
  • pttlThe return value has the same meaning as the "ttl" command, except that the unit becomes milliseconds.

In addition to the "ttl" and "pttl" commands, Redis also provides other commands to get the creation time of cached data and the last modification time.

For example:

  • object idletimeThe command can get the idle time (i.e. the number of seconds from the last use).
  • object refcountThe command can get the reference count of cached data (i.e. how many keys are referenced).

Here is an example of using the Redis command line client to view cache time:

  1. Open the terminal and connect to the Redis server:
$ redis-cli
  1. Select a database (default is 0):
> SELECT <db-number>
  1. Use the TTL command to view the remaining expiration time of the specified key:
> TTL <key>

Which is the key name of the cache you want to view.

  1. Judging by the return value:
  • If -1 is returned, it means that the key has not set an expiration time, that is, the cache will never expire;
  • If -2 is returned, it means that the key does not exist, that is, the cache has been removed;
  • If a positive integer is returned, it means how many seconds there are still expired.

2. Use the corresponding Redis client library in the programming language to execute TTL commands

  • For example:
  • Use the redis-py library in Python:
import redis

# Create a Redis clientr = (host='localhost', port=6379, db=0)

# Get the remaining expiration time of the specified keyttl = ('your:key')

print(ttl)

Notice:

  • Before accessing Redis in a programming language, you need to make sure that the relevant Redis client library is installed.
  • These libraries can usually be installed through package management tools (such as pip, Maven, NuGet, etc.).

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.