Spring Boot 整合 Redis 相当简单,它利用了 Spring Data Redis 项目,使得我们可以在 Spring Boot 应用中轻松地操作 Redis。以下是如何整合 Redis 到 Spring Boot 应用的基本步骤:

1. 添加依赖

首先,在你的 pom.xml 文件中添加 Spring Boot Data Redis 的依赖:

<dependencies>  
    <!-- Spring Boot Redis Starter -->  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-data-redis</artifactId>  
    </dependency>  
      
    <!-- 如果你使用的是 Lettuce 连接池,还需要添加这个依赖 -->  
    <dependency>  
        <groupId>io.lettuce</groupId>  
        <artifactId>lettuce-core</artifactId>  
    </dependency>  
      
    <!-- 其他依赖 -->  
</dependencies>

如果你使用的是 Gradle,那么在 build.gradle 文件中添加如下依赖:

dependencies {  
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'  
    implementation 'io.lettuce:lettuce-core'  
      
    // 其他依赖  
}

2. 配置 Redis

在 application.properties 或 application.yml 文件中添加 Redis 的配置信息:

application.properties 示例

spring.redis.host=localhost  
spring.redis.port=6379  
spring.redis.password=yourpassword # 如果有密码的话  
spring.redis.jedis.pool.max-active=10  
spring.redis.jedis.pool.max-wait=-1ms  
spring.redis.jedis.pool.max-idle=5  
spring.redis.jedis.pool.min-idle=0  
spring.redis.timeout=5000

application.yml 示例

spring:  
  redis:  
    host: localhost  
    port: 6379  
    password: yourpassword # 如果有密码的话  
    jedis:  
      pool:  
        max-active: 10  
        max-wait: -1ms  
        max-idle: 5  
        min-idle: 0  
    timeout: 5000

这里要说的是:

Lettuce和Jedis两者都是Java连接Redis的客户端

选择使用Lettuce而不是Jedis的原因如下:

线程安全性:
  • Lettuce 是基于 Netty 构建的,它使用异步和事件驱动的方式处理连接。因此,它可以在多个线程之间共享一个连接而不需要额外的同步,因此在高并发环境下更高效。
  • Jedis 是基于阻塞 I/O 的,并且不是线程安全的,如果在多个线程中共享同一个 Jedis 实例,需要使用连接池进行同步管理,这可能引入额外的复杂性。
连接方式:
  • Lettuce 支持基于 Reactive Streams 的响应式编程模型,能够更好地与 Spring Reactor、Project Reactor 等框架集成,提供异步和非阻塞的操作。
  • Jedis 是同步的,并且在执行某些操作时会阻塞线程,这可能会影响应用程序的性能和响应性。
性能和扩展性:
  • Lettuce 的设计目标是高性能和扩展性,它可以更好地利用 Redis 4.0 中引入的一些新特性(如 Redis Sentinel 和 Redis Cluster)。
  • Jedis 的设计目标更偏向于简单易用,对于一些特殊的 Redis 集群模式可能支持不够完善。
维护和更新:
  • Lettuce 是一个活跃的项目,并且持续地得到更新和改进。
  • Jedis 在某些方面已经相对稳定,并且在一段时间内没有大的更新。

3. 创建 Redis 配置类

如果需要自定义 Redis 的配置(比如序列化器),可以创建一个配置类:

import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.data.redis.connection.RedisConnectionFactory;  
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.data.redis.serializer.StringRedisSerializer;  
  
@Configuration  
public class RedisConfig {  
  
    @Bean  
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {  
        RedisTemplate<String, Object> template = new RedisTemplate<>();  
        template.setConnectionFactory(redisConnectionFactory);  
  
        // 使用 StringRedisSerializer 来序列化和反序列化 key 值  
        template.setKeySerializer(new StringRedisSerializer());  
        // 使用 JdkSerializationRedisSerializer 来序列化和反序列化 value 值  
        // 你也可以自定义序列化器  
        template.setValueSerializer(new GenericToStringSerializer<>(Object.class));  
          
        template.afterPropertiesSet();  
        return template;  
    }  
}

4. 使用 RedisTemplate 或 StringRedisTemplate

在 Spring Boot 应用中,你可以注入 RedisTemplate 或 StringRedisTemplate 来操作 Redis:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.stereotype.Service;  
  
@Service  
public class RedisService {  
  
    private final RedisTemplate<String, Object> redisTemplate;  
  
    @Autowired  
    public RedisService(RedisTemplate<String, Object> redisTemplate) {  
        this.redisTemplate = redisTemplate;  
    }  
  
    public void setValue(String key, Object value) {  
        redisTemplate.opsForValue().set(key, value);  
    }  
  
    public Object getValue(String key) {  
        return redisTemplate.opsForValue().get(key);  
    }  
      
    // 其他操作...  
}

5. 编写测试

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
 
import java.util.concurrent.TimeUnit;
 
@SpringBootTest
public class RedisTest {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    @Test
    //测试redis
    void contextLoads2() {
        //添加缓存键值对name:mijiu并设置过期时间为1小时
        stringRedisTemplate.opsForValue().set("name","mijiu",10, TimeUnit.SECONDS);
        System.out.println(stringRedisTemplate.opsForValue().get("name"));
 
    }
}
03-29 06:11