SpringBoot2.0 快速集成 Jedis客户端 连接 redis 服务

转自:  https://blog.csdn.net/ljk126wy/article/details/93303627

SpringBoot2.0 快速集成 Jedis客户端 连接 redis 服务
1.简单介绍 redis
2.自动配置方式集成Jedis客户端
2.1引入Jedis依赖
2.2 定义 Jedis Properties类
2.3 定义 Jedis客户端自动配置类
4.测试
1.简单介绍 redis
redis 官方介绍如下:

Redis is an open source (BSD licensed), in-memory data structure
store, used as a database, cache and message broker. It supports data
structures such as strings, hashes, lists, sets, sorted sets with
range queries, bitmaps, hyperloglogs, geospatial indexes with radius
queries and streams. Redis has built-in replication, Lua scripting,
LRU eviction, transactions and different levels of on-disk
persistence, and provides high availability via Redis Sentinel and
automatic partitioning with Redis Cluster

Redis是一个开放源代码(BSD许可)内存中的数据结构存储,用作数据库、缓存和消息代理。它支持字符串(strings)、哈希(hashes)、列表(lists)、集合(sets)、带范围查询的排序集合(sortedsets )、位图(bitmaps)、超日志(hyperloglogs)、带半径查询和流的地理空间索引等数据结构。Redis具有内置复制、lua脚本、transactions 、事务和不同级别的磁盘持久性,并通过Redis Sentinel和Redis群集的自动分区提供高可用性

2.自动配置方式集成Jedis客户端
在配置你首先应该在本地或者远程的机器上安装 redis 服务,可以参考 Windows 安装 Redis 教程 其他可以百度或者期待我后续的博客教程。

通过引入 spring-boot-starter-data-redis 我们就可以使用 RedisTemplate 对象来进行对 redis的各种操作,实际上是 RedisTemplate 是在 Lettuce和 Jedis 的之上进行封装 ,默认情况是使用 Lettuce。

但是我们今天要介绍如何绕开 RedisTemplate 通过 SpringBoot 自动配置的功能来使用Jedis 客户端连接 redis。
自动配置版 Jedis 操作总共分三部

引入 jedis 依赖
定义 Jedis Properties类
定义 Jedis 自动配置类
2.1引入Jedis依赖
首先引入 Jedis 的依赖代码如下:

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

因为 SpringBoot spring-boot-starter-data-redis 集成了 Jedis 所以我们直接引入jedis 依赖 无需在关系jedis的版本号了。

2.2 定义 Jedis Properties类
通过 JedisProperties 配置信息类来 设置连接 reids服务相关配置。例如 注解ip ,服务端口 具体各种配置请参看下面代码的属性注释。

关于配置信息类注解的介绍:

@Component: 声明该注解的类是 Spring的 Bean
@ConfigurationProperties: 通过@ConfigurationProperties 注解 prefix参数定义在 application.properties 中的配置的前缀 。 SpringBoot 通过该注解可以完成将application.properties 中配置的信息注入到JedisProperties 中。

例如 在application.properties 中配置 如下信息:

spring.jedis.host=127.0.0.1
spring.jedis.port=6380

SpringBoot 会帮我们将 application.properties 中的host 和port 配置的值注入到 JedisProperties 中的 host 和 port 成员属性中。

具体代码如下:

@Component
@ConfigurationProperties(prefix="spring.jedis")
public class JedisProperties {

    /**Redis服务器主机ip*/
    private String host = "localhost";
    /**Redis服务器登录密码*/
    private String password;
    /**Redis服务器端口*/
    private int port = 6379;
    /**连接超时时间*/
    private int timeout = 2000;
    /**连接池配置*/
    private Pool pool = new Pool();
    //...省略 get and set 方法
}

public class Pool {
    /**最大连接数, 默认8个*/
    private int maxTotal = 8;
    /**最大空闲连接数, 默认8个*/
    private int maxIdle = 8;
    /**最小空闲连接数, 默认0*/
    private int minIdle = 0;
    private long maxWaitMillis;
    //...省略 get and set 方法    
    }

