- 背景:将主页的目录放入Redis,加快访问速度,减轻数据库压力,并测试redis和mysql之间的查询速度差距
@Service("menuService")
public class MenuServiceImpl implements IMenuService {
@Autowired
private MenuMapper mapper;
@Autowired
private RedisTemplate<String, String> redisTemplate;
private final static String SYSTEM_REDISKEY_ALLMENU="allMenu";
@Override
public List<MenuEntity> getAllMenuList() {
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
boolean hasKey = redisTemplate.hasKey(SYSTEM_REDISKEY_ALLMENU);
if(hasKey) {
long start = System.currentTimeMillis();
String string = opsForValue.get(SYSTEM_REDISKEY_ALLMENU);
long end = System.currentTimeMillis();
System.out.println("查询redis花费的时间是:" + (end - start)+"s");
List<MenuEntity> parseArray = JSON.parseArray(string, MenuEntity.class);
return parseArray;
}else {
MenuEntityExample example = new MenuEntityExample();
long start = System.currentTimeMillis();
example.setDistinct(false);
List<MenuEntity> allMneuList = mapper.selectByExample(example);
long end = System.currentTimeMillis();
System.out.println("查询mysql花费的时间是:" + (end - start)+"s");
String jsonString = JSON.toJSONString(allMneuList);
opsForValue.set(SYSTEM_REDISKEY_ALLMENU, jsonString, 5, TimeUnit.HOURS);
return allMneuList;
}
}
- 结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fcd642d5efc8e99b29c25fe779205607.png)