java:solr

1.solr(数据导入solr自带数据库):

  

    ImportItemController.java:

package com.solr.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.solr.service.ItemService;

@RestController
@RequestMapping("/importItem")
public class ImportItemController {

    @Autowired
    private ItemService itemService;

    @RequestMapping("/import")
    public String importImtems() {
        // 调用service
        return itemService.importItems();
    }

}

  SearchItemController.java:

package com.solr.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.solr.service.SearchItemService;
import com.solr.utils.JSONUtil;

@RestController
@RequestMapping("/searchItem")
public class SearchItemController {

    @Autowired
    private SearchItemService searchItemService;

    /**
     * @description queryCondition就是前端搜索框中用户输入的内容
     * @param param
     * @return
     */
    @RequestMapping("/byQueryCondition/{q}")
    public String searchItems(@PathVariable("q") String queryCondition) {
        Map<Integer, Object> resultMap = new HashMap<Integer, Object>();
        // 第一步:判断用户是否输入了搜索关键字
        if (null == queryCondition && "".equals(queryCondition)) {
            // 报错404
            resultMap.put(500, "未找到查询条件");
        } else {
            // 调用service来从solr中查询出所需要的数据
            try {
                queryCondition = new String(queryCondition.getBytes("ISO-8859-1"), "UTF-8");
                String resultJson = searchItemService.queryItem(queryCondition);
                resultMap.put(200, resultJson);
            } catch (Exception e) {
                e.printStackTrace();
                resultMap.put(500, "solr服务器未检索到数据");
            }
        }
        return JSONUtil.toJSONString(resultMap);
    }
}

  ItemCategoryMapper.java:

package com.solr.mapper;

import com.solr.model.ItemCategory;
import tk.mybatis.mapper.common.Mapper;

public interface ItemCategoryMapper extends Mapper<ItemCategory> {
}

  ItemDescMapper.java:

package com.solr.mapper;

import com.solr.model.ItemDesc;
import tk.mybatis.mapper.common.Mapper;

public interface ItemDescMapper extends Mapper<ItemDesc> {
}

  ItemMapper.java:

package com.solr.mapper;

import com.solr.model.Item;
import tk.mybatis.mapper.common.Mapper;

public interface ItemMapper extends Mapper<Item> {
}

  Item.java(生成器自动生成):

package com.solr.model;

import java.util.Date;
import javax.persistence.*;

@Table(name = "ego_item")
public class Item {
    /**
     * 商品id,同时也是商品编号
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 商品标题
     */
    private String title;

    /**
     * 商品卖点
     */
    @Column(name = "sell_point")
    private String sellPoint;

    /**
     * 商品价格,单位为:分
     */
    private Long price;

    /**
     * 库存数量
     */
    private Integer num;

    /**
     * 商品条形码
     */
    private String barcode;

    /**
     * 商品图片
     */
    private String image;

    /**
     * 所属类目,叶子类目
     */
    private Long cid;

    /**
     * 商品状态,1-正常,2-下架,3-删除
     */
    private Byte status;

    /**
     * 创建时间
     */
    private Date created;

    /**
     * 更新时间
     */
    private Date updated;

    /**
     * 获取商品id,同时也是商品编号
     *
     * @return id - 商品id,同时也是商品编号
     */
    public Long getId() {
        return id;
    }

    /**
     * 设置商品id,同时也是商品编号
     *
     * @param id 商品id,同时也是商品编号
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * 获取商品标题
     *
     * @return title - 商品标题
     */
    public String getTitle() {
        return title;
    }

    /**
     * 设置商品标题
     *
     * @param title 商品标题
     */
    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    /**
     * 获取商品卖点
     *
     * @return sell_point - 商品卖点
     */
    public String getSellPoint() {
        return sellPoint;
    }

    /**
     * 设置商品卖点
     *
     * @param sellPoint 商品卖点
     */
    public void setSellPoint(String sellPoint) {
        this.sellPoint = sellPoint == null ? null : sellPoint.trim();
    }

    /**
     * 获取商品价格,单位为:分
     *
     * @return price - 商品价格,单位为:分
     */
    public Long getPrice() {
        return price;
    }