redis 配置说明

如果你启动的是本地 redis服务 那么你根本不需要进行任何配置就可以操作 redis了。

如果你的redis在安装在远程的服务器中。那么你需要进行如下配置:

# 必选配置
spring.jedis.host= Redis服务器主机ip
spring.jedis.port=Redis服务器端口
# 如果你redis服务配置了密码这个就必须要进行配置。
spring.jedis.password=Redis服务器登录密码
# 非必选配置
spring.jedis.timeout=连接超时时间
spring.jedis.pool.max-total=最大连接数, 默认8个
spring.jedis.pool.max-idle=最大空闲连接数, 默认8个
spring.jedis.pool.min-idle=最小空闲连接数, 默认0
spring.jedis.pool.max-wait-millis=获取连接时的最大等待毫秒数

2.3 定义 Jedis客户端自动配置类
自动配置是SpringBoot 的核心功能之一,在SpringBoot 实战一书中是这么介绍的:针对很多Spring 应用程序常见的应用功能,SpringBoot 能自动提供相关配置。它就像是一个样板配置。并且SprignBoot 自动配置非常灵活,我们也可以通过覆盖自动配置来完成自定义的配置。

关于自动配置中注解介绍:

@Configuration + @Bean: javaConfig 操作组合 和在xml中配置Bean是一个效果。

@ConditionalOnClass: 该注解的参数对应的类必须存在,否则不解析该注解修饰的配置类

@EnableConfigurationProperties: 会将会JedisProperties作为一个Bean引入JedisAutoConfiguration 中

@ConditionalOnMissingBean: 该注解表示,如果存在它修饰的类的Bean,则不需要再创建这个 Bean;可以给该注解传入参数例如@ConditionOnMissingBean(name = “example”),这个表示如果name为“example”的bean存在,这该注解修饰的代码块不执行。

介绍完注解作用下面基本就是 配置JedisPoolConfig 然后生成 JedisPool 对象。具体请参考下面的代码:

@Configuration
@ConditionalOnClass(JedisPool.class)
@EnableConfigurationProperties(JedisProperties.class)
public class JedisAutoConfiguration {
    private JedisProperties jedisProperties;
    
    public JedisAutoConfiguration(JedisProperties jedisProperties) {
        this.jedisProperties = jedisProperties;
    }
    
    @Bean
    @ConditionalOnMissingBean(JedisPool.class)
    public JedisPool jedisPool() {
        
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(jedisProperties.getPool().getMaxIdle());
        poolConfig.setMaxTotal(jedisProperties.getPool().getMaxTotal());
        poolConfig.setMaxWaitMillis(jedisProperties.getPool().getMaxWaitMillis() * 1000);
        
        JedisPool jedisPool = new JedisPool(poolConfig, jedisProperties.getHost(), jedisProperties.getPort(),
                jedisProperties.getTimeout()*1000, jedisProperties.getPassword(), 0);
        return jedisPool;
    }
}

4.测试
功能开发完毕就要对开发的功能进行测试了,
SpringBoot的测试 需要在测试类上引入 @RunWith() 和 @SpringBootTest 注解。
通过 @Autowired 将JedisPool 注入到测试类中
然后通过JedisPool 获取 Jedis对象 就可以操作 redis了。

测试具体代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class JedisTest {
    
    @Autowired
    private JedisPool jedisPool;
    @Test
    public void set() {
        Jedis jedis = jedisPool.getResource();
        jedis.set("abc", "123");
    }
    
    @Test
    public void get() {
        Jedis jedis = jedisPool.getResource();
        String value = jedis.get("abc");
        System.out.println(value);
    }
}

SpringBoot2.0 快速集成 Jedis客户端 连接 redis 服务 具体代码请访问我的 github 进行查看。

github 链接:https://github.com/zhuoqianmingyue/springbootexamples/tree/master/lesson17_redis
--------------------- 
作者:IT乌托邦-桌前明月 
来源:CSDN 
原文:https://blog.csdn.net/ljk126wy/article/details/93303627 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_36688928/article/details/93465928