# 8.3 Redis and Cache

# 1. Basic Usage

Redis and Cache can be easily used together to access Redis services. The Redis object can obtain a Cache object through the use() method. This Cache object offers a rich API for using Redis services. Below is a sample usage:

public void redisDemo() {
  // Get the Redis Cache object named "bbs"
  Cache bbsCache = Redis.use("bbs");
  bbsCache.set("key", "value");
  bbsCache.get("key");
 
  // Get the Redis Cache object named "news"
  Cache newsCache = Redis.use("news");
  newsCache.set("k", "v");
  newsCache.get("k");
 
  // The first created Cache becomes the primary cache, so the cacheName parameter can be omitted
  bbsCache = Redis.use();  // The primary cache can omit the cacheName parameter
  bbsCache.set("jfinal", "awesome");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

In the code above, the use() method takes "bbs" and "news" as parameters to obtain two Cache objects. These objects can operate on their corresponding Redis servers.

Generally, only one RedisPlugin connecting to a single Redis server will be created. You can use Redis.use().set(key, value) directly.

Note: When using methods like incr, incrBy, decr, decrBy to manipulate counters, you should use getCounter(key) to read the value instead of get(key), otherwise a deserialization exception will be thrown. Similarly, you can't use set(key, value) for operations like incrBy(key, value).

Higher versions of JFinal have introduced the call method for both the Redis and Cache classes. This method exposes the Jedis object directly, bypassing serialization and deserialization processes.

// Use lambda to expose Jedis API
Long ret = Redis.call(j -> j.incrBy("key", 1));

Long ret = Redis.call(jedis -> {
    return jedis.incrBy("key", 1);
});
1
2
3
4
5
6

If multiple caches are configured, you can get the corresponding cache object by using Redis.use(...) first and then proceed with the operation.

// Specify the cacheName parameter before performing operations
Long ret = Redis.use("mycache").call(j -> j.incrBy("key", 1));

// Redis.use() without arguments means getting the default cache
Long ret = Redis.use().call(j -> j.incrBy("key", 1));
1
2
3
4
5

For storing data types other than Strings, you can convert them to JSON first and then perform the operation.

User user = dao.findById(userId);
String userJson = JsonKit.toJson(user);

Redis.call(jedis -> {
    return jedis.set("user", userJson);
});

// Or simplify it as below
Redis.call(j -> j.set("user", JsonKit.toJson(user)));
1
2
3
4
5
6
7
8
9

The above call usage does not involve object serialization or deserialization and directly operates on the Jedis object. Given the widespread use of JSON, this is the method recommended by the JFinal official team.

Last Updated: 9/22/2023, 7:03:51 AM