作者:葫芦娃才是萌神 | 来源:互联网 | 2023-10-11 18:46
首先我们在taotao-search-interface工程中新建一个SearchService接口,并在接口中添加一个方法,如下图所示。接着,我们到taotao-search-s
首先我们在taotao-search-interface工程中新建一个SearchService接口,并在接口中添加一个方法,如下图所示。
接着,我们到taotao-search-service工程中添加一个SearchServiceImpl实现类,并实现SearchService接口,如下图所示。
为方便大家复制,现将SearchServiceImpl实现类的代码贴出。
/**
* 商品搜索服务实现类
* Title: SearchServiceImpl
* Description:
* Company: www.itcast.cn
* @version 1.0
*/
@Service
public class SearchServiceImpl implements SearchService {
@Autowired
private ItemSearchDao itemSearchDao;
@Override
public SearchResult search(String queryString, int page, int rows) throws Exception {
SolrQuery query = new SolrQuery();
query.setQuery(queryString);
if (page <1) {
page = 1;
}
query.setStart((page - 1) * rows);
if (rows <1) {
rows = 10;
}
query.setRows(rows);
query.set("df", "item_title");
query.setHighlight(true);
query.addHighlightField("item_title");
query.setHighlightSimplePre("");
query.setHighlightSimplePost("");
SearchResult searchResult = itemSearchDao.search(query);
long totalNumber = searchResult.getTotalNumber();
long totalPage = totalNumber / rows;
if (totalNumber % rows > 0) {
totalPage++;
}
searchResult.setTotalPage(totalPage);
return searchResult;
}
}
写完了Service,下面我们便要发布服务了,我们在taotao-search-service工程的applicationContext-service.xml文件中暴露搜索接口,如下图所示。
为方便大家复制,现将applicationContext-service.xml文件的内容贴出。
<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:dubbo="http://code.alibabatech.com/schema/dubbo" 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.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<context:component-scan base-package="com.taotao.search">context:component-scan>
<dubbo:application name="taotao-search" />
<dubbo:registry protocol="zookeeper" address="192.168.25.128:2181" />
<dubbo:protocol name="dubbo" port="20882" />
<dubbo:service interface="com.taotao.search.service.SearchItemService" ref="searchItemServiceImpl" timeout="300000" />
<dubbo:service interface="com.taotao.search.service.SearchService" ref="searchServiceImpl" timeout="300000" />
beans>
这样,实现商品搜索功能的Service层代码便写完了。