springboot2.x:springboot集成redis

     2022-05-20     562

关键词:

Redis 简介

什么是 Redis

Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库。

Redis 与其他 key-value 缓存(如 Memcached )相比有以下三个特点:

1.Redis 支持数据的持久化,它可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
2.Redis 不仅仅支持简单的 key-value 类型的数据,同时还提供 list,set,zset,hash 等数据结构的存储。
3.Redis 支持数据的备份,即 master-slave 模式的数据备份。

Redis 优势如下:

1.性能极高。Redis 能读的速度是 110000 次/s,写的速度是 81000 次/s。
2.丰富的数据类型。Redis 支持二进制案例的 Strings,Lists,Sets 及 Ordered Sets 数据类型操作。
3.原子性。Redis 所有的操作都是原子性的,意思是要么成功执行要么失败完全不执行。单个操作是原子性的,多个操作也是,通过 MULTI 和 EXEC 指令抱起来。
4.丰富的特性。Redis 还支持 publish/subscribe,通知,key 过期等特性。

Spring Boot 集成 Redis

1.在项目中添加依赖

<?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.1.9.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.zwqh</groupId>
    <artifactId>spring-boot-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-redis</name>
    <description>spring-boot-redis</description>

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

    <dependencies>

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

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

查看 jar 包时发现,Spring Data Redis 下 org.springframework.data.redis.connection 包路径下面默认有两个包 jedis 和 lettuce,这说明 Spring Boot 已经默认包装适配了这两个 Redis 客户端。

在 springboot 1.5.x版本的默认的Redis客户端是 Jedis实现的,springboot 2.x版本中默认客户端是用 lettuce实现的。

Lettuce 与 Jedis 比较

LettuceJedis 的都是连接 Redis Server的客户端。

Jedis 在实现上是直连 redis server,多线程环境下非线程安全,除非使用连接池,为每个 redis实例增加物理连接。


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


下面我们分别使用 Lettuce 和 Jedis 来集成 Redis 服务

2. Lettuce 集成 Redis 服务

导入依赖

由于 Spring Boot 2.X 默认集成了 Lettuce ,所以无需导入。

application.properties配置文件

################ Redis 基础配置 ##############
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=zwqh
# 链接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000
################ Redis 线程池设置 ##############
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

自定义 RedisTemplate

默认情况下的模板只能支持 RedisTemplate<String,String>,只能存入字符串,很多时候,我们需要自定义 RedisTemplate ,设置序列化器,这样我们可以很方便的操作实例对象。如下所示:

@Configuration
public class LettuceRedisConfig {

    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

序列化实体类

public class UserEntity implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 5237730257103305078L;
    
    private Long id;
    private String userName;
    private String userSex;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserSex() {
        return userSex;
    }
    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }
    
}

单元测试


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTests {

    @Autowired
    private RedisTemplate<String, String> strRedisTemplate;
    @Autowired
    private RedisTemplate<String, Serializable> serializableRedisTemplate;
    
    @Test
    public void testString() {
        strRedisTemplate.opsForValue().set("strKey", "zwqh");
        System.out.println(strRedisTemplate.opsForValue().get("strKey"));
    }
    
    @Test
    public void testSerializable() {
        UserEntity user=new UserEntity();
        user.setId(1L);
        user.setUserName("朝雾轻寒");
        user.setUserSex("男");       
        serializableRedisTemplate.opsForValue().set("user", user);      
        UserEntity user2 = (UserEntity) serializableRedisTemplate.opsForValue().get("user");
        System.out.println("user:"+user2.getId()+","+user2.getUserName()+","+user2.getUserSex());
    }

}

执行结果如下:
技术图片
得到我们预期的结果。

3.Jedis 集成 Redis 服务

pom 文件

<?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.1.9.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.zwqh</groupId>
    <artifactId>spring-boot-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-redis</name>
    <description>spring-boot-redis</description>

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

    <dependencies>

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

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

        <!-- Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <!-- 排除lettuce包 -->
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 添加jedis客户端 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties配置文件

################ Redis 基础配置 ##############
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=zwqh
# 链接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000
################ Redis 线程池设置 ##############
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.jedis.pool.min-idle=0

JedisRedisConfig

@Configuration
public class JedisRedisConfig {

