- 本地缓存
- 将数据缓存在应用服务器上,性能最好。
- 常用缓存工具:Ehcache、Guava、Caffeine等。
- 分布式缓存
- 将数据缓存在NoSQL数据库上,跨服务器。
- 常用缓存工具:Redis。
- 多级缓存
- 一级缓存(本地缓存)->二级缓存(分布式缓存)->DB
- 避免缓存雪崩(缓存失效,大量请求直达DB),提高系统的可用性
1.引入依赖
<!--caffeine-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.7.0</version>
</dependency>
2.相关配置文件 配置缓存最大数量、缓存更新频率
#caffeine
caffeine:
posts:
max-size: 15
expire-seconds: 180
3.DiscussPostService 对首页的热帖查询进行缓存处理
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.mapper.DiscussPostMapper;
import com.nowcoder.community.util.SensitiveFilter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class DiscussPostServiceImpl implements DiscussPostService{
private static final Logger logger= LoggerFactory.getLogger(DiscussPostServiceImpl.class);
@Autowired
private DiscussPostMapper discussPostMapper;
@Autowired
private SensitiveFilter sensitiveFilter;
@Value("${caffeine.posts.max-size}")
private int maxSize;
@Value("${caffeine.posts.expire-seconds}")
private int expireSeconds;
// Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache
//帖子列表缓存
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>>() {
@Override
public @Nullable List<DiscussPost> load(@NonNull String key) throws Exception {
if (key==null||key.length()==0){
throw new IllegalArgumentException("参数错误!");
}
String[] split = key.split(":");
if (split==null||split.length!=2){
throw new IllegalArgumentException("参数错误!");
}
int offset = Integer.valueOf(split[0]);
int limit = Integer.valueOf(split[1]);
//二级缓存:Redis->mysql
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>() {
@Override
public @Nullable Integer load(@NonNull Integer key) throws Exception {
logger.debug("load post rows from DB.");
return discussPostMapper.selectDiscussPostRows(key);
}
});
}
@Override
public List<DiscussPost> selectDiscussPosts(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);
}
@Override
public int selectDiscussPostRows(int userId) {
if (userId==0){
return postRowsCache.get(userId);
}
logger.debug("load post rows from DB.");
return discussPostMapper.selectDiscussPostRows(userId);
}
@Override
public int insertDiscussPost(DiscussPost discussPost) {
return discussPostMapper.insertDiscussPost(discussPost);
}
@Override
public DiscussPost selectDiscussPostById(int id) {
return discussPostMapper.selectDiscussPostById(id);
}
@Override
public int updateCommentCount(int id, int commentCount) {
return discussPostMapper.updateCommentCount(id, commentCount);
}
@Override
public int updateType(int id, int type) {
return discussPostMapper.updateType(id, type);
}
@Override
public int updateStatus(int id, int status) {
return discussPostMapper.updateStatus(id, status);
}
@Override
public int updateScore(int id, double score) {
return discussPostMapper.updateScore(id, score);
}
public int addDiscussPost(DiscussPost discussPost){
if (discussPost==null){
throw new IllegalArgumentException("参数不能为空!");
}
//转移HTML标记
discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));
//过滤敏感词
discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));
return discussPostMapper.insertDiscussPost(discussPost);
}
}
4.使用JMeter进行压力测试
(1)添加线程组:使用100个线程,默认1s创建好,持续执行60s;
(2)添加取样器-http请求协议:IP地址为127.0.0.1,方法get,添加热帖路径/community/index?orderMode=1;
(3)添加统一随机定时器:线程延迟0~1000ms
(4)聚合报告;