优化网站性能
- 本地缓存
- 将数据缓存在应用服务器上,性能最好
- 要考虑缓存大小,缓存过期时间
- 常用缓存工具:Ehcache、Guava、Caffeine等
- 将数据缓存在应用服务器上,性能最好
- 分布式缓存
- 将数据缓存在NoSQL数据库上,跨服务器。
- 常用缓存工具:MemCache、Redis等。
- 多级缓存
- > 一级缓存(本地缓存)> 二级缓存(分布式缓存)> DB
- 避免缓存雪崩(缓存失效,大量请求直达DB),提高系统的可用性
本地缓存适合与用户无强关联的信息,Redis可以缓存与用户强关联的信息(如 登录凭证),可以跨服务器,但比本地缓存稍微慢些
两级缓存的过程:
本地缓存
数据变化频率相对较低的数据比较使用于缓存。将热门帖子列表缓存到本地缓存中。使用Caffeine
1、导包
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.7.0</version>
</dependency>
2、自定义配置
# caffeine
caffeine.posts.max-size=15 // 设置缓存空间里缓存多少对象,缓存的列表的对象是page
caffeine.posts.expire-seconds=180 // 3min
缓存数据的更新一般有两种方式:1、数据发生更新 2、缓存到了过期时间
3、优化业务方法,一般是优化Service。
使用Caffeine 缓存 帖子列表和总的行数
Caffeine的核心接口是Cache,其有两个子接口 LoadingCache, AsyncLoadingCache。LoadingCache 是同步缓存,AsyncLoadingCache可以实现异步、并发
@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>>() {
@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]);
// 可以在这里添加二级缓存: 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>() {
@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);
}
压力测试
压力测试最好让数据库里的数据多一些,访问数据库性能差一些,才方便与缓存进行对比。
A、造数据
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class CaffeineTests {
@Autowired
private DiscussPostService postService;
@Test
public void initDataForTest() {
for (int i = 0; i < 300000; i++) {
DiscussPost post = new DiscussPost();
post.setUserId(111);
post.setTitle("互联网求职暖春计划");
post.setContent("今年的就业形势,确实不容乐观。过了个年,仿佛跳水一般,整个讨论区哀鸿遍野!19届真的没人要了吗?!18届被优化真的没有出路了吗?!大家的“哀嚎”与“悲惨遭遇”牵动了每日潜伏于讨论区的牛客小哥哥小姐姐们的心,于是牛客决定:是时候为大家做点什么了!为了帮助大家度过“寒冬”,牛客网特别联合60+家企业,开启互联网求职暖春计划,面向18届&19届,拯救0 offer!");
post.setCreateTime(new Date());
post.setScore(Math.random() * 2000);
postService.addDiscussPost(post);
}
}
@Test
public void testCache() {
System.out.println(postService.findDiscussPosts(0, 0, 10, 1));
System.out.println(postService.findDiscussPosts(0, 0, 10, 1));
System.out.println(postService.findDiscussPosts(0, 0, 10, 1));
System.out.println(postService.findDiscussPosts(0, 0, 10, 0));
}
B、JMeter
压力测试其实就是利用工具,模拟客户端去访问服务器。
1)添加线程组
2)设置http请求
3)请求之间添加一个随机的间隔
4)混合报告:主要看吞吐量,即每秒服务器能处理多少条请求