HttpSolrServer-采用静态工厂方法,创建HttpSolrServer单实例

  HttpSolrServer线程安全,如果使用下面构造器,必须对所有的请求重用相同的实例.如果实例在运行中创建的,
它可能会导致连接泄漏.推荐的做法就是保持每个solr服务url的HttpSolrServer的静态实例,所有的请求都共享这个实例.
参考https://issues.apache.org/jira/browse/SOLR-861查看更多细节.
1.创建配置文件solr-config.properties:

cores=ac,jd

base_url=http://127.0.0.a:13131/solr

 2.创建配置对象ConfigUtil.java 读取properties文件中的配置:

package com.li.util;

import java.util.ResourceBundle;


public class ConfigUtil {
    private static ResourceBundle  resouceBundle = ResourceBundle.getBundle(Config.SEARCH);
    public static String getString(String key){
        return resouceBundle.getString(key);
    }
}

3.配置属性对象类Config.java:

package com.li.util;

public class Config {
    
    //common
    public static final String COMMA = ",";
    public static final String UNDERLINE = "_";
    public static final String SINGE_BLANK =" ";
    public static final String SLASH ="/";
    public static final String COLON =":";
        
    
    public static final String BASE_URL = "base_url";
    public static final String CORES = "cores";
    
    
    //配置文件
    public static final String SEARCH = "solr-config";
    
}

4.静态工厂方法SolrServerFactory.java:

package com.li.solrj;

import java.util.HashMap;
import java.util.Map;

import org.apache.solr.client.solrj.impl.HttpSolrServer;

import com.li.util.Config;
import com.li.util.ConfigUtil;

/**
 * 创建一个HttpSolrServer的静态工厂方法,
 * 用于创建多个集合的单例模式
 * @author Administrator
 *
 */
public class SolrServerFactory {
    
    public static Map<String,HttpSolrServer> servers ;
    
    static {
        servers = new HashMap<String,HttpSolrServer>();
        //静态加载所有的solrServer
        String[] cores = ConfigUtil.getString(Config.CORES).split(Config.COMMA);
        String base_url = ConfigUtil.getString(Config.BASE_URL);
        for(String core : cores){
            String url ;
            if(base_url.endsWith(Config.SLASH)){
                url = base_url + core;
            }else{
                url = base_url+Config.SLASH+core;
            }
            HttpSolrServer server = new HttpSolrServer(url);
            servers.put(core, server);
        }
    }
    public HttpSolrServer newInstance(String collection){
        if(servers.containsKey(collection))
            return servers.get(collection);
        String base_url = ConfigUtil.getString(Config.BASE_URL);
        if(base_url.endsWith(Config.SLASH))
            base_url = base_url+collection;
        else
            base_url = base_url + Config.SLASH + collection;
        return servers.put(collection, new HttpSolrServer(base_url));
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。