1. 延迟加载:
代码语言:javascript复制
// 将商品信息加载到缓存中
public void loadGoodsToCache() {
List<Goods> goodsList = goodsService.getGoodsList();
for (Goods goods : goodsList) {
redisTemplate.opsForValue().set("goods:" goods.getId(), goods);
}
}
// 秒杀开始时将缓存中的商品信息加载到数据库中
public void startSeckill() {
List<Goods> goodsList = redisTemplate.opsForValue().multiGet(redisTemplate.keys("goods:*"));
for (Goods goods : goodsList) {
goodsService.updateGoods(goods);
}
}
2. 队列:
代码语言:javascript复制java
// 将秒杀请求放入消息队列中
public void seckill(String userId, String goodsId) {
SeckillRequest request = new SeckillRequest(userId, goodsId);
rabbitTemplate.convertAndSend("seckill.exchange", "seckill.queue", request);
}
// 消费者处理秒杀请求
@RabbitListener(queues = "seckill.queue")
public void handleSeckillRequest(SeckillRequest request) {
// 处理秒杀请求
}
3. 限流:
代码语言:javascript复制java
// 使用Guava RateLimiter进行限流
private static final RateLimiter rateLimiter = RateLimiter.create(100);
// 处理秒杀请求
public void seckill(String userId, String goodsId) {
if (rateLimiter.tryAcquire()) {
// 处理秒杀请求
} else {
// 返回错误信息
}
}
4. 分布式锁:
代码语言:javascript复制java
// 使用Redisson实现分布式锁
private static final RLock lock = redissonClient.getLock("seckill");
// 处理秒杀请求
public void seckill(String userId, String goodsId) {
try {
lock.lock();
// 处理秒杀请求
} finally {
lock.unlock();
}
}
5. CDN加速:
代码语言:javascript复制java
// 使用Nginx配置CDN加速
location /static/ {
proxy_pass http://cdn.example.com/static/;
}
6. 分布式缓存:
代码语言:javascript复制java
// 使用Redis缓存商品信息
public Goods getGoodsById(String goodsId) {
Goods goods = redisTemplate.opsForValue().get("goods:" goodsId);
if (goods == null) {
goods = goodsService.getGoodsById(goodsId);
redisTemplate.opsForValue().set("goods:" goodsId, goods);
}
return goods;
}
7. 异步处理:
代码语言:javascript复制java
// 将秒杀请求放入消息队列中,由异步处理程序进行处理
public void seckill(String userId, String goodsId) {
SeckillRequest request = new SeckillRequest(userId, goodsId);
rabbitTemplate.convertAndSend("seckill.exchange", "seckill.queue", request);
}
// 异步处理程序处理秒杀请求
@RabbitListener(queues = "seckill.queue")
public void handleSeckillRequest(SeckillRequest request) {
// 处理秒杀请求
}