【SpringBoot】整合Redis(使用spring-boot-starter-data-redis)

文章目录

  • 前言
    • Jedis和Lettuce
    • spring-data-redis
    • spring-boot-starter-data-redis
  • 操作Redis数据
    • pom
    • properties
    • config
  • Redis分布式锁
    • 方式一(使用JedisCluster)
      • pom
      • properties
      • config
    • 方式二(使用Redisson)

前言

Jedis和Lettuce

Jedis Lettuce的都是连接Redis Server客户端程序
Jedis在实现上是直连redis server,多线程环境下非线程安全,除非使用连接池,为每个Jedis实例增加物理连接
Lettuce基于Netty(事件驱动模型)的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例

spring-data-redis

Spring Data Redis提供了从Spring应用程序轻松配置和访问Redis的功能。它提供了用于与存储交互的低级和高级抽象,使用户不必再关注基础设施spring-data-redis的优势:可以方便地更换Redis的Java客户端,比Jedis多了自动管理连接池的特性,方便与其他Spring框架进行搭配使用如:SpringCache

spring-data-redis提供了一个RedisConnectionFactory接口,通过它可以生成一个RedisConnection接口对象,而RedisConnection接口对象是对Redis底层接口的封装。例如,我们使用的Jedis驱动,那么Spring就会提供RedisConnection接口的实现类JedisConnection去封装原有的Jedis(redis.clients.jedis.Jedis)对象。

public interface RedisConnectionFactory extends PersistenceExceptionTranslator {
   

	/**
	 * Provides a suitable connection for interacting with Redis.
	 *
	 * @return connection for interacting with Redis.
	 */
	RedisConnection getConnection();

	/**
	 * Provides a suitable connection for interacting with Redis Cluster.
	 *
	 * @return
	 * @since 1.7
	 */
	RedisClusterConnection getClusterConnection();

	/**
	 * Specifies if pipelined results should be converted to the expected data type. If false, results of
	 * {@link RedisConnection#closePipeline()} and {RedisConnection#exec()} will be of the type returned by the underlying
	 * driver This method is mostly for backwards compatibility with 1.0. It is generally always a good idea to allow
	 * results to be converted and deserialized. In fact, this is now the default behavior.
	 *
	 * @return Whether or not to convert pipeline and tx results
	 */
	boolean getConvertPipelineAndTxResults();

	/**
	 * Provides a suitable connection for interacting with Redis Sentinel.
	 *
	 * @return connection for interacting with Redis Sentinel.
	 * @since 1.4
	 */
	RedisSentinelConnection getSentinelConnection();
}

在SpringDataRedis中是使用RedisConnection接口对象去操作Redis的。要获取RedisConnection接口对象,是通过RedisConnectionFactory接口去生成的,所以第一步要配置的便是这个工厂了,而配置这个工厂主要是配置Redis的连接池,对于连接池可以限定其最大连接数、超时时间等属性。

@Configuration
public class RedisConfig {
   

    private RedisConnectionFactory connectionFactory = null;

	/**
	 * 若使用了spring-boot-autoconfigure,只需在application.yml中配置spring.redis和spring.redis.jedis/lettuce即可,JedisConnectionConfiguration/LettuceConnectionConfiguration会自动注册JedisConnectionFactory/LettuceConnectionFactory-Bean
	 */
    @Bean(name = "RedisConnectionFactory")
    public RedisConnectionFactory initRedisConnectionFactory() {
   
        if (this.connectionFactory != null) {
   
            return this.connectionFactory;
        }
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大空闲数
        poolConfig.setMaxIdle(30);
        // 最大连接数
        poolConfig.setMaxTotal(50);
        // 最大等待毫秒数
        poolConfig.setMaxWaitMillis(2000);
        // 创建Jedis连接工厂
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig);
        // 获取单机的Redis配置
        RedisStandaloneConfiguration rsCfg = connectionFactory.getStandaloneConfiguration();
        ConnectionFactory.setHostName("192.168.11.131");
        ConnectionFactory.setPort(6379);
        ConnectionFactory.setPassword("123456");
        this.connectionFactory = connectionFactory;
        return connectionFactory;
    }
    //......
}

但是我们在使用一条连接时,要先从RedisConnectionFactory工厂获取,然后在使用完成后还要自己关闭它。SpringDataRedis为了进一步简化开发,提供了RedisTemplateRedisTemplate是一个强大的类,首先它会自动从RedisConnectionFactory工厂中获取连接,然后执行对应的Redis命令,在最后还会关闭Redis的连接

spring-boot-starter-data-redis

spring-boot-starter-redis 在2017年6月后就改为了 spring-boot-starter-data-redis,是基于spring-data-redis开发的Redis场景启动器。

阅读源码发现spring-boot-starter-data-redis没有任何代码,只是引入了spring-data-redis的依赖,其实Redis的自动配置代码都在spring-boot-autoconfigure
【SpringBoot】整合Redis(使用spring-boot-starter-data-redis)_第1张图片
关于spring-boot-starter-data-redis的源码分析参考spring-boot-starter-data-redis源码解析与使用实战

SpringBoot2.x 后默认使用的不在是Jedis而是lettuce,所以spring-boot-starter-data-redis 依赖了:lettuce-corespring-data-redisspring-boot-starter

操作Redis数据

推荐使用RedisTemplate

pom

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
    <version>2.1.3.RELEASEversion>
dependency>


<dependency>
	<groupId>org.apache.commonsgroupId

你可能感兴趣的:(SpringBoot,Ehcache/Redis,redis,spring,boot)