前面已经讲过 如果安装及配置Solr服务器了, 那么现在我们就来正式在代码中使用Solr.
1,这里Solr主要是怎么使用的呢?
当我们在前台页面搜索商品名称关键词时, 我们这时是在Solr库中去查找相应的商品信息, 然后将搜索关键词高亮.
2,那么Solr库中的商品信息又是如何添加的呢?
当我们在给商品上架的时候, 将商品信息update 到mysql数据库中的bbs_product表中, 然后同样的将相应的信息 添加到Solr库中.
接下来就看代码的具体实现吧:
一, 商品上架
我们在这里点击上架按钮:
list.jsp:1
点击上架触发isShow事件:
1
接着到Controller层:
ProductController.java:1 //添加页面2 @RequestMapping("/isShow.do")3 public String isShow(Long[] ids, Model model){4 productService.isShow(ids);5 return "forward:/product/list.do";6 }
接着看Service层:
ProdcutServiceImpl.java:
1 //上架@Autowired
private SolrServer solrServer; 2 public void isShow(Long[] ids){ 3 Product product = new Product(); 4 product.setIsShow(true); 5 for (Long id : ids) { 6 //上下架状态 7 product.setId(id); 8 productDao.updateByPrimaryKeySelective(product); 9 10 //TODO 保存商品信息到Solr服务器11 SolrInputDocument doc = new SolrInputDocument();12 //ID13 doc.setField("id", id);14 //名称15 Product p = productDao.selectByPrimaryKey(id);16 doc.setField("name_ik", p.getName());17 //图片URL18 doc.setField("url", p.getImgUrls()[0]);19 //品牌 ID20 doc.setField("brandId", p.getBrandId());21 //价格 sql查询语句: select price from bbs_sku where product_id = ? order by price asc limit 122 SkuQuery skuQuery = new SkuQuery();23 skuQuery.createCriteria().andProductIdEqualTo(id);24 skuQuery.setOrderByClause("price asc");25 skuQuery.setPageNo(1);26 skuQuery.setPageSize(1);27 List skus = skuDao.selectByExample(skuQuery);28 doc.setField("price", skus.get(0).getPrice());29 //...时间等 剩下的省略30 31 try {32 solrServer.add(doc);33 solrServer.commit();34 } catch (Exception e) {35 // TODO Auto-generated catch block36 e.printStackTrace();37 }38 //TODO 静态化39 }40 }
这里使用SolrInputDocument 来保存商品信息, 其中doc.setField("name_ik", p.getName());的name_ik 是我们在solr 配置文件配置的IK 分词器的字段, doc.setField("url", p.getImgUrls()[0]); 这里我们也只是取第一张图片的u