Redis rely on

Redis is a powerful caching tool, so how do you use it in Java projects?

The redis connection driver, the most used by far, should be Jedis.

Search the Maven central repository for Jedis

The latest is 3.3.0.

spring-data-redis

Spring provides a RedisConnectionFactory interface that generates a RedisConnection interface object that encapsulates the underlying Rediis interface.

This is the structure diagram associated with RedisConnection

Under the simplified:

In Spring, Redis is operated through the RedisConnection interface, which encapsulates native Jedis. To obtain the RedisConnection interface object, it is generated through the RedisConnectionFactory interface, so the first step is to configure the RedisConnectionFactory.

RedisConfig

First create a configuration class:

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String hostname;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.database}")
    private int database;

    private RedisConnectionFactory factory = null;

    @Bean("redisConnectionFactory")
    public RedisConnectionFactory initConnectionFactory(a) {
        if(factory ! =null) {
            return factory;
        }
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // Maximum free number
        poolConfig.setMaxIdle(10);
        // Maximum number of connections
        poolConfig.setMaxTotal(25);
        // Maximum waiting milliseconds
        poolConfig.setMaxWaitMillis(timeout);
        // Create a connection factory
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
        // Get the Redis configuration for the single machine
        RedisStandaloneConfiguration rsConfig = jedisConnectionFactory.getStandaloneConfiguration();
        rsConfig.setHostName(hostname);
        rsConfig.setPort(port);
        rsConfig.setPassword(password);
        rsConfig.setDatabase(database);
        factory = jedisConnectionFactory;
        returnfactory; }}Copy the code

Configuration file:

spring:
  redis:
    host: 10.0228.117.
    port: 6379
    password: ""
    timeout: 2000
    database: 0
Copy the code

A RedisConnectionFactory is created from a connection pool, and a RedisConnection object is created from the Factory. To try it out again, get it from the RedisConnectionFactory factory and use it. After using it, you need to manually close it.

Let’s try using the test method:

Execute the testFactory method

Then use the client connection to view

RedisTemplate

If you use RedisConnection only, you need to acquire the connection before each use and release the connection after use. If you forget to release the connection, you will soon run out of connections in the Redis connection pool.

So, Spring provides the RedisTemplate

Ok, so let’s go ahead and try again, first we’ll create the RedisTemplate

    @Bean("redisTemplate")
    public RedisTemplate initRedisTemplate(a) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(initConnectionFactory());
        return template;
    }
Copy the code

Then in test, try using:

Execution Result:

Found no output, we use the client to view

The key we gave was test. Why xxxxtest after storage?

Redis serialization

Redis is NoSql for string storage, while Java is a native language. Objects cannot be stored in Redis, but Java provides a serialization mechanism. If a class implements Serializable interface, it can be serialized. The binary string is obtained by serializing the class object, and Redis can then store the class object as a string. Java can also deserialize binary strings into objects. Spring provides a mechanism for serializers and implements several.

This is the serializer implemented by Spring

A serializer that can be configured in the RedisTemplate

attribute describe note
defaultSerializer Default serializer If not set, then use JdkSerializationRedisSerializer
keySerializer Redis key serializer If not, the default serializer is used
valueSerializer Redis value serializer If not, the default serializer is used
hashKeySerializer Redis Hash Field serializer If not, the default serializer is used
hashValueSerializer Redis Hash Value serializer If not, the default serializer is used
stringSerializer String serializer RedisTemplate is automatically assigned to StringRedisSerializer

Because we have no configuration for what kind of serializer RedisTemplate, so use the default serialization and deserialization JdkSerializationRedisSerializer, that is, the string according to the object serialization, so there are some characters before we set of keys.

String serializer

We specify the serializer for the RedisTemplate as stringSerializer.

And then re-execute it

Then check out Redis:

I forgot to set valueSerializer

Spring’s encapsulation of Redis data type operations

Redis can support 7 types of data structures, five kinds of commonly used data structures: string, hash, list, set, sorted set

RedisTemplate Retrieves data type operation interface:

Redis data structure Operation Interface Acquisition
string redisTemplate.opsForValue()
hash redisTemplate.opsForHash()
list redisTemplate.opsForList()
set redisTemplate.opsForSet()
sorted set redisTemplate.opsForZSet()

Spring’s encapsulation of Redis batch operations

Also, in Spring, batch operations on a key are supported:

RedisTemplate support for batch operations:

Redis data type The encapsulation of Spring batch operations
string redisTemplate.boundValueOps(“key”)
hash redisTemplate.boundHashOps(“key”)
list redisTemplate.boundListOps(“key”)
set redisTemplate.boundSetOps(“key”)
sorted set redisTemplate.boundZSetOps(“key”)

SessionCallback and RedisCallback

RedisTemplate callback

Using callbacks, you can execute multiple Redis commands on the same connection.

SessionCallback has more encapsulation than RedisCallback and is more user-friendly to use.

SessionCallback

    @Test
    public void testRedisSessionCallback(a) {
        redisTemplate.execute((RedisConnection rc) -> {
            rc.set("session1".getBytes(), "session1".getBytes());
            rc.set("session2".getBytes(), "session2".getBytes());
            return null;
        });
    }
Copy the code

RedisCallback

    @Test
    public void testRedisCallback(a) {
        redisTemplate.execute((RedisConnection rc) -> {
            rc.set("redis1".getBytes(), "redis1".getBytes());
            rc.set("redis2".getBytes(), "redis2".getBytes());
            return null;
        });
    }
Copy the code