封装一个简单的solrserver组件

2019-03-27 01:05|来源: 网路

一个简单的solrserver组件

              实现索引更新的异步处理,以及查询接口,日志/线程池/队列监控没有加上。

SolrDocment封装

          接口:

          

public interface ISolrDocument {

    public SolrInputDocument convertToInputDocument()  throws Exception;

    public void buildSolrDocument(SolrDocument document) throws Exception;

}

         实现:

public class SolrDocumentImpl implements ISolrDocument {
    @Override
    public SolrInputDocument convertToInputDocument() throws Exception{
        final SolrInputDocument doc = new SolrInputDocument();

        Field[] fields = this.getClass().getDeclaredFields();
        for (Field f : fields) {
                f.setAccessible(true);
                String idxName = f.getName();
                Object fieldValue =f.get(this);
                doc.addField(idxName, fieldValue);
        }
        return doc;
    }

    @Override
    public void buildSolrDocument(SolrDocument document) throws Exception{
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field f : fields) {
                f.setAccessible(true);

                String idxName = f.getName();

                Object fieldValue = document.get(idxName);
                f.set(this, fieldValue);

        }
    }

查询结构集封装

public class DataResult<T> {
    private int start;
    private int limits;
    private long totalRecord;
    private List<T> records;

    public int getLimits() {
        return limits;
    }

    public void setLimits(int limits) {
        this.limits = limits;
    }

    public long getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(long totalRecord) {
        this.totalRecord = totalRecord;
    }

    public List<T> getRecords() {
        return records;
    }

    public void setRecords(List<T> records) {
        this.records = records;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }
}

 

SolrServer封装

           接口:

public interface ISolrServer {

    public ThreadPoolExecutor getThreadPool();


    void init() throws Exception;

    /**
     * 索引优化
     */
    void optimize();

    /**
     * 清理索引
     * @param query
     */
    void clearDocs(SolrQuery query);

    /**
     * 批量更新索引
     *
     * @param docs
     */
    void batchUpdateDocs(List<ISolrDocument> docs);


    /**
     * 分页查询
     *
     * @param clazz
     * @param query
     * @return
     */
    public <T extends ISolrDocument> DataResult<T> pageSearch(SolrQuery query, Class<T> clazz);


    void destory() throws Exception;
}

           实现:

public class SolrServerImpl implements ISolrServer {

