Solr定时更新

时间:2023-03-08 21:20:15

今天用到solr定时重建索引和增量更新技术,就从网上搜了一些资料,在这里给大家整理了一下,也经过了自己的测试,没有异常。

Solr官方提供了很强大的Data Import Request Handler,同时提供了一个简单的 Scheduler,示例中的 Scheduler 只支持增量更新,不支持定期重做索引,因此我做了一个简单的封装,增加了重做索引的定时器。

1. 将 apache-solr-dataimportscheduler-1.0.jar 和solr自带的 solr-dataimporthandler-4.7.1.jar、 solr-dataimporthandler-extras-4.7.1.jar 放到tomcat发布的webapps/solr/WEB-INF/lib目录下面(或者放到solr.war的lib目录下面)。
        2.修改tomcat发布的webapps/solr/WEB-INF/web.xml(或者修改solr.war中WEB-INF/web.xml), 在servlet节点前面增加:

<listener>
<listener-class>org.apache.solr.handler.dataimport.scheduler.ApplicationListener</listener-class>
</listener>

3.将apache-solr-dataimportscheduler-1.0-source.jar 中 dataimport.properties 取出并根据实际情况修改,然后放到 solr.home/conf (不是solr.home/core/conf) 目录下面,conf这个目录不存在,需要自己手动创建该目录即可。

4.重启tomcat或者jboss 即可。

dataimport.properties 配置项说明

#################################################
# #
# dataimport scheduler properties #
# #
################################################# # to sync or not to sync
# 1 - active; anything else - inactive
syncEnabled=1 # which cores to schedule
# in a multi-core environment you can decide which cores you want syncronized
# leave empty or comment it out if using single-core deployment
syncCores=core0,core1 # solr server name or IP address
# [defaults to localhost if empty]
server=localhost # solr server port
# [defaults to 80 if empty]
port=8080 # application name/context
# [defaults to current ServletContextListener's context (app) name]
webapp=solr # URL params [mandatory]
# remainder of URL
params=/dataimport?command=delta-import&clean=false&commit=true # schedule interval
# number of minutes between two runs
# [defaults to 30 if empty]
# 增量索引的时间间隔,单位分钟
# 为空,为0,或者注释掉:表示永不增量索引
interval=1 # 重做索引的时间间隔,单位分钟,默认7200,即5天;
# 为空,为0,或者注释掉:表示永不重做索引
reBuildIndexInterval=2 # 重做索引的参数
reBuildIndexParams=/dataimport?command=full-import&clean=false&commit=true # 重做索引时间间隔的计时开始时间,第一次真正执行的时间=reBuildIndexBeginTime+reBuildIndexInterval*60*1000;
# 两种格式:2012-04-11 03:10:00 或者 03:10:00,后一种会自动补全日期部分为服务启动时的日期
reBuildIndexBeginTime=03:10:00

对于以上配置,发现两个bug,一个是如果reBuildIndexBeginTime的值为空,则会导致interval强转时报错,另一个是请求solr服务器时返回的状态码永远是415(对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝。)

1、第一个bug

Solr定时更新

这一块代码直接导致一下方法调用的时候报强转错,

Solr定时更新

这个方法对interval属性进行了强转,

Solr定时更新

看如果reBuildIndexBeginTime为空时的设置的代码:

Solr定时更新

以上红框是更改后的格式,原格式只有“yyyy-MM-dd”部分,这样会导致启动的时候会不停地http请求solr服务器,因此需加“HH:mm:ss”,以此解决问题。
        第一个bug解决方法把图1中画红框的代码去除就行了。

2、第二个bug

Solr定时更新

导致原因是HTTP以post请求,我们知道dataimport.properties的param是以get方式的链接,参数也包含在里面,程序未对此链接形式做处理封装成post提交方式,所以导致请求solr失败,把Http链接方式改成get就行了。

关于上面提到apache-solr-dataimportscheduler-1.0.jar和apache-solr-dataimportscheduler-1.0-source.jar的原jar包和重新打包的在以下地址中

http://download.****.net/detail/ltr15036900300/7209195