首页 > 其他分享 >solrj integration with Spring

solrj integration with Spring

时间:2023-04-28 11:08:29浏览次数:51  
标签:solrj Spring integration server import apache org solr public

The first one is EmbeddedSolrServer, so I do not need to start my standalone solr server, I can run the junit tests.
The pom.xml are as follow:
<dependency>
    <groupId>org.apache.solr</groupId>
    <artifactId>solr-solrj</artifactId>
    <version>3.6.0</version>
    </dependency>
    <dependency>
    <groupId>org.apache.solr</groupId>
    <artifactId>solr-core</artifactId>
    <version>3.6.0</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.4</version>
    </dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.1.3</version>
    </dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.1.3</version>
    </dependency>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.1.3</version>
    </dependency>


package com.sillycat.easyhunter.plugin.solr;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.CoreContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;

public class EmbeddedSolrServerTest {

EmbeddedSolrServer server = null;

@Before
public void init() {
System.setProperty("solr.solr.home",
"D:\\book\\solr\\apache-solr-3.6.0\\example\\solr");
CoreContainer.Initializer initializer = new CoreContainer.Initializer();
CoreContainer coreContainer = null;
try {
coreContainer = initializer.initialize();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
server = new EmbeddedSolrServer(coreContainer, "");
}

@After
public void destory() {
server = null;
System.runFinalization();
System.gc();
}

public final void fail(Object o) {
System.out.println(o);
}

@Test
public void server() {
fail(server);
}

@Test
public void query() {
String query = "name:DDR";
SolrParams params = new SolrQuery(query);

try {
QueryResponse response = server.query(params);

SolrDocumentList list = response.getResults();
for (int i = 0; i < list.size(); i++) {
fail(list.get(i));
}
} catch (SolrServerException e) {
e.printStackTrace();
}
}
}

CommonsHttpSolrServer is under deprecation. So in 3.6.0, I change to use HttpSolrServer.

package com.sillycat.easyhunter.plugin.solr;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.SolrParams;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class HttpSolrServerTest {

private HttpSolrServer server;

private static final String DEFAULT_URL = "http://localhost:8983/solr/";

@Before
public void init() {
server = new HttpSolrServer(DEFAULT_URL);
server.setSoTimeout(1000); // socket read timeout 
server.setConnectionTimeout(100); 
server.setDefaultMaxConnectionsPerHost(100); 
server.setMaxTotalConnections(100); 
server.setFollowRedirects(false); // defaults to false 
// allowCompression defaults to false. 
// Server side must support gzip or deflate for this to have any effect. 
server.setAllowCompression(true); 
server.setMaxRetries(1); // defaults to 0.  > 1 not recommended. 

//sorlr J 目前使用二进制的格式作为默认的格式。对于solr1.2的用户通过显示的设置才能使用XML格式。
server.setParser(new XMLResponseParser());
}

@After
public void destory() {
server = null;
System.runFinalization();
System.gc();
}

public final void fail(Object o) {
System.out.println(o);
}

@Test
public void server() {
fail(server);
}

@Test
public void query() {
String query = "name:DDR";
SolrParams params = new SolrQuery(query);
try {
QueryResponse response = server.query(params);

SolrDocumentList list = response.getResults();
for (int i = 0; i < list.size(); i++) {
fail(list.get(i));
}
} catch (SolrServerException e) {
e.printStackTrace();
}
}

}

It is not very simple to use these things like this, so I try to write a factory class for solrserver.
package com.sillycat.easyhunter.plugin.solr;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.core.CoreContainer;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.xml.sax.SAXException;

import com.sillycat.easyhunter.common.StringUtil;

public class SolrServerFactory implements FactoryBean<SolrServer>,
InitializingBean {

protected final Log log = LogFactory.getLog(getClass());

private final String DEFAULT_SERVER_URL = "http://localhost:8983/solr/";

private final String DEFAULT_SOLR_HOME = "D:\\book\\solr\\apache-solr-3.6.0\\example\\solr";

private final String DEFAULT_SOLR_SERVER_CLASS_NAME = "org.apache.solr.client.solrj.embedded.EmbeddedSolrServer";

private String serverURL;

private String solrHome;

private String solrServerClassName;

private SolrServer solrServer = null;

public SolrServer getObject() throws Exception {
return solrServer;
}

public Class<SolrServer> getObjectType() {
return SolrServer.class;
}

public boolean isSingleton() {
return true;
}

public void afterPropertiesSet() throws Exception {
if ("org.apache.solr.client.solrj.embedded.EmbeddedSolrServer"
.equalsIgnoreCase(this.getSolrServerClassName())) {
System.setProperty("solr.solr.home", this.getSolrHome());
CoreContainer.Initializer initializer = new CoreContainer.Initializer();
CoreContainer coreContainer = null;
try {
coreContainer = initializer.initialize();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
EmbeddedSolrServer server = new EmbeddedSolrServer(coreContainer, "");
solrServer = server;
} else if ("org.apache.solr.client.solrj.impl.HttpSolrServer"
.equalsIgnoreCase(this.getSolrServerClassName())) {
HttpSolrServer server = new HttpSolrServer(this.getServerURL());
server.setSoTimeout(1000); // socket read timeout
server.setConnectionTimeout(100);
server.setDefaultMaxConnectionsPerHost(100);
server.setMaxTotalConnections(100);
server.setFollowRedirects(false); // defaults to false
// allowCompression defaults to false.
// Server side must support gzip or deflate for this to have any
// effect.
server.setAllowCompression(true);
server.setMaxRetries(1); // defaults to 0. > 1 not recommended.

// sorlr J 目前使用二进制的格式作为默认的格式。对于solr1.2的用户通过显示的设置才能使用XML格式。
server.setParser(new XMLResponseParser());
solrServer =  server;
}
}

public String getServerURL() {
if (StringUtil.isBlank(serverURL)) {
serverURL = DEFAULT_SERVER_URL;
}
return serverURL;
}

public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}

public String getSolrHome() {
if (StringUtil.isBlank(solrHome)) {
solrHome = DEFAULT_SOLR_HOME;
}
return solrHome;
}

public void setSolrHome(String solrHome) {
this.solrHome = solrHome;
}

public String getSolrServerClassName() {
if (StringUtil.isBlank(solrServerClassName)) {
solrServerClassName = DEFAULT_SOLR_SERVER_CLASS_NAME;
}
return solrServerClassName;
}

public void setSolrServerClassName(String solrServerClassName) {
this.solrServerClassName = solrServerClassName;
}
}

The spring configuration will be 

<bean id="httpSolrServer" class="com.sillycat.easyhunter.plugin.solr.SolrServerFactory">
<property name="solrServerClassName" value="org.apache.solr.client.solrj.impl.HttpSolrServer"/>
<property name="serverURL" value="http://localhost:8983/solr/" />
</bean>

<bean id="embeddedSolrServer" class="com.sillycat.easyhunter.plugin.solr.SolrServerFactory">
<property name="solrServerClassName" value="org.apache.solr.client.solrj.embedded.EmbeddedSolrServer"/>
<property name="solrHome" value="D:\\book\\solr\\apache-solr-3.6.0\\example\\solr" />
</bean>

The test case can be as follow:
package com.sillycat.easyhunter.plugin.solr;

import junit.framework.Assert;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.SolrParams;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/test/resources/test-context.xml" })
public class SolrServerFactoryTest {

@Autowired
@Qualifier("httpSolrServer")
private SolrServer httpSolrServer;

@Autowired
@Qualifier("embeddedSolrServer")
private SolrServer embeddedSolrServer;

@Test
public void dumy() {
Assert.assertTrue(true);
}

@Test
public void embeddedSolrServerQuery() {
String query = "name:DDR";
SolrParams params = new SolrQuery(query);

try {
QueryResponse response = embeddedSolrServer.query(params);

SolrDocumentList list = response.getResults();
for (int i = 0; i < list.size(); i++) {
Assert.assertNotNull(list.get(i));
}
} catch (SolrServerException e) {
e.printStackTrace();
}
}

//@Test
public void httpSolrServerQuery() {
String query = "name:DDR";
SolrParams params = new SolrQuery(query);

try {
QueryResponse response = httpSolrServer.query(params);

SolrDocumentList list = response.getResults();
for (int i = 0; i < list.size(); i++) {
Assert.assertNotNull(list.get(i));
}
} catch (SolrServerException e) {
e.printStackTrace();
}
}
}


references:
http://www.blogjava.net/hoojo/archive/2011/10/21/361747.html

http://wiki.apache.org/solr/Solrj
http://groovy.codehaus.org/Grape
http://www.java2s.com/Code/Java/Spring/MessageDigestExample.htm
http://stackoverflow.com/questions/234600/can-i-use-class-newinstance-with-constructor-arguments


标签:solrj,Spring,integration,server,import,apache,org,solr,public
From: https://blog.51cto.com/u_16087105/6233566

相关文章