    /**
     * 设置商品价格,单位为:分
     *
     * @param price 商品价格,单位为:分
     */
    public void setPrice(Long price) {
        this.price = price;
    }

    /**
     * 获取库存数量
     *
     * @return num - 库存数量
     */
    public Integer getNum() {
        return num;
    }

    /**
     * 设置库存数量
     *
     * @param num 库存数量
     */
    public void setNum(Integer num) {
        this.num = num;
    }

    /**
     * 获取商品条形码
     *
     * @return barcode - 商品条形码
     */
    public String getBarcode() {
        return barcode;
    }

    /**
     * 设置商品条形码
     *
     * @param barcode 商品条形码
     */
    public void setBarcode(String barcode) {
        this.barcode = barcode == null ? null : barcode.trim();
    }

    /**
     * 获取商品图片
     *
     * @return image - 商品图片
     */
    public String getImage() {
        return image;
    }

    /**
     * 设置商品图片
     *
     * @param image 商品图片
     */
    public void setImage(String image) {
        this.image = image == null ? null : image.trim();
    }

    /**
     * 获取所属类目,叶子类目
     *
     * @return cid - 所属类目,叶子类目
     */
    public Long getCid() {
        return cid;
    }

    /**
     * 设置所属类目,叶子类目
     *
     * @param cid 所属类目,叶子类目
     */
    public void setCid(Long cid) {
        this.cid = cid;
    }

    /**
     * 获取商品状态,1-正常,2-下架,3-删除
     *
     * @return status - 商品状态,1-正常,2-下架,3-删除
     */
    public Byte getStatus() {
        return status;
    }

    /**
     * 设置商品状态,1-正常,2-下架,3-删除
     *
     * @param status 商品状态,1-正常,2-下架,3-删除
     */
    public void setStatus(Byte status) {
        this.status = status;
    }

    /**
     * 获取创建时间
     *
     * @return created - 创建时间
     */
    public Date getCreated() {
        return created;
    }

    /**
     * 设置创建时间
     *
     * @param created 创建时间
     */
    public void setCreated(Date created) {
        this.created = created;
    }

    /**
     * 获取更新时间
     *
     * @return updated - 更新时间
     */
    public Date getUpdated() {
        return updated;
    }

    /**
     * 设置更新时间
     *
     * @param updated 更新时间
     */
    public void setUpdated(Date updated) {
        this.updated = updated;
    }
}

  ItemCategory.java:

package com.solr.model;

import java.util.Date;
import javax.persistence.*;

@Table(name = "ego_item_cat")
public class ItemCategory {
    /**
     * 类目ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 父类目ID=0时,代表的是一级的类目
     */
    @Column(name = "parent_id")
    private Long parentId;

    /**
     * 类目名称
     */
    private String name;

    /**
     * 状态。可选值:1(正常),2(删除)
     */
    private Integer status;

    /**
     * 排列序号,表示同级类目的展现次序,如数值相等则按名称次序排列。取值范围:大于零的整数
     */
    @Column(name = "sort_order")
    private Integer sortOrder;

    /**
     * 该类目是否为父类目,1为true,0为false
     */
    @Column(name = "is_parent")
    private Boolean isParent;

    /**
     * 创建时间
     */
    private Date created;

    /**
     * 创建时间
     */
    private Date updated;

    /**
     * 获取类目ID
     *
     * @return id - 类目ID
     */
    public Long getId() {
        return id;
    }

    /**
     * 设置类目ID
     *
     * @param id 类目ID
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * 获取父类目ID=0时,代表的是一级的类目
     *
     * @return parent_id - 父类目ID=0时,代表的是一级的类目
     */
    public Long getParentId() {
        return parentId;
    }

    /**
     * 设置父类目ID=0时,代表的是一级的类目
     *
     * @param parentId 父类目ID=0时,代表的是一级的类目
     */
    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    /**
     * 获取类目名称
     *
     * @return name - 类目名称
     */
    public String getName() {
        return name;
    }

    /**
     * 设置类目名称
     *
     * @param name 类目名称
     */
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    /**
     * 获取状态。可选值:1(正常),2(删除)
     *
     * @return status - 状态。可选值:1(正常),2(删除)
     */
    public Integer getStatus() {
        return status;
    }

