Spring Boot整合Redis缓存全攻略

Spring Boot整合Redis缓存详解

Redis是一种高性能的内存数据库,常用于缓存、消息队列等场景。Spring Boot提供了对Redis的自动配置支持,通过简单的配置即可实现缓存功能。

添加依赖

在pom.xml中添加Spring Boot Redis Starter和缓存相关依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

配置Redis连接

在application.properties或application.yml中配置Redis连接信息:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0

启用缓存支持

在Spring Boot主类上添加@EnableCaching注解:

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

配置Redis缓存管理器

创建Redis缓存配置类:

@Configuration
public class RedisCacheConfig {
    
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(30))  // 设置缓存默认过期时间
            .disableCachingNullValues();      // 不缓存null值
            
        return RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .transactionAware()
            .build();
    }
}

使用缓存注解

在Service层方法上使用缓存注解:

@Service
public class ProductService {
    
    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        // 模拟数据库查询
        return findProductFromDB(id);
    }
    
    @CachePut(value = "products", key = "#product.id")
    public Product updateProduct(Product product) {
        // 更新数据库
        return updateProductInDB(product);
    }
    
    @CacheEvict(value = "products", key = "#id")
    public void deleteProduct(Long id) {
        // 从数据库删除
        deleteProductFromDB(id);
    }
}

自定义Key生成策略

实现KeyGenerator接口自定义缓存Key生成:

@Configuration
public class CacheConfig {
    
    @Bean
    public KeyGenerator customKeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getSimpleName());
            sb.append(method.getName());
            Arrays.stream(params).forEach(param -> {
                if(param != null) {
                    sb.append(param.toString());
                }
            });
            return sb.toString();
        };
    }
}

缓存异常处理

实现CacheErrorHandler处理缓存异常:

public class CustomCacheErrorHandler implements CacheErrorHandler {
    
    @Override
    public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
        // 处理获取缓存异常
    }
    
    @Override
    public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
        // 处理放入缓存异常
    }
    
    @Override
    public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
        // 处理清除缓存异常
    }
    
    @Override
    public void handleCacheClearError(RuntimeException exception, Cache cache) {
        // 处理清空缓存异常
    }
}

多级缓存实现

结合本地缓存和Redis实现多级缓存:

@Configuration
public class MultiLevelCacheConfig {
    
    @Primary
    @Bean
    public CacheManager caffeineCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(Caffeine.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(1000));
        return cacheManager;
    }
    
    @Bean
    public CacheManager redisCacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1));
            
        return RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .build();
    }
    
    @Bean
    public CacheManager multiLevelCacheManager(
            @Qualifier("caffeineCacheManager") CacheManager caffeineCacheManager,
            @Qualifier("redisCacheManager") CacheManager redisCacheManager) {
        return new MultiLevelCacheManager(caffeineCacheManager, redisCacheManager);
    }
}

缓存预热实现

实现ApplicationRunner在应用启动时预热缓存:

@Component
public class CacheWarmUp implements ApplicationRunner {
    
    @Autowired
    private ProductService productService;
    
    @Override
    public void run(ApplicationArguments args) {
        // 预热热门商品缓存
        List<Long> hotProductIds = getHotProductIdsFromDB();
        hotProductIds.forEach(productService::getProductById);
    }
}

缓存监控

通过Redis命令或Spring Boot Actuator监控缓存状态:

management.endpoints.web.exposure.include=health,info,caches
management.endpoint.caches.enabled=true

性能优化建议

  1. 合理设置缓存过期时间,避免缓存雪崩
  2. 对热点数据使用多级缓存
  3. 大对象考虑压缩后存储
  4. 批量操作使用管道技术
  5. 监控缓存命中率调整缓存策略

常见问题解决

  1. 缓存穿透:使用布隆过滤器或缓存空值
  2. 缓存雪崩:设置随机过期时间或使用锁机制
  3. 缓存击穿:使用互斥锁或永不过期策略
  4. 数据一致性:采用双写策略或消息队列同步

通过以上步骤和配置,可以在Spring Boot应用中高效地集成Redis缓存,显著提升系统性能。实际应用中应根据业务场景调整缓存策略和配置参数。

