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

Java实现一定时间内同时请求接口时返回相同数据

1. 缓存机制

使用本地缓存(如Caffeine)

@Service
public class DataService {private final Cache<String, Object> cache = Caffeine.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS)  // 30秒过期.maximumSize(1000).build();public Object getData(String key) {return cache.get(key, k -> fetchDataFromSource(k));}private Object fetchDataFromSource(String key) {// 实际的数据获取逻辑return new Object();}
}

使用Redis缓存

@Service
public class DataService {@Autowiredprivate StringRedisTemplate redisTemplate;public Object getData(String key) {String cachedData = redisTemplate.opsForValue().get(key);if (cachedData != null) {return JSON.parseObject(cachedData, Object.class);}// 获取新数据Object data = fetchDataFromSource(key);redisTemplate.opsForValue().set(key, JSON.toJSONString(data), 30, TimeUnit.SECONDS);return data;}
}

2. 请求合并机制

使用ConcurrentHashMap实现请求合并

@Service
public class MergingDataService {private final ConcurrentHashMap<String, CompletableFuture<Object>> pendingRequests = new ConcurrentHashMap<>();public CompletableFuture<Object> getDataAsync(String key) {// 检查是否有正在进行的相同请求CompletableFuture<Object> existingFuture = pendingRequests.get(key);if (existingFuture != null) {return existingFuture;}// 创建新的请求CompletableFuture<Object> newFuture = new CompletableFuture<>();CompletableFuture<Object> previousFuture = pendingRequests.putIfAbsent(key, newFuture);if (previousFuture != null) {// 其他线程已经创建了请求return previousFuture;}// 执行实际的数据获取try {Object data = fetchDataFromSource(key);newFuture.complete(data);return newFuture;} finally {pendingRequests.remove(key);}}private Object fetchDataFromSource(String key) {// 实际的数据获取逻辑return new Object();}
}

3. 控制器层实现

@RestController
public class DataController {@Autowiredprivate DataService dataService;@Autowiredprivate MergingDataService mergingDataService;@GetMapping("/data")public ResponseEntity<Object> getData(@RequestParam String key) {try {Object data = dataService.getData(key);return ResponseEntity.ok(data);} catch (Exception e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();}}@GetMapping("/data/async")public CompletableFuture<ResponseEntity<Object>> getDataAsync(@RequestParam String key) {return mergingDataService.getDataAsync(key).thenApply(data -> ResponseEntity.ok(data)).exceptionally(throwable -> ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());}
}

4. 使用Spring Cache注解

@Service
@EnableCaching
public class CachedDataService {@Cacheable(value = "dataCache", key = "#key", unless = "#result == null")@Cacheable(cacheNames = "dataCache", key = "#key")public Object getData(String key) {// 模拟耗时操作try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}return fetchDataFromSource(key);}private Object fetchDataFromSource(String key) {return new Object();}
}

推荐方案

  1. 简单场景:使用本地缓存或Redis缓存
  2. 高并发场景:使用请求合并机制避免重复计算
  3. 复杂业务:结合多种方案,先检查缓存,再进行请求合并

这样可以有效减少重复请求对后端服务的压力,并保证在缓存有效期内返回相同的数据。

http://www.jsqmd.com/news/39089/

相关文章:

  • 协议和socket的关系
  • 2025年评价高的上海智算中心IDCE数据中心展同期活动
  • sqlserver日志收缩
  • 2025年玻璃鼠标垫定制厂家推荐排行榜
  • 2025年可靠的环保咨询全国优质服务推荐榜
  • 2025年国内有名的品牌设计行业影响力品牌榜
  • 2025酒店防风卷帘供应厂家推荐榜单
  • 2025年质量好的澳洲海外仓中转一件代发优质服务榜
  • 2025年靠谱的格力空调代理值得信赖机构榜单
  • kubelet在和kube-apiserver通信不支持http2协议cup占用升高
  • 达梦数据库 查询建表语句、获取字段注释(亲测可用)
  • 2025年比较好的标书制作品牌推荐榜
  • 五分钟构建智能知识库:AI如何重塑知识管理
  • 2025年比较好的酒会活动策划行业影响力品牌榜
  • 2025年知名的智慧工厂目视化规划最新品牌推荐榜服务商
  • 基于MATLAB实现空间计量模型及检验方法
  • 2025农用遮阳网销售厂家排行
  • 2025年评价高的赣州装修公司定制
  • 2025年广州包车品牌排行榜
  • 2025背调最好的排行榜单
  • 2025年靠谱的河南公司注册代理记账机构品牌实力推荐排行榜
  • 2025年权威的慧商青少年少儿训练平台口碑排行榜
  • 2025年数控机床生产厂家推荐排行
  • 2025年质量好的欧洲品牌三段力缓冲铰链厂家推荐及选择指南
  • 2025 年 11 月仿石漆厂家推荐排行榜,外墙仿石漆,内墙仿石漆,防霉仿石漆,水包水仿石漆,水包砂仿石漆,耐污仿石漆,自洁仿石漆公司推荐
  • 2025年优质的房屋加固用户满意度排行
  • CF1797F Li Hua and Path
  • 利用粒子群优化算法进行大地电磁视电阻率反演
  • 2025 年 11 月新风系统厂家推荐排行榜,电竞网咖酒店棋牌室KTV洗浴商场办公室别墅大宅学校诊所中医馆会所美容院,商用家用全热交换极寒地区适用精选
  • 2025年知名的昆山绿化养护行业内口碑厂家排行榜