整合完DB层,cache层,开始整合solr。
注入SolrClient,
package hello.configuration; import java.net.MalformedURLException; import javax.annotation.Resource; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.LBHttpSolrClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.solr.repository.config.EnableSolrRepositories; @Configuration
@EnableSolrRepositories(multicoreSupport = true)
@PropertySource(value = "classpath:/solr.properties")
public class SolrConfiguration { private static final String SOLR_HOST = "solr.host"; @Resource
private Environment environment; @Bean
public SolrClient solrServer() throws MalformedURLException {
String solrHost = environment.getRequiredProperty(SOLR_HOST);
return new LBHttpSolrClient(solrHost);
}
}
solr.properties配置文件
solr.host=http://localhost:7574/solr/gettingstarted_shard1_replica1
solr测试类
package hello.test; import java.io.IOException; import javax.annotation.PostConstruct;
import javax.annotation.Resource; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Component; @Component
public class SolrBean { @Resource
private SolrClient solrClient; // @Resource
// private SolrProductRepository solrProductRepository; public void run() throws SolrServerException, IOException {
// Iterable<Product> productList = solrProductRepository.findAll();
// while (productList.iterator().hasNext()) {
// Product product = (Product) productList.iterator().next();
// System.out.println("solr获取值:" + product.getId());
// }
} @PostConstruct
public void run2() throws SolrServerException, IOException {
SolrQuery query = new SolrQuery();// 查询
query.setQuery("id:123");
QueryResponse response = solrClient.query(query);
SolrDocumentList solrDocumentList = response.getResults();
for (SolrDocument sd : solrDocumentList) {
System.out.println("solr获取值:" + sd.getFieldValue("id"));
System.out.println("solr获取值:" + sd.getFieldValue("title"));
}
}
}