分析
后台代码实现
- Servlet
public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//调用Service查询所有
List<Category> all = service.findAll();
//序列化json返回
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getWriter(), all);
}
- Service
@Override
public List<Category> findAll() {
//从redis中查询
Jedis jedis = JedisUtil.getJedis();
//判断查询的集合是否为空
// Set<String> categorys = jedis.zrange("categorys", 0, -1);
Set<Tuple> tuples = jedis.zrangeWithScores("categorys", 0, -1);
//从mysql中查询数据,并存入redis
List<Category> cs;
if (tuples == null || tuples.size() == 0) {
System.out.println("从数据库查询");
cs = dao.findAll();
//存入redis
for (Category c : cs) {
jedis.zadd("categorys", c.getCid(), c.getCname());
}
} else {
System.out.println("从redis查询");
//如果不为空,将set的数据转入list
cs = new ArrayList<Category>();
for (Tuple tuple : tuples) {
Category category = new Category();
category.setCname(tuple.getElement());
category.setCid((int) tuple.getScore());
cs.add(category);
}
}
return cs;
}
根据redis中是否存在相应的数据,诺存在将从redis中取出数据,诺不存在从mysql数据库中取出数据,存入redis中,并返回.
由于需要分类的id,而jedis中zrange()没有无法获取对应存储的score的,所以使zrangeWithScores()方法.而返回的Set< Tuple >进行转换为List< Category >并返回
- Dao
@Override
public List<Category> findAll() {
String sql = "select * from tab_category order by cid asc";
return template.query(sql, new BeanPropertyRowMapper<Category>(Category.class));
}
对查询的分类信息进行排序,防止混乱显示
前端代码实现
//获取分类信息
$.get("category/findAll", function (data) {
var lis = '<li class="nav-active"><a href="index.html">首页</a></li>'
//遍历数组,拼接字符串
$(data).each(function (index, elemeth) {
var li = '<li><a href="route_list.html">' + elemeth.cname + '</a></li>'
lis += li;
});
//拼接收藏排行榜的li
lis += '<li><a href="favoriterank.html">收藏排行榜</a></li>';
$("#category").html(lis)
});
使用ajax进行异步请求