SpringBoot 2.0 Actual | Chapter 21: Integrating Redis

Relevant knowledge

Introduction to Redis

Redis is an open source, in-memory, high-performance data storage system that can be used as a database, cache, and messaging middleware.
Redis supports many types of data structures, such as string, hashes, lists, sets, sortedSets, and so on.
Redis has built-in replication, LUA scripting, transactions, persistence, LRU driven events, and so on.
Redis can provide high availability through Sentinel and Cluster

Lettuce and Jedis

Lettuce and Jedis are client programs that connect to Redis Server.
SpringBoot2.x used Jedis as the default component for interacting with Redis before, and SpringBoot2.x was replaced with Lettuce (lettuce).
Jedis is implemented as a direct connection to redis server and is non-thread safe in a multithreaded environment unless a connection pool is used to add physical connections to each Jedis instance.
Lettuce is a Netty-based connection instance (StatefulRedisConnection) that can be accessed concurrently among multiple threads and is thread-safe to satisfy concurrent access in a multithreaded environment.
At the same time, it is a scalable design, and if one connection instance is not enough, it can be added as needed.

target

Integrate Redis to add, delete, and change redis

Dead work

Install Redis

Docker installation is introduced. Docker installation can be referred to https://blog.csdn.net/gongm24/article/details/86357866

Download Mirror
docker pull redis
Run Mirror
docker run --name redis \
    -p 6379:6379 \
    -itd redis --requirepass "123456"
Check that the installation was successful, use the client to log in to the container, execute the redis-cli-a 123456 command, and connect
docker exec -it redis /bin/bash

Operation steps

Add Dependency

Introduce the Spring Boot Starter parent project

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
</parent>

Add dependencies on spring-boot-starter-data-redis

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

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

The added overall dependencies are as follows

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>

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

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

To configure

spring:
  redis:
    host: 127.0.0.1
    password: 123456
    # Connection timeout (milliseconds)
    timeout: 10000
    # Redis has 16 tiles by default. Configure the specific tiles used here. The default is 0
    database: 0
    lettuce:
      pool:
        # Maximum number of connections in connection pool (no limit with negative value) default 8
        max-active: 8
        # Connection pool maximum blocking wait time (unlimited with negative value) default-1
        max-wait: -1
        # Maximum idle connection in connection pool default 8
        max-idle: 8
        # Minimum idle connection in connection pool default 0
        min-idle: 0

Code

@Slf4j
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class RedisTest {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void testString() throws Exception {
        stringRedisTemplate.opsForValue().set("welcome", "hello redis");
        String welcome = stringRedisTemplate.opsForValue().get("welcome");
        log.info("Storage String: {}", welcome);
    }

}

Encoding (using custom serialization)

Define Objects

@NoArgsConstructor must remember to add and invoke a parameterless constructor to instantiate the object when deserializing.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    String username;
    String password;

}
Register Custom RedisTemplate

The serialization of the value selected jackson

@Configuration
@AutoConfigureAfter(value = RedisAutoConfiguration.class)
public class CustomConfig {

    @Bean(name = "jsonRedisTemplate")
    public RedisTemplate<String, Object> jsonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}
test
@Slf4j
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class RedisTest {

    @Autowired
    @Qualifier("jsonRedisTemplate")
    private RedisTemplate<String, Object> jsonRedisTemplate;

    @Test
    public void testCustomerSerializer() throws Exception {
        jsonRedisTemplate.opsForValue().set("user:1", new User("lili", "123456"));
        User user = (User) jsonRedisTemplate.opsForValue().get("user:1");
        log.info("Storage object: {}", user);
    }

}

Source Address

Source code for this chapter: https://gitee.com/gongm_24/spring-boot-tutorial.git

Concluding remarks

Here's how the other types of Redis work

  • opsForValue: corresponding String
  • opsForZSet: corresponding ZSet (ordered set)
  • opsForHash: corresponding Hash
  • opsForList: corresponding List (list)
  • opsForSet: corresponding Set (set)
  • opsForGeo: corresponding GEO (geographic location)

Reference resources

extend

Redis related data

The spring-data-redis document: https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/#new-in-2.0.0
Redis documentation: https://redis.io/documentation
Redis Chinese Documentation: http://www.redis.cn/commands.html

153 original articles were published, 22 were praised, 100,000 visits+
Private letter follow

Tags: Redis Spring Jedis Docker

Posted on Fri, 10 Jan 2020 17:16:18 -0800 by mountaindave