Spring Boot2 Series Tutorial (26) Spring Boot integrate Redis

Redis appear before our wide variety of caching framework, with Redis, caching scheme basically unified, before about Redis, Song Ge has a series of tutorials, not known Redis small partners can refer to this tutorial:

Many use the Java operating Redis program, Jedis is the more popular a program, in addition to Jedis, there are many other solutions, as follows:

In addition to these programs, there is also the use of a considerable number of programs that Spring Data Redis.

In the traditional SSM, the need to develop themselves to configure the Spring Data Redis, this configuration is more complicated, configure the three main things: the connection pool, connection information and key and value serialization scheme.

In Spring Boot, the default integrated Redis is Spring Data Redis, the default underlying connection pool using lettuce, developers can modify for your own familiar, such as Jedis.

Spring Data Redis Redis provides a very convenient for the operation template RedisTemplate. Spring Data This is a good thing, then the next we look at the specific usage Spring Boot in the Spring Data Redis.

Option One: Spring Data Redis

Create Project

Create a project, dependent on the introduction of Redis:

Once created, you need to manually introduced commos-pool2 dependent, so the final complete dependence pom.xml 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>

Here mainly introduces the Spring Data Redis + connection pool.

Redis configuration information

Next, the configuration information Redis information includes two aspects, one of the basic information Redis, the other is connected to the 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

When the developer in the project to introduce the Spring Data Redis, and equipped with basic information about the Redis, at this time, automated configuration will take effect.

We can be discerned from Spring Boot in Redis automated configuration class:

@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, this is a marked class configuration, while the configuration takes effect in the presence of RedisOperations (ie, the project was introduced in Spring Data Redis)
  2. Then import the attributes configured application.properties
  3. And then introduced into the connection pool information (if present)
  4. Finally, two Bean, RedisTemplate and StringRedisTemplate, wherein StringRedisTemplate is RedisTemplate subclass, two methods are basically the same, the main difference is reflected in the different types of data operations, RedisTemplate are two generic Object, meaning those stored key and value can be an object, and two generic StringRedisTemplate are string, meaning those who StringRedisTemplate the key and value can only be strings. If the developer does not provide relevant Bean, two configuration will take effect, it would not take effect.

use

Next, you may be injected directly in the Service RedisTemplate StringRedisTemplate or in 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 manipulation in Redis, generally speaking, be divided into two:

  1. For key operation, and related methods in the RedisTemplate
  2. For a specific data type of operation, related methods need to obtain the corresponding data type, a data type corresponding operation method is opsForXXX

This method can be invoked to store the data in Redis go as follows:

K1 preceding character is caused due to the use RedisTemplate, RedisTemplate result of the key after the serialization.

In RedisTemplate, key scheme is the default sequence JdkSerializationRedisSerializer.

In the StringRedisTemplate, the default key sequence scheme is StringRedisSerializer, therefore, if StringRedisTemplate, there will be the default prefix key front case.

However, the developer itself can modify the sequence RedisTemplate scheme, 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, also can be used directly StringRedisTemplate:

@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, automation Spring Boot configuration can only configure Redis stand-alone, and if Redis cluster, then everything needs its own manual configuration, on how to operate Redis cluster, Song Ge and then later share with you.

Option Two: Spring Cache

Redis is operated by the form of Spring Cache, Spring Cache Cache unified facade of rivers and lakes, such programs have had a Song Ge before a special article describes, small venue where partners can: the Spring in the Boot, Redis cache can do that use! .

Option Three: return to the original era

The third option is the direct use of Jedis or other client tools to manipulate Redis, this program is also supported in Spring Boot, although operational problems, but supports, there are articles presented before this operation Song Ge, so here will not repeat them, you can refer Jedis use .

to sum up

Spring Boot in, Redis operation, which Li Songge for everyone summarizes the three programs, in fact, the first two using some widely used directly Jedis still relatively small, basically in Spring Boot never seen anyone do so directly.

Well, we stop here, there are discussion questions please leave a message.

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

Song Ge scan code concerned, the public number backstage reply 2TB, Song Ge obtain exclusive ultra-dry 2TB free Java learning

Guess you like

Origin www.cnblogs.com/lenve/p/11915332.html