Spring Boot 2 Series Tutorial Spring Boot Integrated Redis

Posted by vivianp79 on Sat, 23 Nov 2019 03:09:10 +0100

Before Redis came along, we had a wide range of caching frameworks. With Redis, the caching scheme was basically unified. There was a series of tutorials about Redis and Songo that Redis's little buddies might refer to:

There are many ways to use Java to operate Redis. Jedis is currently one of the more popular solutions. In addition to Jedis, there are many other solutions as follows:

In addition to these schemes, Spring Data Redis is one that is used quite a lot.

In traditional SMM, Spring Data Redis needs to be configured by the developer himself. This configuration is cumbersome, mainly configuring three things: connection pool, connector information, and serialization scheme of key and value.

In Spring Boot, the default integrated Redis is Spring Data Redis, and the default underlying connection pool uses lettuce, which allows developers to modify to their own familiarity, such as Jedis.

Spring Data Redis provides RedisTemplate, a very convenient operation template for Redis.This is something Spring Data is good at, so let's take a look at the specific use of Spring Data Redis in Spring Boot.

Scenario 1: Spring Data Redis

Create a project

Create a project to introduce Redis dependencies:

After successful creation, you also need to manually introduce the commos-pool2 dependency, so the final complete pom.xml dependency is as follows:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
</dependencies>

The main point here is to introduce the Spring Data Redis +connection pool.

Configure Redis Information

The next step is to configure the Redis information, which consists of two aspects: the basic Redis information and the connection pool information:

spring.redis.database=0
spring.redis.password=123
spring.redis.port=6379
spring.redis.host=192.168.66.128
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1ms
spring.redis.lettuce.shutdown-timeout=100ms

Automatic Configuration

Automated configuration takes effect when the developer introduces Spring Data Redis in the project and configures the basic information of Redis.

We can see from the Redis automated configuration class in Spring Boot that:

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(
                    RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
            RedisTemplate<Object, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
    }
    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate stringRedisTemplate(
                    RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
            StringRedisTemplate template = new StringRedisTemplate();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
    }
}

This automated configuration class is well understood:

  1. First mark this as a configuration class, and the configuration will not take effect until RedisOperations exist (that is, Spring Data Redis was introduced into the project)
  2. Then import the properties configured in application.properties
  3. Then import the connection pool information (if it exists)
  4. Finally, two Beans are provided, RedisTemplate and StringRedisTemplate, where StringRedisTemplate is a subclass of RedisTemplate and the two methods are basically the same. The main difference is that the data types of operations are different. Both generics in RedisTemplate are Objects. Both keys and values stored by the implier can be one Object, while StringRedisTemplate is the same.Both generics of E are String, meaning that the key and value of String RedisTemplate can only be strings.These two configurations will take effect if the developer does not provide a Bean, otherwise they will not.

Use

Next, you can inject String RedisTemplate or RedisTemplate directly into Service to use:

@Service
public class HelloService {
    @Autowired
    RedisTemplate redisTemplate;
    public void hello() {
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set("k1", "v1");
        Object k1 = ops.get("k1");
        System.out.println(k1);
    }
}

Data operations in Redis can be broadly divided into two types:

  1. For key operations, the relevant method is in RedisTemplate
  2. For specific data type operations, the related methods need to obtain the corresponding data type first. The operation method to obtain the corresponding data type is opsForXXX

Calling this method will store the data in Redis as follows:

The characters preceding k1 are caused by the use of RedisTemplate, which is the result of serializing the key.

In RedisTemplate, the default serialization scheme for key is JdkSerializationRedisSerializer.

In StringRedisTemplate, the default serialization scheme for keys is StringRedisSerializer, so if you use StringRedisTemplate, keys are not prefixed by default.

However, developers can modify the serialization scheme in RedisTemplate as follows:

@Service
public class HelloService {
    @Autowired
    RedisTemplate redisTemplate;
    public void hello() {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set("k1", "v1");
        Object k1 = ops.get("k1");
        System.out.println(k1);
    }
}

Of course, you can also use StringRedisTemplate directly:

@Service
public class HelloService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    public void hello2() {
        ValueOperations ops = stringRedisTemplate.opsForValue();
        ops.set("k2", "v2");
        Object k1 = ops.get("k2");
        System.out.println(k1);
    }
}

Also note that the automatic configuration of Spring Boot can only configure Redis on a single machine. If it is a Redis cluster, everything needs to be manually configured by itself. For how to operate the Redis cluster, Songgo will come back and share with you later.

Option 2: Spring Cache

Operating Redis in the form of Spring Cache, Spring Cache unifies the facade of cached rivers and lakes. This scheme is described in a special article by Songo, where a little partner can move: In Spring Boot, Redis caching is still useful!.

Option 3: Return to the Primitive Age

The third option is to use Jedis or other client tools directly to operate Redis, which is also supported in Spring Boot. Although the operation is cumbersome, it is supported. There are also articles about this operation before Songo, so it will not be repeated here for reference. Jedis uses.

summary

In Spring Boot, Redis's operation, here Songge summarizes three options for you. In fact, the first two are more widely used, and Jedis is less used directly. Basically, no one in Spring Boot has done this directly.

Okay, that's all for this article. Please leave a comment if you have any questions.

Related cases have been uploaded to GitHub, and younger partners are welcome to download: https://github.com/lenve/javaboy-code-samples

Scavenger pays attention to Songgor, public number backstage reply 2TB, get Songgor exclusive 2TB free Java learning dry goods

Topics: Java Redis Spring Jedis