BbS.okane040.info/PoSt/1121_697932.HtM
BbS.okane041.info/PoSt/1121_552935.HtM
BbS.okane042.info/PoSt/1121_882661.HtM
BbS.okane043.info/PoSt/1121_660821.HtM
BbS.okane044.info/PoSt/1121_591326.HtM
BbS.okane045.info/PoSt/1121_170533.HtM
BbS.okane046.info/PoSt/1121_131168.HtM
BbS.okane047.info/PoSt/1121_672458.HtM
BbS.okane048.info/PoSt/1121_043937.HtM
BbS.okane049.info/PoSt/1121_200286.HtM
BbS.okane040.info/PoSt/1121_201243.HtM
BbS.okane041.info/PoSt/1121_459589.HtM
BbS.okane042.info/PoSt/1121_892234.HtM
BbS.okane043.info/PoSt/1121_784356.HtM
BbS.okane044.info/PoSt/1121_265215.HtM
BbS.okane045.info/PoSt/1121_305780.HtM
BbS.okane046.info/PoSt/1121_161132.HtM
BbS.okane047.info/PoSt/1121_170954.HtM
BbS.okane048.info/PoSt/1121_816105.HtM
BbS.okane049.info/PoSt/1121_587403.HtM
BbS.okane040.info/PoSt/1121_651524.HtM
BbS.okane041.info/PoSt/1121_509537.HtM
BbS.okane042.info/PoSt/1121_114709.HtM
BbS.okane043.info/PoSt/1121_653575.HtM
BbS.okane044.info/PoSt/1121_665746.HtM
BbS.okane045.info/PoSt/1121_075425.HtM
BbS.okane046.info/PoSt/1121_720940.HtM
BbS.okane047.info/PoSt/1121_153121.HtM
BbS.okane048.info/PoSt/1121_620383.HtM
BbS.okane049.info/PoSt/1121_319842.HtM
BbS.okane040.info/PoSt/1121_292884.HtM
BbS.okane041.info/PoSt/1121_324086.HtM
BbS.okane042.info/PoSt/1121_701083.HtM
BbS.okane043.info/PoSt/1121_253156.HtM
BbS.okane044.info/PoSt/1121_150774.HtM
BbS.okane045.info/PoSt/1121_462940.HtM
BbS.okane046.info/PoSt/1121_293427.HtM
BbS.okane047.info/PoSt/1121_870392.HtM
BbS.okane048.info/PoSt/1121_444106.HtM
BbS.okane049.info/PoSt/1121_637078.HtM
BbS.okane040.info/PoSt/1121_616135.HtM
BbS.okane041.info/PoSt/1121_018965.HtM
BbS.okane042.info/PoSt/1121_990314.HtM
BbS.okane043.info/PoSt/1121_973532.HtM
BbS.okane044.info/PoSt/1121_442104.HtM
BbS.okane045.info/PoSt/1121_085897.HtM
BbS.okane046.info/PoSt/1121_513881.HtM
BbS.okane047.info/PoSt/1121_187218.HtM
BbS.okane048.info/PoSt/1121_133949.HtM
BbS.okane049.info/PoSt/1121_625854.HtM
BbS.okane040.info/PoSt/1121_402206.HtM
BbS.okane041.info/PoSt/1121_326021.HtM
BbS.okane042.info/PoSt/1121_291991.HtM
BbS.okane043.info/PoSt/1121_181372.HtM
BbS.okane044.info/PoSt/1121_879779.HtM
BbS.okane045.info/PoSt/1121_770746.HtM
BbS.okane046.info/PoSt/1121_137002.HtM
BbS.okane047.info/PoSt/1121_729864.HtM
BbS.okane048.info/PoSt/1121_129391.HtM
BbS.okane049.info/PoSt/1121_395041.HtM
BbS.okane040.info/PoSt/1121_129475.HtM
BbS.okane041.info/PoSt/1121_407169.HtM
BbS.okane042.info/PoSt/1121_761332.HtM
BbS.okane043.info/PoSt/1121_416401.HtM
BbS.okane044.info/PoSt/1121_389778.HtM
BbS.okane045.info/PoSt/1121_867501.HtM
BbS.okane046.info/PoSt/1121_799469.HtM
BbS.okane047.info/PoSt/1121_219390.HtM
BbS.okane048.info/PoSt/1121_452226.HtM
BbS.okane049.info/PoSt/1121_847736.HtM
BbS.okane040.info/PoSt/1121_368239.HtM
BbS.okane041.info/PoSt/1121_388940.HtM
BbS.okane042.info/PoSt/1121_510741.HtM
BbS.okane043.info/PoSt/1121_156677.HtM
BbS.okane044.info/PoSt/1121_132499.HtM
BbS.okane045.info/PoSt/1121_019539.HtM
BbS.okane046.info/PoSt/1121_825338.HtM
BbS.okane047.info/PoSt/1121_130229.HtM
BbS.okane048.info/PoSt/1121_838268.HtM
BbS.okane049.info/PoSt/1121_002085.HtM

#牛客AI配图神器#

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 10:05
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-19 12:08
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务