核心内容摘要
91prony:解锁无限可能,开启数字新纪元
HoRain 云小助手个人主页⛺️生活的理想就是为了理想的生活!⛳️ 推荐前些天发现了一个超棒的服务器购买网站性价比超高大内存超划算忍不住分享一下给大家。
点击跳转到网站。
目录⛳️ 推荐Spring Cache与Redis结合基本使用指南
添加依赖
配置Redis连接
启用缓存
使用缓存注解Cacheable - 缓存读取CachePut - 缓存更新CacheEvict - 缓存删除
自定义缓存配置JSON序列化
实际使用示例
缓存操作说明
最佳实践建议Spring Cache与Redis结合基本使用指南根据知识库信息我为您整理了Spring Cache与Redis结合的基本
使用方法
添加依赖在pom.xml中添加以下依赖!-- Redis依赖 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-redis/artifactId /dependency !-- Spring Cache依赖 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-cache/artifactId /dependency
配置Redis连接在application.properties中配置spring.redis.hostlocalhost spring.redis.port6379 spring.redis.passwordyourpassword或在application.yml中配置spring: redis: host:
192.
168.
100 port: 6379 password: 密码 database: 0 timeout: 10000ms lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1ms
启用缓存在主配置类上添加EnableCaching注解SpringBootApplication EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
使用缓存注解Cacheable - 缓存读取Service public class ProductService { Cacheable(value products, key #id) public Product getProductById(Long id) { System.out.println(Fetching product from the database for id: id); return new Product(id, Product id,
100.
; } }CachePut - 缓存更新CachePut(value products, key #product.id) public Product updateProduct(Product product) { // 更新产品信息 return product; }CacheEvict - 缓存删除CacheEvict(value products, key #id) public void deleteProduct(Long id) { // 删除产品 }
自定义缓存配置JSON序列化默认情况下Redis存储的是Java序列化字节流建议配置为JSON格式Configuration EnableCaching public class RedisCacheConfig { Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config RedisCacheConfiguration.defaultCacheConfig() // 设置key为String序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置value为JSON序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) // 不缓存null值 .disableCachingNullValues() // 默认缓存1小时 .entryTtl(Duration.ofHours(
); return RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); } }
实际使用示例创建REST控制器访问缓存数据RestController public class ProductController { Autowired private ProductService productService; GetMapping(/product/{id}) public Product getProduct(PathVariable Long id) { return productService.getProductById(id); } }
缓存操作说明操作描述缓存读取使用Cacheable方法调用时先检查缓存命中则直接返回缓存更新使用CachePut强制将方法返回结果更新到缓存缓存删除使用CacheEvict从缓存中移除指定条目缓存存储Redis将数据以键值对形式存储在内存中可设置TTL
最佳实践建议序列化选择避免使用JDK序列化推荐使用JSON序列化如GenericJackson2JsonRedisSerializer连接池配置生产环境必须配置Lettuce连接池限制避免资源耗尽TTL设置根据业务需求合理设置缓存过期时间空值缓存考虑缓存空值防止缓存穿透缓存粒度根据查询模式选择合适的缓存粒度整个对象或部分字段通过Spring Cache与Redis的结合使用可以大幅提高应用性能减少数据库访问次数同时确保缓存数据的一致性和及时更新。
❤️❤️❤️本人水平有限如有纰漏欢迎各位大佬评论批评指正如果觉得这篇文对你有帮助的话也请给个点赞、收藏下吧非常感谢! Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