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
| private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);
@Value("${caffeine.posts.max-size}") private int maxSize;
@Value("${caffeine.posts.expire-seconds}") private int expireSeconds;
private LoadingCache<String, List<DiscussPost>> postListCache;
private LoadingCache<Integer, Integer> postRowsCache;
@PostConstruct public void init() { postListCache = Caffeine.newBuilder() .maximumSize(maxSize) .expireAfterWrite(expireSeconds, TimeUnit.SECONDS) .build(new CacheLoader<String, List<DiscussPost>>() { @Nullable @Override public List<DiscussPost> load(@NonNull String key) throws Exception { if (key == null || key.length() == 0) { throw new IllegalArgumentException("参数错误!"); }
String[] params = key.split(":"); if (params == null || params.length != 2) { throw new IllegalArgumentException("参数错误!"); }
int offset = Integer.valueOf(params[0]); int limit = Integer.valueOf(params[1]);
logger.debug("load post list from DB."); return discussPostMapper.selectDiscussPosts(0, offset, limit, 1); } });
postRowsCache = Caffeine.newBuilder() .maximumSize(maxSize) .expireAfterWrite(expireSeconds, TimeUnit.SECONDS) .build(new CacheLoader<Integer, Integer>() { @Nullable @Override public Integer load(@NonNull Integer key) throws Exception {
logger.debug("load post rows from DB."); return discussPostMapper.selectDiscussPostRows(key); } }); }
public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit, int orderMode) { if (userId == 0 && orderMode == 1) { return postListCache.get(offset + ":" + limit); }
logger.debug("load post list from DB."); return discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode); }
public int findDiscussPostRows(int userId) { if (userId == 0) { return postRowsCache.get(userId); }
logger.debug("load post rows from DB."); return discussPostMapper.selectDiscussPostRows(userId); }
|