Jedis client and SpringDataRedis client

Table of contents

3.Redis Java client

3.1.Jedis client

3.1.1.Quick Start

3.1.2. Connection pool

3.2.SpringDataRedis client

3.2.1.Quick Start

3.2.2. Custom serialization

3.2.3.StringRedisTemplate


3.Redis Java client

3.1.Jedis client

Jedis' official website address: GitHub - redis/jedis: Redis Java client

3.1.1.Quick Start

First create a project:

Let’s get started quickly:

1) Introduce dependencies:

<!--jedis-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.7.0</version>
</dependency>
<!--单元测试-->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.7.0</version>
    <scope>test</scope>
</dependency>

2) Establish connection

Create a new unit test class with the following content:

@BeforeEach
    void setUp() {
        // 1.建立连接
         jedis = new Jedis("192.168.200.xxx", 6379);
        // 2.设置密码
        jedis.auth("xxxx");
        // 3.选择库
        jedis.select(0);
    }

3) Test:

@Test
void testString() {
    // 存入数据
    String result = jedis.set("name", "虎哥");
    System.out.println("result = " + result);
    // 获取数据
    String name = jedis.get("name");
    System.out.println("name = " + name);
}

@Test
void testHash() {
    // 插入hash数据
    jedis.hset("user:1", "name", "Jack");
    jedis.hset("user:1", "age", "21");

    // 获取
    Map<String, String> map = jedis.hgetAll("user:1");
    System.out.println(map);
}

 

4) Release resources

@AfterEach
void tearDown() {
    if (jedis != null) {
        jedis.close();
    }
}

3.1.2. Connection pool

Jedis itself is thread-unsafe, and frequent creation and destruction of connections will cause performance losses. Therefore, we recommend that you use Jedis connection pool instead of Jedis direct connection.

package com.heima.jedis.util;

import redis.clients.jedis.*;

public class JedisConnectionFactory {

    private static JedisPool jedisPool;

    static {
        // 配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(8);
        poolConfig.setMaxIdle(8);
        poolConfig.setMinIdle(0);
        poolConfig.setMaxWaitMillis(1000);
        // 创建连接池对象,参数:连接池配置、服务端ip、服务端端口、超时时间、密码
        jedisPool = new JedisPool(poolConfig, "192.168.200.xxx", 6379, 1000, "xxx");
    }

    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

3.2.SpringDataRedis client

SpringData is a data operation module in Spring, including the integration of various databases. The integration module for Redis is called SpringDataRedis. Official website address: Spring Data Redis

  • Provides integration of different Redis clients (Lettuce and Jedis)

  • Provides RedisTemplate unified API to operate Redis

  • Support Redis publish-subscribe model

  • Supports Redis Sentinel and Redis Cluster

  • Supports reactive programming based on Lettuce

  • Supports data serialization and deserialization based on JDK, JSON, strings, and Spring objects

  • Supports JDKCollection implementation based on Redis

SpringDataRedis provides the RedisTemplate tool class, which encapsulates various operations on Redis. And the operation APIs of different data types are encapsulated into different types:

3.2.1.Quick Start

SpringBoot already provides support for SpringDataRedis, which is very simple to use.

First, create a new maven project, and then follow the steps below:

1) Introduce dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.heima</groupId>
    <artifactId>redis-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--common-pool-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <!--Jackson依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2) Configure Redis

spring:
  redis:
    host: 192.168.150.101
    port: 6379
    password: 123321
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: 100ms

3) Inject RedisTemplate

Because of SpringBoot's automatic assembly, we can just use it:

@SpringBootTest
class RedisStringTests {

    @Autowired
    private RedisTemplate redisTemplate;
}

4) Write tests

@SpringBootTest
class RedisStringTests {

    @Autowired
    private RedisTemplate edisTemplate;

    @Test
    void testString() {
        // 写入一条String数据
        redisTemplate.opsForValue().set("name", "虎哥");
        // 获取string数据
        Object name = stringRedisTemplate.opsForValue().get("name");
        System.out.println("name = " + name);
    }
}

3.2.2. Custom serialization

RedisTemplate can receive any Object as a value and write it to Redis:

However, the Object will be serialized into byte form before writing. The default is to use JDK serialization. The result is as follows: 

shortcoming:

  • Poor readability

  • Large memory usage

We can customize the serialization method of RedisTemplate, the code is as follows:

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        // 创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(connectionFactory);
        // 创建JSON序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = 
            							new GenericJackson2JsonRedisSerializer();
        // 设置Key的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置Value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        // 返回
        return template;
    }
}

 JSON serialization is used here instead of the default JDK serialization method. The final result is as follows:

The overall readability has been greatly improved, and Java objects can be automatically serialized into JSON strings, and JSON can be automatically deserialized into Java objects when querying. However, the corresponding class name during serialization is recorded in order to achieve automatic deserialization during query. This will bring additional memory overhead.

3.2.3.StringRedisTemplate

In order to save memory space, we can not use JSON serializer to process value, but use String serializer uniformly, which requires that only String type keys and values ​​can be stored. When Java objects need to be stored, the serialization and deserialization of the objects is done manually.

Because the serialization and deserialization during storage and reading are implemented by ourselves, SpringDataRedis will not write class information to Redis.

This usage is relatively common, so SpringDataRedis provides a subclass of RedisTemplate: StringRedisTemplate. Its key and value serialization method is String by default.

 This saves us the step of customizing the serialization method of RedisTemplate, but uses it directly:

@Autowired
private StringRedisTemplate stringRedisTemplate;
// JSON序列化工具
private static final ObjectMapper mapper = new ObjectMapper();

@Test
void testSaveUser() throws JsonProcessingException {
    // 创建对象
    User user = new User("虎哥", 21);
    // 手动序列化
    String json = mapper.writeValueAsString(user);
    // 写入数据
    stringRedisTemplate.opsForValue().set("user:200", json);

    // 获取数据
    String jsonUser = stringRedisTemplate.opsForValue().get("user:200");
    // 手动反序列化
    User user1 = mapper.readValue(jsonUser, User.class);
    System.out.println("user1 = " + user1);
}

Guess you like

Origin blog.csdn.net/m0_62609939/article/details/130583246