当前位置: 首页 > news >正文

创办一个网站需要多少资金百度下载免费安装

创办一个网站需要多少资金,百度下载免费安装,网站建设与维护 电子版,企业网站设计意义Spring Boot 缓存最佳实践:从基础到生产的完整指南 引言 在现代分布式系统中,缓存是提升系统性能的银弹。Spring Boot 通过 spring-boot-starter-cache​ 模块提供了开箱即用的缓存抽象,但如何根据业务需求实现灵活、可靠的缓存方案&#xf…

在这里插入图片描述

Spring Boot 缓存最佳实践:从基础到生产的完整指南


引言

在现代分布式系统中,缓存是提升系统性能的银弹。Spring Boot 通过 spring-boot-starter-cache​ 模块提供了开箱即用的缓存抽象,但如何根据业务需求实现灵活、可靠的缓存方案?本文将带您从零开始,逐步构建符合生产要求的缓存系统。


一、基础篇:5分钟快速接入

1.1 最小化配置

pom.xml 依赖

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

Nacos 配置(application.yml)

spring:cache:type: simple # 默认内存缓存

启动类注解

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

业务层使用

@Service
public class ProductService {@Cacheable("products")public Product getProduct(Long id) {// 数据库查询逻辑}
}

二、进阶篇:多缓存引擎支持

2.1 缓存类型切换

配置选项对比

类型依赖适用场景特点
simple内置开发测试环境无过期策略
caffeinecom.github.ben-manes.caffeine高性能本地缓存支持多种过期策略
redisspring-boot-starter-data-redis分布式生产环境支持持久化、集群

Nacos 配置示例

spring:cache:type: redis # 切换缓存引擎# Redis 连接配置redis:host: redis.prod.clusterport: 6379password: ${REDIS_PASSWORD}

三、生产级特性实现

3.1 方法级 TTL 控制

实现方式1:语法约定

语法约定

@Cacheable("热点数据#600") // 600秒过期
public HotData getHotData(String key) {// 业务逻辑
}

TTL 解析实现

public class CacheConfig {@Beanpublic CacheManagerCustomizer<RedisCacheManager> redisCacheCustomizer() {return manager -> manager.setCacheDecorator((name, config) -> {String[] parts = name.split("#");if (parts.length > 1) {Duration ttl = Duration.ofSeconds(Long.parseLong(parts[1]));return new RedisCacheWrapper(parts[0], config.entryTtl(ttl));}return new RedisCacheWrapper(name, config);});}
}
实现方式2:自定义注解+AOP切面
  • 定义自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheCustomTtl {long value();      // 缓存时间(秒)long jitter() default 10; // 抖动范围(秒)//....自定义其他逻辑
}
  • aop切面逻辑
@Aspect
@Component
public class CacheTtlAspect {@Around("@annotation(cacheCustomTtl)")public Object applyCustomTtl(ProceedingJoinPoint joinPoint, CacheCustomTtl cacheCustomTtl) throws Throwable {// 获取原始缓存配置Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();Cacheable cacheable = method.getAnnotation(Cacheable.class);String[] cacheNames = cacheable.value();// 生成带自定义时间的缓存名称(例如: user#3600)String newCacheName = cacheNames[0] + "#" + cacheCustomTtl.value();String[] modifiedCacheNames = {newCacheName};// 动态修改缓存名称Cacheable modifiedCacheable = new CacheableWrapper(cacheable, modifiedCacheNames);((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(Cacheable.class).value();// 通过反射调用原方法(需使用动态代理或工具类)return joinPoint.proceed();}// 包装类用于动态修改注解属性private static class CacheableWrapper implements Cacheable {private final Cacheable delegate;private final String[] cacheNames;public CacheableWrapper(Cacheable delegate, String[] cacheNames) {this.delegate = delegate;this.cacheNames = cacheNames;}@Overridepublic String[] value() { return cacheNames; }// 其他方法委托给原注解...}
}

3.2 随机抖动(Jitter)

防雪崩配置

spring:cache:jitter-range: 60s # 最大抖动时间范围

抖动值生成逻辑

private Duration applyJitter(Duration ttl) {long jitter = ThreadLocalRandom.current().nextLong(spring.cache.jitter-range.getSeconds() + 1);return ttl.plusSeconds(jitter);
}

四、高级优化方案

4.1 多级缓存架构

命中
未命中
未命中
业务层
本地缓存
Redis集群
数据库

实现要点

  • 使用 Caffeine 作为一级缓存
  • Redis 作为二级缓存
  • 自定义 CacheManager 实现分级策略

基于Spring Boot的多级缓存架构实现

4.2 监控与治理

Spring Boot Actuator 集成

management:endpoints:web:exposure:include: caches,health,metrics

关键监控指标

  • cache.gets​:缓存查询次数
  • cache.puts​:缓存写入次数
  • cache.removals​:缓存清除次数
  • cache.evictions​:缓存淘汰次数

五、最佳实践总结

5.1 配置推荐

# 生产环境推荐配置
spring:cache:type: redisjitter-range: 30skey-separator: "::"redis:lettuce:pool:max-active: 20max-idle: 10min-idle: 5

5.2 避坑指南

  1. 键设计原则

    • 使用业务语义明确的键命名(如 user:profile:{userId}​)
    • 避免使用可变对象作为键
  2. 缓存穿透防护

    @Cacheable(value = "users", unless = "#result == null")
    public User getUser(Long id) {// 返回null时自动跳过缓存
    }
    
  3. 版本兼容策略

    @CachePut(value = "products#3600", key = "#product.id")
    public Product updateProduct(Product product) {// 更新后自动刷新缓存
    }
    

最后

根据业务场景灵活选择适合的缓存策略,从简单的内存缓存到复杂的分布式缓存体系,Spring Boot 的缓存抽象层始终提供一致的使用体验。记住:没有完美的缓存方案,只有最适合业务场景的缓存策略。

http://www.ds6.com.cn/news/7815.html

相关文章:

  • 深圳网址网站建设公司公司网站优化方案
  • 制作动态网站的流程百度词条优化
  • h5模板免费哪里有网站推广优化
  • 教人做甜点的网站谷歌ads广告投放
  • 昆明网站建设哪家便宜足球世界排名国家
  • 淘宝客优惠券网站建设教程视频谷歌网站
  • 网站开发项目的部署seo优化培训班
  • 建筑网站图片在线网站seo诊断
  • 做平面设计去哪些网站找图重庆seo技术分享
  • 为什么做企业网站今日全国疫情一览表
  • wordpress文章样式专业网站优化培训
  • 北京cms建站系统百度搜索引擎广告投放
  • 网站建设改版公司宁波网站优化公司价格
  • 单位的网站的建设方案百度关键词首页排名服务
  • 政府网站建设进展情况优化的近义词
  • 新乡网站建设设计公司商务软文写作
  • 中国十大门窗品牌有哪些企业网站优化哪家好
  • 怎样在网站做咨询医生挣钱网络营销有哪些形式
  • 深圳高端网站开发南宁百度推广排名优化
  • 绵阳做网站优化河南郑州网站顾问
  • 网站建设狼雨哪里有学电脑培训班
  • 云南网站建设公司排行2023免费b站推广大全
  • 网站服务器在今日军事新闻头条最新
  • 评论给网站带来的益处镇江关键字优化品牌
  • 前几年做哪个网站能致富营销网络的建设
  • 外链博客网站广州:推动优化防控措施落地
  • 台州市网站建设网页模板之家
  • 做网站建设工资高吗做互联网推广的公司
  • 网站登录页面模板 下载上海seo顾问推推蛙
  • 网站为什么要做seo百度seo软件