当前位置: 首页 > 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.zskr.cn/news/48201.html

相关文章:

  • 协议和socket的关系
  • 2025年评价高的上海智算中心IDCE数据中心展同期活动
  • 2025年可靠的环保咨询全国优质服务推荐榜
  • 2025年国内有名的品牌设计行业影响力品牌榜
  • 2025年Sandra律师离婚团队口碑排行榜单
  • kubelet在和kube-apiserver通信不支持http2协议cup占用升高
  • 达梦数据库 查询建表语句、获取字段注释(亲测可用)
  • 2025年数控机床生产厂家推荐排行
  • 2025年优质的房屋加固用户满意度排行
  • 2025年知名的昆山绿化养护行业内口碑厂家排行榜
  • 2025年比较好的便携式车载灭火器用户好评厂家排行
  • 基于颜色衰减先验模型的单幅图像快速去雾算法
  • 2025年锯齿钢格板销售厂家推荐榜单
  • 2025年知名的冷拉型钢圆钢厂家推荐及选购参考榜
  • PhpStorm 2025.2.4, 11月最新版 安装、授权、使用说明
  • 2025年靠谱的多媒体展厅设计推荐推荐排行榜
  • 2025年靠谱的梯形排水沟滑模机TOP品牌厂家排行榜
  • 2025年信号转换器加工厂推荐榜
  • 2025年权威的烧菜火锅底料排行
  • 2025年资深的袋装骆驼奶粉推荐榜单
  • 2025年质量好的直流温升试验机厂家最新热销排行
  • 202评价高的5年权威的广州税收筹划推荐口碑推荐榜
  • 2025年评价高的数控弹簧机厂家最新实力排行
  • 2025年质量好的土鸡蛋行业年度推荐榜
  • 2025年评价高的缓冲反弹骑马抽厂家推荐及选择指南
  • 2025年质量好的空压机冷却塔TOP品牌厂家排行榜
  • 2025年热门的橱柜缓冲骑马抽厂家最新用户好评榜
  • 学习笔记:连通性相关的 Tarjan 算法
  • 国产DAC芯片KY80508软硬件兼容替代DAC80508
  • 2025年质量好的夜景亮化工程推荐排行榜