    /**
     * 设置状态。可选值:1(正常),2(删除)
     *
     * @param status 状态。可选值:1(正常),2(删除)
     */
    public void setStatus(Integer status) {
        this.status = status;
    }

    /**
     * 获取排列序号,表示同级类目的展现次序,如数值相等则按名称次序排列。取值范围:大于零的整数
     *
     * @return sort_order - 排列序号,表示同级类目的展现次序,如数值相等则按名称次序排列。取值范围:大于零的整数
     */
    public Integer getSortOrder() {
        return sortOrder;
    }

    /**
     * 设置排列序号,表示同级类目的展现次序,如数值相等则按名称次序排列。取值范围:大于零的整数
     *
     * @param sortOrder 排列序号,表示同级类目的展现次序,如数值相等则按名称次序排列。取值范围:大于零的整数
     */
    public void setSortOrder(Integer sortOrder) {
        this.sortOrder = sortOrder;
    }

    /**
     * 获取该类目是否为父类目,1为true,0为false
     *
     * @return is_parent - 该类目是否为父类目,1为true,0为false
     */
    public Boolean getIsParent() {
        return isParent;
    }

    /**
     * 设置该类目是否为父类目,1为true,0为false
     *
     * @param isParent 该类目是否为父类目,1为true,0为false
     */
    public void setIsParent(Boolean isParent) {
        this.isParent = isParent;
    }

    /**
     * 获取创建时间
     *
     * @return created - 创建时间
     */
    public Date getCreated() {
        return created;
    }

    /**
     * 设置创建时间
     *
     * @param created 创建时间
     */
    public void setCreated(Date created) {
        this.created = created;
    }

    /**
     * 获取创建时间
     *
     * @return updated - 创建时间
     */
    public Date getUpdated() {
        return updated;
    }

    /**
     * 设置创建时间
     *
     * @param updated 创建时间
     */
    public void setUpdated(Date updated) {
        this.updated = updated;
    }
}

  ItemDesc.java:

package com.solr.model;

import java.util.Date;
import javax.persistence.*;

@Table(name = "ego_item_desc")
public class ItemDesc {
    /**
     * 主键
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 商品ID
     */
    @Column(name = "item_id")
    private Long itemId;

    /**
     * 创建时间
     */
    private Date created;

    /**
     * 更新时间
     */
    private Date updated;

    /**
     * 商品描述
     */
    @Column(name = "item_desc")
    private String itemDesc;

    /**
     * 获取主键
     *
     * @return id - 主键
     */
    public Long getId() {
        return id;
    }

    /**
     * 设置主键
     *
     * @param id 主键
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * 获取商品ID
     *
     * @return item_id - 商品ID
     */
    public Long getItemId() {
        return itemId;
    }

    /**
     * 设置商品ID
     *
     * @param itemId 商品ID
     */
    public void setItemId(Long itemId) {
        this.itemId = itemId;
    }

    /**
     * 获取创建时间
     *
     * @return created - 创建时间
     */
    public Date getCreated() {
        return created;
    }

    /**
     * 设置创建时间
     *
     * @param created 创建时间
     */
    public void setCreated(Date created) {
        this.created = created;
    }

    /**
     * 获取更新时间
     *
     * @return updated - 更新时间
     */
    public Date getUpdated() {
        return updated;
    }

    /**
     * 设置更新时间
     *
     * @param updated 更新时间
     */
    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    /**
     * 获取商品描述
     *
     * @return item_desc - 商品描述
     */
    public String getItemDesc() {
        return itemDesc;
    }

    /**
     * 设置商品描述
     *
     * @param itemDesc 商品描述
     */
    public void setItemDesc(String itemDesc) {
        this.itemDesc = itemDesc == null ? null : itemDesc.trim();
    }
}

  ItemService.java:

package com.solr.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.solr.mapper.ItemCategoryMapper;
import com.solr.mapper.ItemDescMapper;
import com.solr.mapper.ItemMapper;
import com.solr.model.Item;
import com.solr.model.ItemDesc;
import com.solr.utils.JSONUtil;