  • 使用Solrj管理Solr索引
    Solrj是Solr搜索服务器的一个比较基础的客户端工具,可以非常方便地与Solr搜索服务器进行交互,最基本的功能就是管理Solr索引,包括添加、更新、删除和查询等。对于一些比较基础的应用,用Solj基本够用,而且你可以非常容易地通过使用Solrj的API实现与Solr搜索服务器进行交互,实现对Solr的基......
  • Spring Boot Profile使用
    SpringBoot使用@Profile注解可以实现不同环境下配置参数的切换,任何@Component或@Configuration注解的类都可以使用@Profile注解。例如:@Configuration@Profile("production")publicclassProductionConfiguration{//...} 通常,一个项目中可能会有多个profile场景,例如下......
  • 通过在classpath自动扫描方式把组件纳入spring容器中管理
    知识点:【前面的例子我们都是使用XML的bean定义来配置组件。在一个稍大的项目中,通常会有上百个组件,如果这些这组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找及维护起来也不太方便。spring2.5为我们引入了组件自动扫描机制,他可以在类路径底......
  • 使用Spring进行面向切面(AOP)编程
    基础知识:【要进行AOP编程,首先我们要在spring的配置文件中引入aop命名空间:<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework......
  • 文件上传下载-SpringMvc
    进行文件上传时,表单需要做的准备:1.请求方式为POST:<formaction=”uploadServlet”method=”post”/>2.使用file的表单域:<inputtype=”file”name=”file”/>3.使用multipart/form-data的请求编码方式:<formaction=”uploadServlet”type=”file”name=”file”metho......
  • spring boot jpa MYSQL教程mysql连接的空闲时间超过8小时后 MySQL自动断开该连接
     SunApr1608:15:36CST2023Therewasanunexpectederror(type=InternalServerError,status=500).PreparedStatementCallback;SQL[selectuserIdfromfamilyxiao_UserConnectionwhereproviderId=?andproviderUserId=?];Nooperationsallowedaftercon......
  • Spring17_配置文件知识要点5
    <bean>标签id属性:在容器中Bean实例的唯一标识,不允许重复class属性:要实例化的Bean的全限定名scope属性:Bean的作用范围,常用是Singleton(默认)和prototype<property>标签:属性注入,set方法注入使用name属性:属性名称va......
  • SpringCloud微服务架构分析说明!
    SpringCloud是一个基于SpringBoot的微服务框架,它提供了一系列的工具和组件,用于构建分布式系统中各个微服务之间的通信和互联,实现服务发现、负载均衡、分布式配置等功能。下面我们来具体解析一下SpringCloud微服务架构。服务注册与发现在微服务架构中,服务的数量非常多,因此需要一个机......
  • Spring17_配置文件依赖注入4
    一、Bean的依赖注入入门1.创建UserService,UserService内部再调用UserDao的save()方法 2.将UserServiceImpl的创建权交给Spring3.从Spring容器中获得UserService进行操作执行UserController中的main方法,检查控制台输出:二、Bean的依赖......
  • springboot分页插件的问题
    1:maven依赖的问题此类原因是与pom.xml文件中引入的分页依赖有关,由于springboot本身集成pagerhelper的分页插件,只需要引入如下依赖即可<!--spring-bootmybatispagehelper--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-st......