1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
@Service public class EmergencyProductService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private ProductMapper productMapper;
@PostConstruct public void emergencyCacheWarmup() { log.info("开始紧急缓存预热..."); List<Long> hotProductIds = getHotProductIds(); for (Long productId : hotProductIds) { try { ProductInfo product = productMapper.selectById(productId); if (product != null) { String cacheKey = "product:" + productId; redisTemplate.opsForValue().set(cacheKey, product, Duration.ofMinutes(30 + new Random().nextInt(30))); } Thread.sleep(10); } catch (Exception e) { log.error("预热商品缓存失败: productId={}", productId, e); } } log.info("紧急缓存预热完成,预热商品数量: {}", hotProductIds.size()); }
public ProductInfo getProductByIdWithFallback(Long productId) { String cacheKey = "product:" + productId; ProductInfo cached = (ProductInfo) redisTemplate.opsForValue().get(cacheKey); if (cached != null) { return cached; } String lockKey = "lock:product:" + productId; Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", Duration.ofSeconds(10)); if (Boolean.TRUE.equals(lockAcquired)) { try { ProductInfo product = productMapper.selectById(productId); if (product != null) { int randomExpire = 1800 + new Random().nextInt(600); redisTemplate.opsForValue().set(cacheKey, product, Duration.ofSeconds(randomExpire)); } return product; } finally { redisTemplate.delete(lockKey); } } else { try { Thread.sleep(100); return (ProductInfo) redisTemplate.opsForValue().get(cacheKey); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } } }
private List<Long> getHotProductIds() { return Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L); } }
|