@Service
public class ItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemCategoryMapper itemCategoryMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Autowired
    private SolrServer solrServer;

    /**
     * @description 从数据库中查询出数据导入solr库
     * @return
     */
    public String importItems() {
        Map<Integer, Object> resultMap = new HashMap<Integer, Object>();
        // 第一步:从mysql数据库中查询出商品信息(List<Item>),需要ItemMapper
        List<Item> itemList =  itemMapper.selectAll();// 从mysql中查询出所有的商品信息
        // 第二步:开始向solr库中进行导入
        // 在solr配置文件(schema.xml)中,只需要item_title,sell_porint,price,image,category,desc,但是从mysql查询出的字段多余
        for(Item item : itemList) {
            // SolrInputDocument
            SolrInputDocument solrDocument = new SolrInputDocument();
            solrDocument.addField("id", item.getId());
            solrDocument.addField("item_title", item.getTitle());
            solrDocument.addField("item_sell_point", item.getSellPoint());
            solrDocument.addField("item_price", item.getPrice());
            solrDocument.addField("item_image", item.getImage());
            if(item.getCid() != null && item.getCid() > 0L) {
                // 从数据库中通过cid查询出商品类目名称
                solrDocument.addField("item_category_name", itemCategoryMapper.selectByPrimaryKey(item.getCid()).getName());
            }
            ItemDesc itemDesc = new ItemDesc();
            itemDesc.setItemId(item.getId());
            ItemDesc itemDescription = itemDescMapper.selectOne(itemDesc);
            if(itemDescription != null) {
                solrDocument.addField("item_desc", itemDescription.getItemDesc());
            }
            // 需要通过某一个class向solr服务器存入数据
            try {
                solrServer.add(solrDocument);
                resultMap.put(200, "数据导入成功");
            } catch (SolrServerException e) {
                e.printStackTrace();
                resultMap.put(500, "数据导入异常");
            } catch (IOException e) {
                e.printStackTrace();
                resultMap.put(500, "数据导入异常");
            }
        }
        return JSONUtil.toJSONString(resultMap);
    }

}

  SearchItemService.java:

package com.solr.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.solr.model.Item;
import com.solr.utils.JSONUtil;

@Service
public class SearchItemService {

    @Autowired
    private SolrServer solrServer;

    public String queryItem(String param) throws Exception {

        // 第一步:创建出solr的搜索对象SolrQuery-->solr-solrj,java调用solr提供的查询数据的接口
        SolrQuery query = new SolrQuery();
        // 把需要写入的条件传入到SolrQuery对象中
        query.setQuery(param);
        // 设置查询的起始条数
        query.setStart(0);
        // 每页显示的条数
        query.setRows(20);
        // 设置查询关键字
        query.set("df", "item_keywords");

        // 设置高亮显示
        query.setHighlight(true);
        // 设置需要高亮显示的字段
        query.addHighlightField("item_title");
        // 设置需要高亮显示的颜色
        // 用户在搜索框中搜索了"华为"---><font color="yellow">华为</font>
        query.setHighlightSimplePre("<font style=‘color:red‘>");
        query.setHighlightSimplePost("</font>");

        // 首先从solr服务器中查询出所有的匹配结果 并且返回
        QueryResponse response = solrServer.query(query);
        // response-->用户在搜索框中输入的关键字-->点击搜索按钮-->调用controller-->调用service-->到solr服务器中进行查询
        // -->把查询出的封装成QueryResponse(搜索出的数据)
        SolrDocumentList solrDocumentList = response.getResults();// response.getResults();获取的是查询出的所有结果集文档

        // response.getHighlighting();-->获取存入的高亮信息<font style="color:yellow;">华为</font>xxxxxx....
        Map<String, Map<String, List<String>>> hl = response.getHighlighting();

        // 转换为Java对象的结果集
        List<Item> itemList = new ArrayList<>();
        // 数据导入的时候,把查询出的实体类集合进行便利-->存入solrDocument
        // 从solr查询数据的时候,首先把查询出的solrDocumentList便利-->存入每一个实体类中-->把存好的实体类再存入list集合中
        // 方便页面通过jstl进行展示
        for (SolrDocument doc : solrDocumentList) {
            // 把结果集文档,转换成实体对象-->最终要显示页面上
            Item item = new Item();
            item.setId(Long.parseLong((String) doc.get("id")));
            item.setImage((String) doc.get("item_image"));
            item.setPrice((Long) doc.get("item_price"));

            // 因为map比较适合转换为json对象,所以封装到map中比较合适
            Map<String, List<String>> h = hl.get((String) doc.get("id"));
            // Map<String, List<String>>-->map:key=item_title
            //List<String>:带有高亮显示的item_title
            //List<String>:<font style="color:yellow;">索尼</font>(SONY) KD-55X9000B 55英寸 智能 4K 电视
            List<String> l = h.get("item_title");
            if (l != null && l.size() > 0) {
                item.setTitle(l.get(0));// 现在item实体类已经拥有了高亮显示的title信息
            } else {
                item.setTitle((String) doc.get("item_title"));// 如果没有获取到数据,就把不是高亮显示的title信息封装到实体对象中
            }
            itemList.add(item);
        }
        return JSONUtil.toJSONString(itemList);
    }

}

  JSONUtil.java:

