SpringBoot - Redis相关
in 后端 with 0 comment

SpringBoot - Redis相关

in 后端 with 0 comment

SpringBoot整合Redis相关记录

连接池 - 默认Lettuce客户端

整合springboot和redis,使用如下maven依赖:

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

发现默认没使用连接池,查了一番才知道,springboot 1.X版本的默认使用Jedis客户端,带有连接池直接配置可用。2.X版本以后会默认使用Lettuce客户端,如果要使用连接池还需要添加依赖(不添加依赖直接配置链接池会报错):

<!-- redis连接池 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

并且配置文件修改为:

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
    password: # 密码(默认为空)
    timeout: 6000  # 连接超时时长(毫秒)
    lettuce:
      pool:
        max-active: 1000  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1      # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10      # 连接池中的最大空闲连接
        min-idle: 5      # 连接池中的最小空闲连接

更换Jedis客户端

既然官方更换默认客户端,自然是比原来的更优,Lettuce的连接是基于Netty的,能更好的利用资源。但如果想换成Jedis,也可以很简单的更换。
首先是依赖中排除Lettuce,然后引入Jedis:

<!-- redis支持 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

配置文件连接池部分改为Jedis就行了:

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
    password: # 密码(默认为空)
    timeout: 6000  # 连接超时时长(毫秒)
    jedis:
      pool:
        max-active: 1000  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1      # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10      # 连接池中的最大空闲连接
        min-idle: 5      # 连接池中的最小空闲连接
Responses