    @Value("${spring.redis.database}")
    private int database;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    /**
     * 连接池配置信息
     */

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大连接数
        jedisPoolConfig.setMaxTotal(maxActive);
        // 当池内没有可用连接时,最大等待时间
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 最大空闲连接数
        jedisPoolConfig.setMinIdle(maxIdle);
        // 最小空闲连接数
        jedisPoolConfig.setMinIdle(minIdle);
        // 其他属性可以自行添加
        return jedisPoolConfig;
    }

    /**
     * Jedis 连接
     * 
     * @param jedisPoolConfig
     * @return
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling()
                .poolConfig(jedisPoolConfig).and().readTimeout(Duration.ofMillis(timeout)).build();
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }

    /**
     * 缓存管理器
     * 
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        return RedisCacheManager.create(connectionFactory);
    }

    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(JedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(jedisConnectionFactory(jedisPoolConfig()));
        return redisTemplate;
    }

}

单元测试同上

出现预期结果。

总结

上面介绍了 Spring Boot 2.X 如何通过 Lettuce 和 Jedis 来集成 Redis 服务,按项目需求,我们也可以自定义操作类来实现数据操作。

示例代码

github

码云

非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.

原文标题:Spring Boot 2.X(六):Spring Boot 集成Redis

原文地址:https://www.zwqh.top/article/info/11

(汇总)springboot实践折腾记&springboot2.x实践记

SpringBoot2.x实践记SpringBoot2.x实践记:Retry(annotion)SpringBoot2.x实践记:GsonSpringBoot2.x实践记:MailSpringBoot2.x实践记:H2DatabaseSpringBoot实践折腾记SpringBoot实践折腾记(1&# 查看详情

《springboot免费教程》连载目录

...Star关注支持一下,随时获得更新信息!快速入门SpringBoot2.x基础教程:版本关系SpringBoot2.x基础教程:快速入门SpringBoot2.x基础教程:工程结构推荐配置详解SpringBoot2.x基础教程:配置文件详解SpringBoot2.x基础教... 查看详情

《springboot免费教程》连载目录

...Star关注支持一下,随时获得更新信息!快速入门SpringBoot2.x基础教程:版本关系SpringBoot2.x基础教程:快速入门SpringBoot2.x基础教程:工程结构推荐配置详解SpringBoot2.x基础教程:配置文件详解SpringBoot2.x基础教... 查看详情

2018最新springboot2.0教程(零基础入门)

一、零基础快速入门SpringBoot2.01、SpringBoot2.x课程全套介绍和高手系列知识点简介:介绍SpringBoot2.x课程大纲章节java基础,jdk环境,maven基础2、SpringBoot2.x依赖环境和版本新特性说明简介:讲解新版本依赖环境和springboot2新特性概述3... 查看详情

springboot2.x集成单节点redis

Springboot2.x集成单节点Redis说明在Springboot1.x版本中,默认使用Jedis客户端来操作Redis,而在Springboot2.x版本中,默认使用Lettuce客户端来操作Redis。Springboot提供了RedisTemplate来统一封装了对Redis操作,开发者只需要使用RedisTemplate就可以... 查看详情

springboot2.x配置文件讲解

SpringBoot2.x配置文件讲解简介:SpringBoot2.x常见的配置文件xml、yml、properties的区别和使用xml、properties、json、yaml1、常见的配置文件xx.yml,xx.properties,1)YAML(YetAnotherMarkupLanguage)写YAML要比写XML快得多(无需关注标签或引号)使用空格Spa... 查看详情

springboot2.x教程-thymeleaf原理是什么

layout:posttitle:SpringBoot2.x教程-Thymeleaf原理是什么categories:SpringBootdescription:SpringBoot2.x教程-Thymeleaf原理是什么keywords:SpringBoot,Spring,Thymeleaf---如要要理清楚Thymeleaf的原理,那么就要从模板引擎的原理说起。Thymeleaf只不过是众多模板 查看详情

springboot2.x-springboot整合amqp之rabbitmq

文章目录SpringBoot2.X-SpringBoot整合AMQP之RabbitMQRabbitMQ简介引入依赖编写配置编写接口启用Rabbit注解消息监听消息测试SpringBoot2.X-SpringBoot整合AMQP之RabbitMQSpringBoot2整合RabbitMQ案例。RabbitMQ简介简介RabbitMQ是一个由erlang开发的AMQP(AdvanvedMess... 查看详情

springboot2.x:springboot

 几个重要的事件回调机制: 1、配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunlistener 2、需要放在ioc容器中     3、ApplicationRunner &nbs 查看详情

springboot2.x入门——helloworld

Springboot2.x入门——helloWorld一、简介1.1Springboot简介SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化... 查看详情

springboot2.x搭建springbootadmin2.x

...用2.0.5SpringBootAdmin基于Eureka进行Client发现,Eureka搭建参见SpringBoot2.x搭建EurekaSpringBootAdmin项目文档参见SpringBootAdmin参考文档2创建项目在SpringBoot项目生成器中,输入Group和Artifact,如下配置:3编辑pom.xml文件p 查看详情

springboot2.x版本整合redis集群

参考技术A启动Redis集群搭建方式SpringBoot1.x版本默认使用jedis连接,2.x版本使用lettuce连接ymlyml测试 查看详情

springboot2.x文件上传实战

设置上传的文件大小:@ConfigurationpublicclassfileConfigure{@BeanpublicMultipartConfigElementmultipartConfigElement(){MultipartConfigFactoryfactory=newMultipartConfigFactory();//单个文件的大小factory.setMaxFileSize("20 查看详情

springcloud:升级到springboot2.x/finchley.release遇到的坑

springboot2.x已经出来好一阵了,而且springcloud的最新Release版本Finchley.RELEASE,默认集成的就是springboot2.x,这几天将一个旧项目尝试着从低版本升级到2.x,踩坑无数,记录一下:一、gradle的问题springboot2.x要求gradle版本不能太旧,先... 查看详情

springboot2.x参数校验(代码片段)

本文主要对SpringBoot2.x参数校验进行简单总结,其中SpringBoot使用的2.4.5版本。一、引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>&l 查看详情

springboot2.x上传文件限制大小

SpringBoot1.3.x multipart.maxFileSizemultipart.maxRequestSizeSpringBoot1.4.xand1.5.xspring.http.multipart.maxFileSizespring.http.multipart.maxRequestSizeSpringBoot2.xspring.servlet.multipart.maxF 查看详情

springboot2.x版本整合redis(单机/集群)(使用lettuce)

在springboot1.x系列中,其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce。此处springboot2.x,所以使用的是Lettuce。关于jedis跟lettuce的区别:Lettuce和Jedis的定位都是Redis的client,所以他们当然可以直接连接redisserver。Jedis在实现... 查看详情

springboot2.x单元测试

简介:讲解SpringBoot的单元测试 1、引入相关依赖 <!--springboot程序测试依赖,如果是自动创建项目默认添加--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</arti 查看详情