SpringBoot整合Redis

SpringData是Spring中数据操作的模块,包含对各种数据库的集成,其中对Redis的集成模块就叫做SpringDataRedis,官网地址:
https://spring.io/projects/spring-data-redis

(1)提供了对不同Redis客户端的整合(Lettuce和Jedis)

(2)提供了RedisTemplate统一API来操作Redis

(3)支持Redis的发布订阅模型

(4)支持Redis哨兵和Redis集群

(5)支持基于Lettuce的响应式编程

(6)支持基于JDK、JSON、字符串、Spring对象的数据序列化及反序列化

(7)支持基于Redis的JDKCollection实现


1、SpringDataRedis快速入门

SpringDataRedis中提供了RedisTemplate工具类,其中封装了各种对Redis的操作。并且将不同数据类型的操作API封装到了不同的类型中:

(1)SpringBoot已经提供了对SpringDataRedis的支持,使用非常简单:

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

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

(2)配置文件

spring:
  redis:
    host: 120.48.16.249
    port: 6379
    password: 111111
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: 100ms

(3)注入RedisTemplate

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
          // 插入一条string类型数据        
      	redisTemplate.opsForValue().set("name", "李四");
          // 读取一条string类型数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name = " + name);
    }

SpringDataRedis的使用步骤:

(1)引入
spring-boot-starter-data-redis依赖

(2)在application.yml配置Redis信息

(3)注入RedisTemplate

原文链接:,转发请注明来源!