Spring Data Redis 教程

Spring Data Redis 配置Lettuce连接器

Lettuce 是一种可伸缩,线程安全,完全非阻塞的 Redis 客户端,多个线程可以共享一个 RedisConnection,它利用 Netty NIO 框架来高效地管理多个连接,从而提供了异步和同步数据访问方式,用于构建非阻塞的反应性应用程序。

Lettuce 连接器是 Spring Data Redis 通过 org.springframework.data.redis.connection.lettuce 包支持的基于 Netty 的开源连接器。

下面将介绍怎样在 Spring Boot 中引入 Spring Data Redis,且配置使用 Lettuce 作为连接 Redis 的驱动。

配置依赖

下面是 Spring Boot 的 maven 配置文件,内容如下:

<?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.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hxstrive.redis</groupId>
    <artifactId>redis_learn_spring_data_lettuce</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redis_learn_spring_data_lettuce</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- 添加 lettuce 依赖 -->
        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>6.1.9.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>

配置 Configuration 类

添加如下 Configuration 配置类,配置 Lettuce 连接器和 RedisTemplate 模板对象。代码如下:

package com.hxstrive.redis.redis_learn_spring_data_lettuce.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 配置 Lettuce 连接工厂和 RedisTemplate 对象
 * @author hxstrive.com 2022/8/4
 */
@Configuration
public class AppConfig {

    /**
     * 配置 Lettuce 连接器
     */
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(
                new RedisStandaloneConfiguration("127.0.0.1", 6379));
    }

    /**
     * 配置 RedisTemplate 对象
     */
    @Bean
    public RedisTemplate<String,String> redisTemplate(
            RedisConnectionFactory connectionFactory) {
        RedisTemplate<String,String> template = new RedisTemplate<>();
        // 设置 Redis 连接工厂
        template.setConnectionFactory(connectionFactory);

        // 设置 Key 序列化器
        template.setKeySerializer(new StringRedisSerializer());
        // 设置 Value 序列化器
        template.setValueSerializer(new StringRedisSerializer());
        // 设置默认序列化器
        template.setDefaultSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();

        return template;
    }
}

示例代码

下面将通过 @SpringBootTest 注解编写一个简单的 Spring Boot 测试类,用来测试 RedisTemplate 是否能够正常的向 Redis 写入数据,和从 Redis 获取数据。代码如下:

package com.hxstrive.redis.redis_learn_spring_data_lettuce;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
public class HelloWorld {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Test
    void contextLoads() {
        System.out.println("redisTemplate = " + redisTemplate);

        // 向 Redis 写入值
        ValueOperations<String,String> ops = redisTemplate.opsForValue();
        ops.set("lettuce-key", "hello, lettuce");

        // 从 Redis 获取值
        String value = ops.get("lettuce-key");
        System.out.println(value);
    }

}

运行程序结果如下:

redisTemplate = org.springframework.data.redis.core.RedisTemplate@6981f8f3
hello, lettuce

Process finished with exit code 0

上面在创建 Lettuce 连接器时,仅仅指定了 Redis 服务器的 IP 地址和端口。其实,还可以指定一些 Lettuce 特定连接参数。默认情况下,由 LettuceConnectionFactory 创建的所有 LettuceConnection 实例对于所有非阻塞和非事务性操作共享相同的线程安全本机连接。

如果要每次都使用专用连接,请将 shareNativeConnection 设置为 false。 如果 shareNativeConnection 设置为 false,LettuceConnectionFactory 也可以配置为使用 LettucePool 来池化阻塞和事务连接或所有连接。

Lettuce 与 Netty 的本机传输集成,让您使用 Unix 域套接字与 Redis 通信。需确保包括与您的运行时环境匹配的适当本机传输依赖项。以下示例显示如何在 /var/run/redis.sock 为 Unix 域套接字创建一个 Lettuce 连接工厂:

@Configuration
public class AppConfig {
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(
            new RedisSocketConfiguration("/var/run/redis.sock"));
    }
}

注意:Netty 目前支持 OS-native 传输的 epoll (Linux) 和 kqueue (BSD/macOS) 接口。

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号