如何优化网站性能
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
caffeine.posts.expire-seconds=180
3.添加缓存代码
@Service
public class DiscussPostService {
private static final Logger LOGGER = LoggerFactory.getLogger(DiscussPostService.class);
@Autowired
DiscussPostMapper discussPostMapper;
@Autowired
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[] params = key.split(":");
if (params == null || params.length != 2){
throw new IllegalArgumentException("参数错误!");
}
int offset = Integer.valueOf(params[0]);
int limit = Integer.valueOf(params[1]);
//此处可以缓存二级缓存 this -> 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 list from DB.");
return discussPostMapper.selectDiscussPostRows(key);
}
});
}
public List<DiscussPost> findDiscussPosts(int userId,int page,int size,int orderMode){
if (userId == 0 && orderMode == 1){
return postListCache.get(page + ":" + size);
}
LOGGER.debug("load post list from DB.");
return discussPostMapper.selectDiscussPosts(userId,page,size,orderMode);
}
public Integer findDiscussPostRows(int userId){
if (userId == 0){
return postRowsCache.get(userId);
}
LOGGER.debug("load post list from DB.");
return discussPostMapper.selectDiscussPostRows(userId);
}
}
性能优化前
优化后性能