SpringBoot集成Redis-6.x版本流程

发布于:2025-06-29 ⋅ 阅读:(19) ⋅ 点赞:(0)

SpringBoot集成Redis是我们常见的功能,今天我们分享一下:

前言:

1、pom包引用


        <!-- Redis Starter (默认使用 Lettuce) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- Jackson 序列化支持 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.3</version> <!-- Spring Boot 2.3.4 内置版本 -->
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.9.0</version> <!-- 兼容2.3.4的版本 -->
        </dependency>

       
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.8.RELEASE</version>
    </parent>

2、配置文件信息

# Redis 基础配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.database=0

# 连接池配置 明确使用commons-pool2连接池
spring.redis.lettuce.pool.enabled=true
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.timeout=5000ms

# 全局缓存过期时间 (单位: 秒)
spring.cache.redis.time-to-live=180

3、服务配置类

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;


@Configuration
@EnableCaching // 启用缓存注解
public class RedisConfig {

    /**
     * 自定义 RedisTemplate (解决乱码问题)
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // Key 使用 String 序列化
        template.setKeySerializer(new StringRedisSerializer());
        // Value 使用 JSON 序列化
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // Hash Value 使用 JSON 序列化
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 设置全局缓存过期时间 (3分钟)
     */
    @Bean
    public RedisCacheConfiguration cacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(3)) // 设置缓存默认过期时间
                .disableCachingNullValues()      // 不缓存 null 值
                .serializeValuesWith(
                        RedisSerializationContext.SerializationPair
                                .fromSerializer(new GenericJackson2JsonRedisSerializer())
                );
    }
}

4、业务伪代码

@Autowired
private RedisTemplate<String, Object> redisTemplate;

@Autowired
private ObjectMapper objectMapper;

1)保存并获取字符串

       redisTemplate.opsForValue().set("token", "123qaz", 3, TimeUnit.MINUTES);

        String json = (String) redisTemplate.opsForValue().get("token");

2)保存并获取对象

       String key = "user:" + user.getId();


        // 方法1:使用 RedisTemplate 自动序列化
        redisTemplate.opsForValue().set(key, user, 3, TimeUnit.MINUTES);

       // 方法1:直接获取对象 (自动反序列化)
        User user120 = (User) redisTemplate.opsForValue().get(key1);

       // 方法2:获取JSON字符串并转换
        /*
        String json = (String) redisTemplate.opsForValue().get(key);
        if(json != null) {
            return objectMapper.readValue(json, User.class);
        }
        */

3)保存并获取集合

        List<User> userList = new ArrayList<>();
        User user = new User();
        user.setArea("北京");
        user.setBsnm("北京站");
        user.setId(10);
        User user1 = new User();
        user1.setArea("昌平");
        user1.setBsnm("龙珠站");
        user1.setId(9);
        userList.add(user1);
        userList.add(user);
        String key12 = "user:" + user.getId()+":"+user1.getId();
        redisTemplate.opsForValue().set(key12, userList, 3, TimeUnit.MINUTES);
       //强制获取
       List<User> user12List = (List<User>) redisTemplate.opsForValue().get(key12);
      //标准安全获取



     /**
     * 从缓存获取用户列表
     */
    public List<User> getUserListFromCache(String key) {
        try {
            // 1. 从Redis获取数据
            Object cachedData = redisTemplate.opsForValue().get(key);
            if (cachedData == null) {
                return Collections.emptyList(); // 缓存不存在
            }
            // 2. 类型安全转换
            if (cachedData instanceof List) {
                // 3. 直接转换(当序列化配置正确时可用)
                return (List<User>) cachedData;
            } else if (cachedData instanceof String) {
                // 4. 处理JSON字符串形式的数据
                return objectMapper.readValue(
                        (String) cachedData,
                        new TypeReference<List<User>>() {}
                );
            }
            // 5. 其他类型处理
            return objectMapper.convertValue(
                    cachedData,
                    new TypeReference<List<User>>() {}
            );
        } catch (Exception e) {
            // 6. 异常处理(记录日志等)
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

4)多个key获取数据

    /**
     * 获取实体对象集合
     */
    public List<User> getUsers(List<String> userIds) {
        List<String> keys = userIds.stream()
                .map(id -> "user:" + id)
                .collect(Collectors.toList());
        // 批量获取
        List<Object> results = redisTemplate.opsForValue().multiGet(keys);
        return results.stream()
                .filter(Objects::nonNull)
                .map(obj -> (User) obj) // 自动反序列化
                .collect(Collectors.toList());
    }

5)使用注解获取缓存

     /**
     * 自动缓存结果 (使用全局3分钟过期)
     */
    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        // 模拟数据库查询
        return productRepository.findById(id).orElse(null);
    }
    
    /**
     * 自定义缓存过期时间 (覆盖全局设置)
     */
    @Cacheable(value = "hot_products", key = "#id", cacheManager = "customCacheManager")
    public Product getHotProduct(Long id) {
        // ...
    }
    
    // 在 RedisConfig 中添加
    @Bean
    public RedisCacheManager customCacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(5)) // 自定义5分钟
            .serializeValuesWith(RedisSerializationContext.SerializationPair
                .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        
        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
    }

 

5、

6、

7、

8、

到此,SpringBoot集成Redis分享完成,下篇我们分享器源码相关,敬请期待。


网站公告

今日签到

点亮在社区的每一天
去签到