Spring-data-redis for Redis Learning

Keywords: Redis Spring Jedis Java

Spring-data-redis for Redis Learning

Preface

Earlier, we learned the basics of Redis and how to operate Redis through Jedis in Java. At the same time, we also mentioned that Jedis's operation is too low-level, or not completely encapsulated. When we want to store an object, it's actually troublesome. So let's learn another operation tool, spring-data-redis.

Spring-data-redis is a sub-project of Spring-Data project. It is mainly used to operate Redis. Through Spring-data-redis tool, Redis can be operated in a more object-oriented way.

Spring-data-redis configuration

Environmental preparation

For ease of operation, Spring-boot is used as scaffolding, version 2.0.4.RELEASE, and dependencies are introduced as follows

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

When using Spring-data-redis, pay special attention to version information. The configuration and operation of Spring-data-redis in Spring Boot 2.X are quite different from those in 1.X series. Here, 2.0.4.RELEASE is taken as an example.

Bean configuration

In Spring Boot 2.X, there are two different usage operations, one is using Jedis, the other is using Lettuce. Here we demonstrate the use of Jedis, mainly Lettuce, which has not been studied yet. If you have time later, study it.

Configuration of connection pool

It's better to configure the information in the configuration file, which is directly coded in the program for convenience.

@Bean
public JedisPoolConfig poolConfig() {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxTotal(100);
    poolConfig.setMaxWaitMillis(30 * 1000);
    poolConfig.setMinIdle(20);
    poolConfig.setMaxIdle(40);
    poolConfig.setTestWhileIdle(true);
    return poolConfig;
}

Connection Factory Configuration

The difference between the 2.x series and the 1.x series is that 1.x can set various configuration information directly through the JedisConnection Factory, but after 2.x, all set methods are marked as expired. You can also see by looking at the way JedisConnectionFactory is constructed, so if you're using a stand-alone version of edis, you need to configure two things

public JedisConnectionFactory(
    RedisStandaloneConfiguration standaloneConfig, JedisClientConfiguration clientConfig) {}

Of course, you can not configure connection pool information, where the configuration of connection pool is different from 1.x, using JedisClient Configuration for configuration.

@Bean
public RedisStandaloneConfiguration redisStandaloneConfiguration() {
    RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
    configuration.setHostName(host);
    configuration.setPassword(RedisPassword.of(password));
    configuration.setPort(port);
    return configuration;
}
@Bean
public JedisClientConfiguration clientConfiguration() {
    JedisClientConfiguration.JedisClientConfigurationBuilder builder = JedisClientConfiguration.builder();
    return builder.usePooling()
            .poolConfig(poolConfig())
            .build();
}

Please pay special attention to the above configuration of JedisClient Configuration, constructed by builder, and then used usePooling() and poolConfig() to configure connection pool information. Many of the schemes for directly constructing a JedisPool bean on the Internet are not effective in 2.x. If you don't believe it, keep checking the connection pool information, or the default way.

@Bean
public JedisConnectionFactory redisConnectionFactory() {
    return new JedisConnectionFactory(redisStandaloneConfiguration(), clientConfiguration());
}

RedisTemplate configuration

At the beginning of the article, we mentioned the inconvenience of using native Jedis operation and the improvement of Spring-data-redis. In fact, the main advantage of using the latter is that it provides serialization options and can configure different serializers to serialize keys and values as needed.

As we all know, Redis stores binary, or strings, so an object can not be stored directly in Redis. We can separate the attributes of an object, but this is too inefficient. Direct serialization through serializers can improve the efficiency of coding. In this case, efficiency refers to the efficiency of coding.

@Bean
public RedisTemplate redisTemplate() {
    // Note that String RedisTempalte is used here
    StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
    GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
    // Serializer for setting values
    template.setValueSerializer(jackson2JsonRedisSerializer);
    return template;
}

Note how the template is configured above. In Spring-data-redis, two templates are provided. One is RedisTemplate, each of which is String RedisTempalte. The difference is that the key sequence of RedisTemplate uses the default serializer, JdkSerialization RedisSerializer, while String RedisTemplate uses String RedisSerializer.

In the above configuration, we can also use RedisTempalte and manually configure its corresponding serializer to override the default serializer.

In the above configuration, the value serializer we used is Generic Jackson 2Json RedisSerializer. Of course, it is also possible to use Jackson 2Json RedisSerializer, just need to do some additional configuration.

So far, the configuration link is completed, and then the use.

Spring-data-redis

In Spring-data-redis, five different operation classes are provided for Redis's five different data structures, as follows

ValueOperations<K, V> valueOps;
ListOperations<K, V> listOps;
SetOperations<K, V> setOps;
ZSetOperations<K, V> zSetOps;
HashOperations<K, HK, HV> hashOps;

The corresponding object can be obtained by tempalte.opsForXXX() method, and then the corresponding operation can be carried out.

When injecting RedisTemplate, it should be noted that since RedisTemplate is generic and the type of the corresponding operation class obtained is the same as that of the injection, it is recommended to select the appropriate type when injecting.

@Autowired
private RedisTemplate<String, User> redisTemplate;

// .....

ValueOperations<String, User> ops = redisTemplate.opsForValue();
ListOperations<String, User> listOps = redisTemplate.opsForList();
HashOperations<String, Object, Object> hashOps = redisTemplate.opsForHash();
// ....

The corresponding Ops operates in a similar way to the original life command, just because the serializer is now added. Do you remember the configuration above? All, you can now manipulate objects directly.

The content stored in Redis is related to a specific serializer, such as the configuration above, which stores the following

"{\"@class\":\"cn.xuhuanfeng.spring.mvc.springmvcdemo.domain.User\",\"name\":\"xuhuanfeng\",\"password\":\"huanfeng\"}"

summary

This section mainly studies the configuration and use of Spring-data-redis. The main focus is on configuration. The configuration of Spring boot 2.x is a little different from that of Spring boot 1.x. Most of the configurations found on the Internet are based on 1.x, so I hope this configuration can help you who are also learning.

Posted by mikep on Sat, 11 May 2019 04:28:46 -0700