package com.solr.utils;

import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtil {

    // 定义jackson对象
    private static final ObjectMapper mapper = new ObjectMapper();
    /**
     * 将对象转换成json字符串
     * @param data
     * @return
     */
    public static String toJSONString(Object data) {
        try {
            String string = mapper.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json结果集转化为对象
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> T parseObject(String jsonData, Class<T> beanType) {
        try {
            T t = mapper.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json数据转换成list
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> List<T> parseArray(String jsonData, Class<T> beanType) {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = mapper.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

  ItemCategoryMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.solr.mapper.ItemCategoryMapper" >
  <resultMap id="BaseResultMap" type="com.solr.model.ItemCategory" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="parent_id" property="parentId" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="INTEGER" />
    <result column="sort_order" property="sortOrder" jdbcType="INTEGER" />
    <result column="is_parent" property="isParent" jdbcType="BIT" />
    <result column="created" property="created" jdbcType="TIMESTAMP" />
    <result column="updated" property="updated" jdbcType="TIMESTAMP" />
  </resultMap>
</mapper>

  ItemDescMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.solr.mapper.ItemDescMapper" >
  <resultMap id="BaseResultMap" type="com.solr.model.ItemDesc" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="item_id" property="itemId" jdbcType="BIGINT" />
    <result column="created" property="created" jdbcType="TIMESTAMP" />
    <result column="updated" property="updated" jdbcType="TIMESTAMP" />
    <result column="item_desc" property="itemDesc" jdbcType="LONGVARCHAR" />
  </resultMap>
</mapper>

  ItemMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.solr.mapper.ItemMapper" >
  <resultMap id="BaseResultMap" type="com.solr.model.Item" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="sell_point" property="sellPoint" jdbcType="VARCHAR" />
    <result column="price" property="price" jdbcType="BIGINT" />
    <result column="num" property="num" jdbcType="INTEGER" />
    <result column="barcode" property="barcode" jdbcType="VARCHAR" />
    <result column="image" property="image" jdbcType="VARCHAR" />
    <result column="cid" property="cid" jdbcType="BIGINT" />
    <result column="status" property="status" jdbcType="TINYINT" />
    <result column="created" property="created" jdbcType="TIMESTAMP" />
    <result column="updated" property="updated" jdbcType="TIMESTAMP" />
  </resultMap>
</mapper>

  mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- mybatis默认是没有开启延迟加载的 需要手动开启 -->
    <settings>
        <!-- 延迟加载 默认false -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 积极加载 默认true -->
        <setting name="aggressiveLazyLoading" value="false" />
        <!--开启缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

  applicationContext-db.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--数据源配置 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件,**表示迭代查找 -->
        <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml" />
        <!--mybatis配置文件位置 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
    </bean>

    <!--扫描com.solr下的mapper接口 -->
    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.solr" />
        <!--使用mybatis通用mapper插件 -->
        <property name="properties">
            <value>
                mappers=tk.mybatis.mapper.common.Mapper
            </value>
        </property>
    </bean>
</beans>

  applicationContext-solr.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

    <bean id="solrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
    <!-- baseURL:用来连接solr的集群(服务器) -->
        <!-- baseURL:指向了solr的地址 http://ip地址:端口号/solr -->
        <constructor-arg name="baseURL" value="${solr.service.url}" />
    </bean>

</beans>

  applicationContext-tx.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 事务详情 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- <tx:method name="select*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" /> -->
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>
    <!--支持基于注解的aspectj -->
    <aop:aspectj-autoproxy />

    <!--aop编程,切入点表达式 确定增强的连接器,从而获得切入点 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.solr.service..*.*(..)))" />
    </aop:config>
</beans>

  applicationContext-mvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 自动扫描且只扫描@Controller 扫描的是controller -->
    <context:component-scan base-package="com.solr.controller" />

    <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
    <mvc:default-servlet-handler />

    <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg index="0" value="UTF-8" />
            </bean>
            <!-- json的格式化 -->
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

  application.properties:

#MYSQL jdbc
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

#solr resource
solr.service.url=http\://192.168.1.184\:8080/solr

  applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

       <!-- 加载application.properties配置文件 -->
       <context:property-placeholder location="classpath:application.properties" />

       <!-- 开启扫描注解,spring只扫描service -->
       <context:component-scan base-package="com.solr.service" />

       <!-- 需要哪个配置文件就引入哪个 -->
       <import resource="spring/applicationContext-db.xml"/>
       <import resource="spring/applicationContext-solr.xml"/>
       <import resource="spring/applicationContext-tx.xml"/>

</beans>

  web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <!--spring入口文件的配置 -->
    <!-- 确定配置文件位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 配置spring 监听器,加载xml配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 解决POST请求的中文乱码 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- DispatcherServlet:前端控制器 配置前端控制器servlet -->
    <servlet>
        <servlet-name>solr_demo</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载前端控制器配置文件 上下文配置位置 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc/applicationContext-mvc.xml</param-value>
        </init-param>
        <!-- 表示随WEB服务器启动 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>solr_demo</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

  pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.solr</groupId>
    <artifactId>solr_demo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>solr_demo Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>

        <!-- junit begin -->
        <junit.version>4.12</junit.version>
        <!-- junit end -->

        <!-- spring begin -->
        <spring.version>4.3.4.RELEASE</spring.version>
        <!-- spring end -->

        <!-- json begin -->
        <jackson.version>2.8.1</jackson.version>
        <fastjson.version>1.2.17</fastjson.version>
        <!-- json end -->

        <!-- servlet jsp jstl begin -->
        <servlet-api.version>3.0.1</servlet-api.version>
        <jsp-api.version>2.0</jsp-api.version>
        <jstl.version>1.2</jstl.version>
        <!-- servlet jsp jstl end -->

        <!-- mysql begin -->
        <mysql.version>5.1.40</mysql.version>
        <!-- mysql begin -->

        <!-- druid begin -->
        <druid.version>1.0.26</druid.version>
        <!-- druid end -->

        <!-- mybatis begin -->
        <mybatis.version>3.3.0</mybatis.version>
        <mybatis.spring.version>1.2.3</mybatis.spring.version>
        <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
        <mybatis.mapper.version>3.3.9</mybatis.mapper.version>
        <!-- mybatis end -->

        <!-- ehcache begin -->
        <ehcache.version>2.10.3</ehcache.version>
        <!-- ehcache end -->

        <!-- solr begin -->
        <solrj.version>4.10.3</solrj.version>
        <!-- solr end -->

    </properties>

    <dependencies>
        <!-- 所需要的jar包 -->
        <!-- junit start -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- junit end -->

        <!--spring start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring end -->

        <!--json start -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <!--json end -->

        <!-- servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet-api.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- jsp -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp-api.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- database begin -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
        <!-- database end -->

        <!-- mybatis plugins begin -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>${mybatis.mapper.version}</version>
        </dependency>
        <!-- mybatis plugins end -->

        <!--ehcache 缓存配置 -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>${ehcache.version}</version>
        </dependency>

        <!-- solr客户端 -->
            <dependency>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-solrj</artifactId>
                <version>${solrj.version}</version>
            </dependency>
    </dependencies>
    <build>
        <finalName>solr_demo</finalName>
    </build>
</project>
时间: 2024-10-06 01:02:41

java:solr的相关文章

Java的solr操作实现

JAVA操作solr的实现其实很简单,但是很多细节要注意,在实际的开发中,很多人喜欢自己封装这些基础的方法以一个全新的“面貌”出现,其实都是一回事,操作熟了自然就会想到将一些实现功能用到的方法重新封装,这也是编程进阶的表现. SolrJ的使用 SolrJ覆盖了solr的全部功能,下面将自己在实际开发中所使用的程序粘贴出来并适当加以解释,由于本人比较菜,代码书写不是那么的精练,还请见谅. 1.  创建solrserver对象: try { solr = new CommonsHttpSolrSer

BugPhobia沟通篇章:Solr模式配置与数据导入调研

0x01 :Scrum Meeting特别说明 特别说明,考虑到编译原理课程考核的时间安排,每天开发时间急剧缩短以至于难以维系正常的Scrum Meeting,因此,将2015/12/13 00:00 A.M. ~ 2015/12/14 22:00 P.M.的Scrum Meeting合并,因此,第二次Scrum Meeting的开发时间为两天,此次将首先发布Solr模式配置与数据导入调研方便沟通工作的进一步开展 0x01 :模式配置说明(Schema.xml) 0x0100 :types段落定

java操作solr实现索引,查询,删除,拼写检查等功能

使用java操作solr 前面讲了很多对solr的操作都是直接在页面上操作的,实际工作中肯定是要使用java进行操作的,在这我们就看一下如何使用java来操作solr Solr提供了solrj来使用java操作solr,SolrJ是封装了httpClient方法,来操作solr的API的.首先添加maven依赖 <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj<

深入理解Java:注解(Annotation)--注解处理器

深入理解Java:注解(Annotation)--注解处理器 如果没有用来读取注解的方法和工作,那么注解也就不会比注释更有用处了.使用注解的过程中,很重要的一部分就是创建于使用注解处理器.Java SE5扩展了反射机制的API,以帮助程序员快速的构造自定义注解处理器. 注解处理器类库(java.lang.reflect.AnnotatedElement): Java使用Annotation接口来代表程序元素前面的注解,该接口是所有Annotation类型的父接口.除此之外,Java在java.l

深入理解Java:注解(Annotation)自己定义注解入门

深入理解Java:注解(Annotation)自己定义注解入门 要深入学习注解.我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前.我们就必须要了解Java为我们提供的元注解和相关定义注解的语法. 元注解: 元注解的作用就是负责注解其它注解. Java5.0定义了4个标准的meta-annotation类型.它们被用来提供对其它 annotation类型作说明.Java5.0定义的元注解: [email protected], [email protected], [email pro

Java:String、StringBuffer和StringBuilder的区别

Java:String.StringBuffer和StringBuilder的区别 1 String String:字符串常量,字符串长度不可变.Java中String是immutable(不可变)的. String类的包含如下定义: [java] view plain copy /** The value is used for character storage. */ private final char value[]; /** The offset is the first index

Java:String和Date、Timestamp之间的转换

一.String与Date(java.util.Date)互转 1.1 String -> Date Java代码   String dateStr = "2010/05/04 12:34:23"; Date date = new Date(); //注意format的格式要与日期String的格式相匹配 DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { date = sdf

java:打包

包名命名规范: 1.包名全部小写 2.包名一般情况下是域名的倒过来写+个性命名,如:tinyphp.com,就写成com.tinyphp+.xxx 打包方法 package + 包名 package test; class Test {.. } 运行: E:\d>javac -d . Test.java 就会生成一个test文件夹 -d 就是目录的意思,directory," . "是当前目录 调用类的路径也会改变,格式:"包名"+"."+

Kotlin中变量不同于Java: var 对val(KAD 02)

原文标题:Variables in Kotlin, differences with Java. var vs val (KAD 02) 作者:Antonio Leiva 时间:Nov 28, 2016 原文链接:http://antonioleiva.com/variables-kotlin/ Kotlin系列课程的第二课:Kotlin中变量不同于Java: var 对val. 在这第二章节中,我们将了解Kotlin中变量是怎样工作的,什么是val和var,什么时间使用它们. 我从这开始,是因