失效『Java与Redis联合实现过期失效』(redisjava过期)
Recently, people are increasingly looking for ways to quickly access data stored in a database to boost productivity and solve complex problems. A database cache can be used to bridge the gap between a database and a web application. The most common type of database cache is an in-memory system. It stores data on the main memory of a computer so that application can access data from memory directly. Redis is currently the most popular in-memory database cache system.
Here’s how to use Redis for data cache expiration. To do this, we will use Java client to connect and operate our Redis cache. As Redis supports multiple data structures, we will use list data structure to store our strings and their expiry timestamp. When storing a string, we will also store its expiry timestamp in the same list. This way we can easily retrieve the string value and the expiry timestamp that we need later.
The following is related code written in Java to illustrate it:
//Create Jedis instance
Jedis jedis = new Jedis(“localhost”);
// Store string in Redis list
String key = “string_key”;
String value = “string_value”;
long expiryTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
jedis.lpush(key, value, String.valueOf(expiryTime));
// Get string from Redis list
String cachedString = jedis.lindex(key, 0);
String expiryTimeString = jedis.lindex(key, 1);
// Check if string is still valid
long expiryTimeFromList = Long.valueOf(expiryTimeString);
if (expiryTimeFromList > System.currentTimeMillis()) {
// String is valid
} else {
// String is expired
}
Using the code above, we can make our Redis cache expire using Java. The code is pretty straightforward and easy to understand. First we create an instance of the Jedis object to connect to our Redis database. Next we store the key-value pair in the list together with the expiry timestamp. Finally, when retrieving the key-value pair, we check to see if its expiry time has passed. If so, we discard the data.
A database cache can tremendously improve the performance of our applications. By combining the power of a database cache such as Redis with the flexibility of the Java programming language, we can further improve the performance of our applications by setting expiry times for our cache data.