Solr单机版使用的是HttpSolrServer,集群版用的是CloudSolrServer,这两个类都是SolrServer的子类,我们在Dao层使用SolrServer抽象类进行操作,从而我们可以不用更改Dao层代码,只需要在spring容器中切换单机版或集群版Solr即可。
现在我们到applicationContext-solr.xml文件当中配置一下Solr集群,如下图所示。
为方便大家复制,现将applicationContext-solr.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: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://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!-- solr单机版 -->
<!-- <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
<constructor-arg name="baseURL" value="http://192.168.25.129:8080/solr" />
</bean> -->
<!-- Solr集群版 -->
<bean id="cloudSolrServer" class="org.apache.solr.client.solrj.impl.CloudSolrServer">
<constructor-arg name="zkHost" value="192.168.25.129:2181,192.168.25.129:2182,192.168.25.129:2183" />
<property name="defaultCollection" value="collection2"></property>
</bean>
</beans>
由于还没有将数据库中的数据导入到集群版的索引库中,因此我们需要到淘淘商城后台重新导入到索引库,整个过程耗费的时间比较长,可能需要一两分钟左右,如下图所示。
导入成功后,我们访问淘淘商城首页,并在搜索框中输入”iPhone6”关键字并按回车进行搜索,发现可以正常搜索到结果,如下图所示,这说明我们切换到集群版后,代码完全没问题。