引入rabbitmq/应用解偶/流量削峰,引入redisson实现分布式锁

This commit is contained in:
xiongxiaoyang
2020-06-02 22:32:33 +08:00
parent 8885730e77
commit 1bda806862
11 changed files with 264 additions and 31 deletions

View File

@ -41,9 +41,6 @@
</dependency>
</dependencies>

View File

@ -13,6 +13,7 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
@ -34,6 +35,8 @@ public class BookController {
private final BookService bookService;
private final RabbitTemplate rabbitTemplate;
/**
* 小说分类列表查询接口
*/
@ -67,7 +70,7 @@ public class BookController {
@ApiOperation("点击量新增接口")
@PostMapping("addVisitCount")
public ResultBean addVisitCount(@ApiParam("小说ID") @RequestParam("bookId") Long bookId) {
bookService.addVisitCount(bookId, 1);
rabbitTemplate.convertAndSend("ADD-BOOK-VISIT-EXCHANGE", null, bookId);
return ResultBean.ok();
}

View File

@ -0,0 +1,70 @@
package com.java2nb.novel.book.listener;
import com.java2nb.novel.book.service.BookService;
import com.java2nb.novel.common.cache.CacheKey;
import com.java2nb.novel.common.cache.CacheService;
import com.java2nb.novel.common.utils.Constants;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author 11797
*/
@Component
@Slf4j
@RequiredArgsConstructor
public class BookVisitAddListener {
private final BookService bookService;
private final CacheService cacheService;
private final RedissonClient redissonClient;
/**
* 更新数据库
* 流量削峰每本小说累积10个点击更新一次
*/
@SneakyThrows
@RabbitListener(queues = {"UPDATE-DB-QUEUE"})
public void updateDb(Long bookId, Channel channel, Message message) {
log.debug("收到更新数据库消息:" + bookId);
RLock lock = redissonClient.getLock("addVisitCountToDb");
lock.lock();
try {
Integer visitCount = (Integer) cacheService.getObject(CacheKey.BOOK_ADD_VISIT_COUNT + bookId);
if (visitCount == null) {
visitCount = 0;
}
cacheService.setObject(CacheKey.BOOK_ADD_VISIT_COUNT + bookId, ++visitCount);
if (visitCount >= Constants.ADD_MAX_VISIT_COUNT) {
bookService.addVisitCount(bookId, visitCount);
cacheService.del(CacheKey.BOOK_ADD_VISIT_COUNT + bookId);
}
}catch (Exception e){
log.error("更新数据库失败"+bookId);
}
lock.unlock();
Thread.sleep(1000 * 2);
}
}

View File

@ -3,3 +3,15 @@ spring:
name: book-service
profiles:
active: dev
cloud:
nacos:
config:
extconfig[0]:
dataid: novel-redis.yml
group: novel-common
refresh: true
extconfig[1]:
dataid: novel-rabbitmq.yml
group: novel-common
refresh: true