我们作为开发者,很多时候需要学习一些技术,正好我刚好有需求要去研究搜索引擎,当研究es的时候,es的logstash-jdbc-input数据同步工具这个工具只需要配置好 jdbc_page_size => "1000" 就会自动分页就不用怕数据量太大而导致内存溢出或者是连接数据库超时。
但是solr的data-config.xml是没有类似配置项的,网上搜寻了资料可以在全量查询语句上加上自定义参数。下图的${dataimporter.request.length} ${dataimporter.request.offset}这两个参数可以通过url传入。
<entity name="search_data" dataSource="engine_test" PK="id"
query="select * from test limit ${dataimporter.request.length} offset ${dataimporter.request.offset}">
package com.yc.util;
import feign.Feign;
import feign.Request;
import feign.Retryer;
import feign.Param;
import feign.RequestLine;
public class DataImportToSolr {
/** http://localhost:8888/solr/search/dataimport?core=search&offset=0
* &indent=on&commit=true&length=500&name=dataimport&clean=false&wt=json&
* command=full-import**/
public static void main(String[] args) {
SolrCommand solrCommand = Feign.builder()
.options(new Request.Options(1000, 3500))
.retryer(new Retryer.Default(5000, 5000, 3))
.target(SolrCommand.class, "http://localhost:8888");
int length = 100000;
int total = 2000000;
for (int i = 0; i <= total / length; i++) {
long begin = System.currentTimeMillis();
System.out.println("第" + i + "页");
while(true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = solrCommand.insertToSolrPageable(length, i * length);
if (!result.contains("busy")) {
System.out.println("即将开始下一页...");
break;
}
}
System.out.println("总共花费时间" + (System.currentTimeMillis() - begin) + "ms");
}
}
}
interface SolrCommand {
// RequestLine注解声明请求方法和请求地址,可以允许有查询参数
@RequestLine("GET solr/search/dataimport?core=search&indent=on&commit=true" + "&length={length}&offset={offset}"
+ "&name=dataimport&clean=false&wt=json&command=full-import")
String insertToSolrPageable(@Param(value = "length") Integer length, @Param(value = "offset") Integer offset);
}
以上代码是分页导入到solr的程序。url是solr的dataimport功能的url加上我们自定义的参数就好了。可以先在solr管理界面点一次全量同步获取到url再分页同步数据
需要引入feign,maven代码
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>8.18.0</version>
<scope>runtime</scope>
</dependency>