    private  CloudSolrServer solrServer;
    private String zookeeperStr;
    private String coreName;
    private String idName;
    private int corePoolSize;
    private int maxPoolSize;
    private int threadQueueSize;
    private ThreadPoolExecutor threadPool;
    @Override
    public void init() throws Exception {
        this.threadPool
                = new ThreadPoolExecutor(corePoolSize,
                maxPoolSize,
                10000,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(threadQueueSize),
                new SolrThreadFactory("solr-pool"),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        solrServer=new CloudSolrServer(this.zookeeperStr);
        solrServer.setDefaultCollection(coreName);
        solrServer.setIdField(idName);
        solrServer.setZkClientTimeout(10000);
        solrServer.setZkConnectTimeout(5000);
    }

    @Override
    public void optimize() {


    }

    @Override
    public void clearDocs(final SolrQuery query) {
        this.threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    SolrServerImpl.this.solrServer.deleteByQuery(query.getQuery());
                    SolrServerImpl.this.solrServer.commit(false, false, true);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void batchUpdateDocs(List<ISolrDocument> docs) {
        try {
            List<SolrInputDocument> inputDocs=new ArrayList<SolrInputDocument>();
            for(ISolrDocument doc:docs){
                inputDocs.add(doc.convertToInputDocument());
            }
            this.solrServer.add(inputDocs);
            this.solrServer.commit(false,false,true);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public <T extends ISolrDocument> DataResult<T> pageSearch(SolrQuery query, Class<T> clazz) {
        int limit=query.getRows()==0?20:query.getRows();
        int start=query.getStart();
        List<T> dataResults=new ArrayList<T>(limit);
        DataResult datas=new DataResult();
        datas.setLimits(limit);
        datas.setStart(start);
        try{
            QueryResponse response= this.solrServer.query(query);
            SolrDocumentList solrDocumentList=response.getResults();
            datas.setTotalRecord(solrDocumentList.getNumFound());
            for (SolrDocument doc :solrDocumentList){
                T iSolrDocument=clazz.newInstance();
                iSolrDocument.buildSolrDocument(doc);
                dataResults.add(iSolrDocument);
            }
            datas.setRecords(dataResults);
        }catch (Exception e){
            e.printStackTrace();
        }

        return datas;
    }

    @Override
    public void destory() throws Exception {
        this.solrServer.shutdown();

    }

    public void setIdName(String idName) {
        this.idName = idName;
    }

    public void setCoreName(String coreName) {
        this.coreName = coreName;
    }

    public void setZookeeperStr(String zookeeperStr) {
        this.zookeeperStr = zookeeperStr;
    }

    public CloudSolrServer getSolrServer() {
        return solrServer;
    }

    public void setSolrServer(CloudSolrServer solrServer) {
        this.solrServer = solrServer;
    }

    public String getZookeeperStr() {
        return zookeeperStr;
    }

    public String getCoreName() {
        return coreName;
    }

    public String getIdName() {
        return idName;
    }

    public int getCorePoolSize() {
        return corePoolSize;
    }

    public void setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getThreadQueueSize() {
        return threadQueueSize;
    }

    public void setThreadQueueSize(int threadQueueSize) {
        this.threadQueueSize = threadQueueSize;
    }

    public ThreadPoolExecutor getThreadPool() {
        return threadPool;
    }

    public void setThreadPool(ThreadPoolExecutor threadPool) {
        this.threadPool = threadPool;
    }
}

  任务处理封装

public class BatchTaskExecutor{

    private ISolrServer iSolrServer;

    private int batchSize = 100;

    private int queueLength = 2000;


    private int workThreadSize = 2;

    private Semaphore semaphore;

    private LinkedBlockingQueue<ISolrDocument> docQueue;

    public void init(){
        this.semaphore = new Semaphore(this.workThreadSize);
        docQueue = new LinkedBlockingQueue<ISolrDocument>(this.queueLength);
        while(true){
            this.iSolrServer.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    List<ISolrDocument> list=BatchTaskExecutor.this.batchPollDocs();
                    BatchTaskExecutor.this.acquire();
                    try {
                        BatchTaskExecutor.this.iSolrServer.batchUpdateDocs(list);
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        BatchTaskExecutor.this.release();
                    }
                }
            });
        }

    }

    public boolean acquire() {
        try {
            return this.semaphore.tryAcquire(1,10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void release() {
        this.semaphore.release();
    }

    public boolean offerDoc(ISolrDocument doc) {

        try {
            return this.docQueue.offer(doc, 1000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<ISolrDocument> batchPollDocs() {

        List<ISolrDocument> docs = new ArrayList<ISolrDocument>(this.batchSize);
        while (docs.size() < this.batchSize) {
            ISolrDocument doc = null;
            try {
                doc = this.docQueue.poll(1000, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
               e.printStackTrace();
            } finally {
                if (doc==null) {
                    break;
                } else {
                    docs.add(doc);
                }
            }

        }
        return docs;
    }
}

 


转自:http://www.cnblogs.com/requelqi/p/3754871

相关问答

更多
  • 勒问题用百度找
  • 实现对Solr的基本管理功能。 如果你的应用比较复杂,用Solj基本够用,可以非常方便地与Solr搜索服务器进行交互。 对于一些比较基础的应用,而且你可以非常容易地通过使用Solrj的API实现与Solr搜索服务器进行交互。最基本的功能就是管理Solr索引,包括添加、更新、删除和查询等Solrj是Solr搜索服务器的一个比较基础的客户端工具
  • 提供原生视图很简单: 创建一个ViewManager的子类(或者更常见的,SimpleViewManage的派生类)。 实现createViewInstance方法。 导出视图的属性设置器:使用@ReactProp(或@ReactPropGroup)注解。 把这个视图管理类注册到应用程序包的createViewManagers里。 实现JavaScript模块。 在开始之前,先创建一个工程,命令如下: React-native init NativeView 第一步. 创建ViewManager的子类MyT ...
  • 正如您所见,您无法在表单内呈现表单,因此您需要延迟对话框的呈现,直到表单呈现完毕。 因此,不使用组件内的对话框,而是使用环境bean。 环境将存储页面上所有对话框的配置 http://tapestry.apache.org/environmental-services.html 在每个页面的末尾添加一个块,从环境中查找配置并呈现所有对话框。 希望你使用的是布局,所以这将在一个地方。 例如:Layout.java @Inject Environment environment; @Property priv ...
  • 只需从您的自定义制作一个常规组件。 您需要为您的组件定义一个items道具作为组件的项目。 而且,要为您的组件定义slot ,您需要使用标签,并使用name属性指定name 。 如果您希望在 组件中访问组件中的某个 ,只需将标签作为自定义组件中插槽的内容即可。 它看起来像这样: Vue.component('my-b-table', { template: `
  • 您可以使用/deep/ combinator来克服封装: :host /deep/ ng-component { ... } 也可以看看 将外部css样式加载到Angular 2组件中 Angular 2:如何设置组件的主机元素? D3.js组件中的样式不以角度2显示 Angular2 - 将[_ngcontent-mav-x]添加到样式 update ::slotted is now supported by all new browsers and can be used with `ViewEn ...
  • 如果不使用ViewEncapsulation.None则无法更改primeng组件样式。 @Component元数据中指定的样式仅适用于该组件的模板。 嵌套在模板中的任何组件或投影到组件中的任何内容都不会继承它们。 您只能定位每个子组件的host元素。 您将无法定位组件内使用的任何内部元素。 风格范围 You cannot change the primeng component styles without using the ViewEncapsulation.None. The styles spec ...
  • 好吧,我发现有两种方法可以解决这个问题: 1)我们可以通过设置DF标志发送大数据包,告诉我们想要片段输出数据包。 但在这种情况下,数据包可能会丢失,因为并非所有设备/ etc都支持数据包碎片 2)我们可以自动计算主机之间的最大MTU,拆分它们并发送。 另一方面,我们将所有这些数据包放在一起并恢复它们。 这可以通过为此目的实现我们自己的“系统”来完成。 有关IP数据包碎片和重组的更多信息,请参阅此处 Well, I found that there actually 2 ways to handle that ...
  • MulticoreServerFactory总是返回HttpClient的对象,它只允许2个并发连接到同一主机,从而导致上述问题。 这似乎是spring-data-solr的一个错误,可以通过创建自定义工厂并覆盖一些方法来解决这个问题。 编辑:MultiCoreSolrServerFactory中的clone方法已损坏。 这还没有得到纠正。 由于我的一些同事最近遇到过这个问题,我将在这里发布一个解决方法 - 创建自己的类并覆盖一个方法。 public class CustomMulticoreSolrSer ...