SpringBoot与Redis联姻:从青铜到王者的配置婚庆指南!

87 阅读3分钟

各位SpringBoot的月老们!今天我们要给SpringBoot和Redis牵红线,这桩婚事成了之后,你的系统性能能原地起飞!(前提是别把彩礼——服务器配置搞错)来,系好安全带,老司机要飙车了!


第一幕:包办婚姻の基本法

Step1 先下聘礼(加依赖)

<!-- 在pom.xml里塞红包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

(小声BB:这包自带Lettuce客户端,想换Jedis的看后文离婚...啊不切换教程)

Step2 写婚书(配yml)

spring:
  redis:
    host: localhost # 别写127.0.0.1装逼,翻车了别哭
    port: 6379
    password: 你的密码不是123456吧?
    database: 0 # 洞房编号,别乱闯其他database
    lettuce:
      pool:
        max-active: 8 # 连接池最大人数,超过要排队
        max-wait: -1ms # 等对象等到天荒地老(-1表示无限等待)

第二幕:洞房花烛夜の基础操作

自动注入你的贤内助

@Autowired
private RedisTemplate<String, Object> redisTemplate; // 原装夫人

// 存储操作比丈母娘收彩礼还利索
redisTemplate.opsForValue().set("老婆的购物车", "双十一清单");
// 读取速度比查男友手机还快
Object cart = redisTemplate.opsForValue().get("老婆的购物车");

高段位玩法(直接@Cacheable)

@Service
public class UserService {
    @Cacheable(value = "users", key = "#userId") // 自动缓存,比备忘录还贴心
    public User getUserById(String userId) {
        // 假装这里有耗时500ms的数据库查询
    }
}
// 记得在主类开光:@EnableCaching

第三幕:婚后矛盾调解室

槽点1:RedisTemplate的JDK序列化审美掉线
默认用JDK序列化存的数据,在Redis里看着像乱码:
"\xac\xed\x00\x05t\x00\x0c老婆的购物车"

解决方案——给RedisTemplate整容

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 上美颜滤镜(JSON序列化)
        template.setDefaultSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        return template;
    }
}

槽点2:Lettuce偶尔网卡
遇到RedisCommandTimeoutException不要慌:

  1. 检查网络是不是在吃鸡(延迟)
  2. 适当调大超时时间:
spring:
  redis:
    timeout: 3000ms # 默认是2秒,建议调成业务可接受范围

第四幕:七年之痒の进阶玩法

玩法1:切换原配客户端(Lettuce→Jedis)
修改pom.xml上演《回家的诱惑》:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

玩法2:缓存雪崩防护盾

@Cacheable(value = "users", key = "#userId", 
           cacheManager = "randomExpireCacheManager") // 自定义缓存管理器

自定义CacheManager配置随机过期时间,防止集体去世:

@Bean
public RedisCacheManager randomExpireCacheManager(RedisConnectionFactory factory) {
    // 设置基础过期时间+随机偏移量
    return RedisCacheManager.builder(factory)
           .cacheDefaults(getRandomTtlConfig(3600)) // 基础1小时±随机10分钟
           .build();
}

终极大招:婚姻保卫战

保命符1:连接池监控
在application.yml配置:

management:
  endpoints:
    web:
      exposure:
        include: "*"  # 暴露监控端点
  metrics:
    tags:
      application: ${spring.application.name}

访问/actuator/redis查看:

  • 连接池使用率(别让连接池变成游泳池)
  • 命令耗时统计(找出哪个SQL在摸鱼)

保命符2:缓存穿透金钟罩
使用布隆过滤器防御:

@Bean
public RBloomFilter<String> userBloomFilter(RedissonClient redisson) {
    RBloomFilter<String> filter = redisson.getBloomFilter("userFilter");
    filter.tryInit(100000L, 0.03); // 10万用户量,3%误判率
    return filter;
}

保命符3:双写一致性宝典
更新数据库时同步清理缓存:

@Transactional
@CacheEvict(value = "users", key = "#user.id")
public void updateUser(User user) {
    // 先更新数据库
    // 缓存自动清理,下次查询时重新加载
}

最后送上婚姻保鲜秘诀:
定期检查Redis内存使用情况!
(否则你的婚姻会像Redis一样——说崩就崩)

现在你已获得"SpringBoot+Redis婚庆协会"认证!要不要挑战用Redis实现分布式Session共享?(然后发现还得处理头发掉光的问题)我们下期《Redis集群:从拜天地到闹分家的那些年》再见! 💥