• springboot整合solr,solr设置登录用户密码连接


    简介:该文章会介绍solr整合springboot,操作api 使用两种方式,SolrClient,SolrTemplate 两种方式基本使用方法与对比。其实大家学习完后会发现SolrTemplate 通过代理工厂模式对SolrClient 逻辑封装一层,感兴趣的朋友可以往下点开看源码看看,这里不做详细点缀。

    首先需要安装solr 并且配置相应的账号密码

    可以参考前写的文章:

    Sorl环境搭建与mysql表导入数据
    solr配置账号权限登录

    目录结构介绍在这里插入图片描述

    目录介绍:

    annotation 注解目录
    bean bean对象
    controller 控制层
    fiter 拦截器
    resourcess 配置文件信息

    代码

    1. application.yml配置文件
    spring:
      data:
        solr:
          host: http://127.0.0.1:8983/solr
          user: zyy
          pwd: 123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. SolrApplication.java 启动程序
    package com.zyy.test;
    
    
    import com.zyy.test.filter.SolrAuthInterceptor;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.solr.client.solrj.impl.HttpSolrClient;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    
    import java.net.URI;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description TODO
     * @date 2022/7/18
     **/
    
    @SpringBootApplication
    public class SolrApplication {
        @Value("${spring.data.solr.user}")
        private String username;
        @Value("${spring.data.solr.pwd}")
        private String password;
        @Value("${spring.data.solr.host}")
        private String uri;
    
        public static void main(String[] args) {
            SpringApplication.run(SolrApplication.class, args);
        }
    
        /***
         * @apiNote 配置solr账号密码
         * @author zhaoyy
         * @date 2021-6-8 15:05
         * 拦截器 {@link SolrAuthInterceptor}
         * @return {@link HttpSolrClient }
         */
        @Bean
        public HttpSolrClient solrClient() {
            CredentialsProvider provider = new BasicCredentialsProvider();
            final URI uri = URI.create(this.uri);
            provider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                    new UsernamePasswordCredentials(username, password));
            HttpClientBuilder builder = HttpClientBuilder.create();
            // 指定拦截器,用于设置认证信息
            builder.addInterceptorFirst(new SolrAuthInterceptor());
            builder.setDefaultCredentialsProvider(provider);
            CloseableHttpClient httpClient = builder.build();
            return new HttpSolrClient.Builder(this.uri).withHttpClient(httpClient).build();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    1. SolrAuthInterceptor.java l拦截器
    package com.zyy.test.filter;
    
    import org.apache.http.HttpHost;
    import org.apache.http.HttpRequest;
    import org.apache.http.HttpRequestInterceptor;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.AuthState;
    import org.apache.http.auth.Credentials;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.client.protocol.HttpClientContext;
    import org.apache.http.impl.auth.BasicScheme;
    import org.apache.http.protocol.HttpContext;
    import org.apache.http.protocol.HttpCoreContext;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description TODO
     * @date 2022/8/22
     **/
    public class SolrAuthInterceptor implements HttpRequestInterceptor {
        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                CredentialsProvider provider =
                        (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost httpHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                AuthScope scope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
                Credentials credentials = provider.getCredentials(scope);
                authState.update(new BasicScheme(), credentials);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    1. control 控制层代码
      BaseController.java
    package com.zyy.test.controller;
    
    import com.zyy.test.annotation.FilterName;
    import com.zyy.test.bean.MarketRankDb;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.springframework.cglib.beans.BeanMap;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Sort;
    import org.springframework.data.solr.core.query.Criteria;
    import org.springframework.data.solr.core.query.SimpleQuery;
    
    import java.lang.reflect.Field;
    import java.util.*;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description 控制类基础封装对象
     * @date 2022/8/22
     **/
    public class BaseController {
    
        protected SimpleQuery buildParam(MarketRankDb bean) {
            SimpleQuery query = new SimpleQuery("*:*");
            Map<String, Object> map = BeanMap.create(bean);
            Field[] file = bean.getClass().getDeclaredFields();
            for (Field field : file) {
                String key = field.getName();
                FilterName filterName = field.getAnnotation(FilterName.class);
                if (Objects.nonNull(filterName)) {
                    continue;
                }
                if (StringUtils.isNotBlank(key) && Objects.nonNull(map.get(key))) {
                    query.addCriteria(new Criteria(key).contains(map.get(key).toString()));
                }
            }
    
            if (map.containsKey("pageSize") && Optional.ofNullable(map.get("pageSize")).isPresent() &&
                    map.containsKey("pageNo") && Optional.ofNullable(map.get("pageNo")).isPresent()) {
                PageRequest pageRequest = PageRequest.of(bean.getPageNo() - 1, bean.getPageSize());
                query.setPageRequest(pageRequest);
            }
            query.addSort(Sort.by(Sort.Direction.ASC, "id"));
            return query;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    ControllerTest.java

    package com.zyy.test.controller;
    
    import com.zyy.test.bean.Area;
    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.apache.solr.common.SolrInputDocument;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    import java.io.IOException;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description SolrClient api 操作solr
     * @date 2022/8/15
     **/
    @RestController
    @RequestMapping("test")
    public class ControllerTest {
        @Resource
        private SolrClient solrClient;
    
        @PostMapping("add")
        public void add(Area area) {
            SolrInputDocument document = new SolrInputDocument();
            document.setField("id", area.getId());
            document.setField("name", area.getName());
            try {
                solrClient.add(document);
                solrClient.commit();
            } catch (SolrServerException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @GetMapping("delete")
        public void delete(String query) {
            try {
                solrClient.deleteByQuery(query);
                solrClient.commit();
            } catch (SolrServerException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @PostMapping("update")
        public Area update(Area book) {
            try {
                solrClient.addBean(book);
                solrClient.commit();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SolrServerException e) {
                e.printStackTrace();
            }
            return book;
        }
    
        @GetMapping("get")
        public Area get(String id) {
            try {
                SolrDocument solrDocument = solrClient.getById(id);
                solrClient.commit();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SolrServerException e) {
                e.printStackTrace();
            }
            return new Area();
        }
    
        @GetMapping("getAll")
        public void queryDocument() throws IOException, SolrServerException {
            SolrQuery query = new SolrQuery();
            //查询条件,默认所有查询
            query.setQuery("*:*");
            //查询结果的封装对象
            QueryResponse queryResponse = solrClient.query(query);
            //查询结果
            SolrDocumentList results = queryResponse.getResults();
            //查询到的数量
            long numFound = results.getNumFound();
            System.out.println(numFound);
            for (SolrDocument result : results) {
                System.out.println("id=>" + result.get("id") + "name=>" + result.get("name"));
            }
        }
    
        @GetMapping("one")
        public String one() {
            return "hello world!";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106

    SolrTemplateControllerTest.java

    package com.zyy.test.controller;
    
    import com.zyy.test.bean.CollectionNameEnum;
    import com.zyy.test.bean.SearchCorpCard;
    import org.apache.solr.client.solrj.*;
    import org.apache.solr.client.solrj.request.UpdateRequest;
    import org.apache.solr.client.solrj.response.QueryResponse;
    import org.apache.solr.client.solrj.response.UpdateResponse;
    import org.springframework.data.solr.core.SolrTemplate;
    import org.springframework.data.solr.core.query.Criteria;
    import org.springframework.data.solr.core.query.SimpleQuery;
    import org.springframework.data.solr.core.query.result.ScoredPage;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    import java.io.IOException;
    import java.util.List;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description SolrClient与SolrTemplate 基本api 使用语法,结论推荐使用SolrTemplate
     * @date 2022/8/15
     **/
    @RestController
    @RequestMapping("solr")
    public class SolrTemplateControllerTest {
        @Resource
        private SolrClient solrClient;
    
        /**
         * SolrTemplate 其实底部也是通过工厂模式封装了一层 SolrClient 对象
         */
        @Resource
        private SolrTemplate solrTemplate;
    
    
        @GetMapping("getName")
        public List<SearchCorpCard> getName(String name) {
            //设置参数
            SimpleQuery query = new SimpleQuery("*:*").
                    addCriteria(new Criteria("corpName").contains(name));
            //起始页
            query.setRows(1);
            //查询起始页 (pageNo-1)* pageSize
            query.setOffset(10L);
            ScoredPage<SearchCorpCard> tbItems = solrTemplate.queryForPage(CollectionNameEnum.TB_SEARCH_CORP_CARD.getCode(), query, SearchCorpCard.class);
    
            tbItems.forEach(x -> System.out.println(x.toString()));
            return tbItems.getContent();
        }
    
        @GetMapping("getName1")
        public List<SearchCorpCard> getName1(String name) throws SolrServerException, IOException {
            SolrQuery query = new SolrQuery();
            //查询条件,默认所有查询
            query.setQuery("*:*");
            QueryResponse queryResponse = solrClient.query(CollectionNameEnum.TB_SEARCH_CORP_CARD.getCode(), query);
            /**
             * 注意使用queryResponse.getBeans 对象转换时需要用注解  @Field 代码底层是通过@Field 标记元素换换,
             * 而上面是通过mappering文件类名称映射的
             *
             */
            List<SearchCorpCard> list = queryResponse.getBeans(SearchCorpCard.class);
            list.forEach(x -> System.out.println(x.toString()));
            solrClient.commit(CollectionNameEnum.TB_SEARCH_CORP_CARD.getCode());
            return list;
        }
    
        /**
         * 新增 solrTemplate 添加对象
         *
         * @param bean
         * @throws SolrServerException
         * @throws IOException
         */
        @PostMapping("add")
        public void add(@RequestBody SearchCorpCard bean) throws SolrServerException, IOException {
            UpdateResponse queryResponse = solrTemplate.saveBean(CollectionNameEnum.TB_SEARCH_CORP_CARD.getCode(), bean);
            solrTemplate.commit(CollectionNameEnum.TB_SEARCH_CORP_CARD.getCode());
        }
    
        /**
         * 新增 solrClient 添加对象
         *
         * @param bean
         * @throws SolrServerException
         * @throws IOException
         */
        @PostMapping("add1")
        public void add1(@RequestBody SearchCorpCard bean) throws SolrServerException, IOException {
            solrClient.addBean(CollectionNameEnum.TB_SEARCH_CORP_CARD.getCode(), bean);
            solrClient.commit(CollectionNameEnum.TB_SEARCH_CORP_CARD.getCode());
        }
    
        /**
         * 测试接口
         *
         * @return
         */
        @GetMapping("one")
        public String one() {
            return "hello world!";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106

    SolrTestController.java

    package com.zyy.test.controller;
    
    import com.zyy.test.bean.CollectionNameEnum;
    import com.zyy.test.bean.MarketRankDb;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.solr.client.solrj.response.UpdateResponse;
    import org.assertj.core.util.Lists;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.solr.core.SolrTemplate;
    import org.springframework.data.solr.core.query.result.ScoredPage;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description SolrTemplate api 操作solr
     * @date 2022/8/22
     **/
    @Slf4j
    @RestController
    @RequestMapping("/test/solr")
    public class SolrTestController extends BaseController {
    
        @Autowired
        private SolrTemplate solrTemplate;
    
        /**
         * 根据参数条件查询列表数据
         *
         * @param marketRank
         * @return
         */
        @PostMapping("getList")
        private List<MarketRankDb> getList(@RequestBody MarketRankDb marketRank) {
            Page<MarketRankDb> page = solrTemplate.query(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode(), buildParam(marketRank), MarketRankDb.class);
            return page.getContent();
        }
    
    
        /**
         * 分页查询
         *
         * @param marketRank
         * @return
         */
        @PostMapping("getPageList")
        private List<MarketRankDb> getPageList(@RequestBody MarketRankDb marketRank) {
            ScoredPage<MarketRankDb> data = solrTemplate.queryForPage(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode(), buildParam(marketRank), MarketRankDb.class);
            log.info("分页返回数据data={}", data);
            return data.getContent();
        }
    
        /**
         * 添加一条记录
         *
         * @param marketRank
         */
        @PostMapping("add")
        private void add(@RequestBody MarketRankDb marketRank) {
            UpdateResponse response = solrTemplate.saveBeans(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode(), Lists.newArrayList(marketRank));
            log.info("修改结果result ={}", response);
            solrTemplate.commit(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode());
        }
    
        /**
         * 更新数据
         *
         * @param marketRank
         */
        @PostMapping("update")
        private void update(@RequestBody MarketRankDb marketRank) {
            solrTemplate.saveBean(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode(), buildParam(marketRank));
            solrTemplate.commit(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode());
        }
    
    
        /**
         * 根据参数条件删除对应数据
         *
         * @param marketRank
         */
        @GetMapping("delete")
        private void delete(@RequestBody MarketRankDb marketRank) {
            solrTemplate.delete(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode(), buildParam(marketRank));
            solrTemplate.commit(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode());
        }
    
        /**
         * 根据ids 多个删除
         *
         * @param ids
         */
        @GetMapping("deletes")
        private void delete(@RequestBody List<String> ids) {
            solrTemplate.deleteByIds(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode(), ids);
            solrTemplate.commit(CollectionNameEnum.TB_MOBILE_MARKET_RANK.getCode());
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    1. bean对象
      SearchCorpCard.java
    package com.zyy.test.bean;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.ToString;
    import org.apache.solr.client.solrj.beans.Field;
    
    import java.io.Serializable;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description TODO
     * @date 2022/8/16
     **/
    @Data
    @AllArgsConstructor
    @ToString
    @NoArgsConstructor
    public class SearchCorpCard implements Serializable {
    
        @Field
        private String corpId;
        @Field
        private String corpName;
        @Field
        private String registNo;
        @Field
        private String creditCode;
        @Field
        private String registfund;
        @Field
        private String registAddess;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    MarketRankDb.java

    package com.zyy.test.bean;
    
    import com.zyy.test.annotation.FilterName;
    import lombok.Data;
    import org.apache.solr.client.solrj.beans.Field;
    
    import java.io.Serializable;
    
    /**
     * 功能:app市场榜单排名DB实体类
     *
     * @author zhaoyy
     * @date 2022-01-13 11:14
     */
    @Data
    public class MarketRankDb implements Serializable {
        @FilterName
        private static final long serialVersionUID = -4000524883785970259L;
    
        @Field
        private Long id;
        @Field
        private String market;
        @Field
        private String listType;
        @Field
        private String subType;
        @Field
        private String trackId;
        @Field
        private String trackName;
        @Field
        private String description;
        @Field
        private String downloads;
        @Field
        private String downloadUrl;
        @Field
        private String appUpdateTime;
        @Field
        private String versionCode;
        @Field
        private String versionDate;
        @Field
        private String versionName;
        @Field
        private String fileSize;
        @Field
        private String packageName;
        @Field
        private String sellerName;
        @Field
        private Integer status;
        @Field
        private String artworkUrl;
        @Field
        private String yesterdayDownload;
        @Field
        private String yesterdayComment;
        @Field
        private String rankChange;
        @Field
        private Integer rank;
        @Field
        @FilterName
        private Integer pageSize;
        @Field
        @FilterName
        private Integer pageNo;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    CollectionNameEnum.java

    package com.zyy.test.bean;
    
    /**
     * solr 集合名称
     *
     * @author zhaoyy
     */
    public enum CollectionNameEnum {
        Test("zyy_test", "测试集合"),
        TB_SEARCH_CORP_CARD("tb_search_corp_card", "企业搜索集合"),
        TB_MOBILE_MARKET_RANK("tb_mobile_market_rank", "手机应用市场app范围排行榜"),
        ;
    
        private String code;
        private String desc;
    
        CollectionNameEnum(String code, String desc) {
            this.code = code;
            this.desc = desc;
        }
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public void setDesc(String desc) {
            this.desc = desc;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    Area.java

    package com.zyy.test.bean;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.ToString;
    import org.apache.solr.client.solrj.beans.Field;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.solr.core.mapping.SolrDocument;
    
    /**
     * @author zhaoyy
     * @version 1.0
     * @description TODO
     * @date 2022/8/15
     **/
    @Data
    @AllArgsConstructor
    @ToString
    @NoArgsConstructor
    @SolrDocument(collection = "zyy_test")
    public class Area {
        @Field
        private Integer code;
        @Field
        private Integer cityCode;
        @Field
        private Integer provinceCode;
    
        @Field
        private String name;
    
        @Id
        @Field
        private Integer id;
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    1. annotation 过滤器
    package com.zyy.test.annotation;
    
    
    import java.lang.annotation.*;
    
    /**
     * 过滤字段参与where查询
     *
     * @author zhaoyy
     */
    @Documented
    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface FilterName {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    1. pom.xml maven 配置文件
    
    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <groupId>com.zyy.solrgroupId>
        <version>1.0-SNAPSHOTversion>
        <artifactId>solr-springbootartifactId>
    
        <description>
            1、solr整合使用:分词搜索等使用
        description>
    
        <properties>
            <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
            <maven.compiler.source>1.8maven.compiler.source>
            <maven.compiler.target>1.8maven.compiler.target>
            <spring-boot.version>2.3.1.RELEASEspring-boot.version>
            <drools.version>7.47.0.Finaldrools.version>
        properties>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-dependenciesartifactId>
                    <version>${spring-boot.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
            dependencies>
        dependencyManagement>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.bootgroupId>
                        <artifactId>spring-boot-starter-loggingartifactId>
                    exclusion>
                exclusions>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-log4j2artifactId>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <exclusions>
                    
                    <exclusion>
                        <groupId>junitgroupId>
                        <artifactId>junitartifactId>
                    exclusion>
                    <exclusion>
                        <groupId>org.junit.vintagegroupId>
                        <artifactId>junit-vintage-engineartifactId>
                    exclusion>
                exclusions>
            dependency>
    
            <dependency>
                <groupId>org.kiegroupId>
                <artifactId>kie-springartifactId>
                <version>${drools.version}version>
                <exclusions>
                    
                    <exclusion>
                        <groupId>org.springframeworkgroupId>
                        <artifactId>spring-txartifactId>
                    exclusion>
                    <exclusion>
                        <groupId>org.springframeworkgroupId>
                        <artifactId>spring-beansartifactId>
                    exclusion>
                    <exclusion>
                        <groupId>org.springframeworkgroupId>
                        <artifactId>spring-coreartifactId>
                    exclusion>
                    <exclusion>
                        <groupId>org.springframeworkgroupId>
                        <artifactId>spring-contextartifactId>
                    exclusion>
                exclusions>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-autoconfigureartifactId>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.22version>
            dependency>
            
            <dependency>
                <groupId>com.github.magesegroupId>
                <artifactId>ik-analyzerartifactId>
                <version>8.5.0version>
            dependency>
            
           
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-solrartifactId>
                <version>2.4.11version>
            dependency>
        dependencies>
    project>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123

    创建对应solr 实例

    创建命令:solr create -c “zyy-test” 名称需要与CollectionNameEnum code 值对应

    表结构:

    CREATE TABLE `tb_mobile_market_rank_test` (
      `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
      `market` varchar(30) DEFAULT NULL COMMENT '市场平台',
      `list_type` varchar(30) DEFAULT NULL COMMENT '榜单分类',
      `sub_type` varchar(30) DEFAULT '' COMMENT '子分类',
      `trackid` varchar(50) DEFAULT NULL COMMENT 'app标识ID',
      `track_name` varchar(255) DEFAULT NULL COMMENT 'app名称',
      `description` text COMMENT '描述',
      `downloads` varchar(50) DEFAULT NULL COMMENT '下载量',
      `download_url` varchar(1024) DEFAULT NULL COMMENT '下载链接',
      `app_update_time` varchar(30) DEFAULT NULL COMMENT '更新时间',
      `version_code` varchar(50) DEFAULT NULL COMMENT '版本编码',
      `version_date` varchar(30) DEFAULT NULL COMMENT '最近版本更新时间',
      `version_name` varchar(50) DEFAULT NULL COMMENT '版本',
      `file_size` varchar(50) DEFAULT NULL COMMENT '文件大小',
      `package_name` varchar(255) DEFAULT NULL COMMENT '捆绑包ID(包名)',
      `seller_name` varchar(500) DEFAULT NULL COMMENT '开发者',
      `status` int(2) DEFAULT NULL COMMENT '状态',
      `artwork_url` varchar(500) DEFAULT NULL COMMENT 'app-icon图标链接',
      `yesterday_download` varchar(50) DEFAULT NULL COMMENT '昨日下载量',
      `yesterday_comment` varchar(50) DEFAULT NULL COMMENT '昨日评论量',
      `rank_change` varchar(255) DEFAULT NULL COMMENT '排名变动情况',
      `rank` int(5) DEFAULT NULL COMMENT '排名',
      `CREATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `CREATE_USER` varchar(30) DEFAULT NULL COMMENT '创建人',
      `MODIFY_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
      `MODIFY_USER` varchar(30) DEFAULT NULL COMMENT '修改人',
      PRIMARY KEY (`ID`) USING BTREE,
      KEY `idx_tb_market_rank_market` (`market`) USING BTREE,
      KEY `idx_tb_market_rank_list_type` (`list_type`) USING BTREE,
      KEY `idx_tb_market_rank_sub_type` (`sub_type`) USING BTREE,
      KEY `idx_market_rank_create_time` (`CREATE_TIME`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=3065090 DEFAULT CHARSET=utf8mb4 COMMENT='app市场榜单排名表';
    
    CREATE TABLE `tb_xzqh_areas` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `code` varchar(6) DEFAULT NULL,
      `name` varchar(100) DEFAULT NULL,
      `cityCode` varchar(6) DEFAULT NULL,
      `provinceCode` varchar(6) DEFAULT NULL,
      `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `udx_areas_code` (`code`)
    ) ENGINE=InnoDB AUTO_INCREMENT=10886 DEFAULT CHARSET=utf8 COMMENT='县级(区县)';
    
    CREATE TABLE `tb_search_corp_card` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `code` varchar(6) DEFAULT NULL,
      `name` varchar(100) DEFAULT NULL,
      `cityCode` varchar(6) DEFAULT NULL,
      `provinceCode` varchar(6) DEFAULT NULL,
      `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `udx_areas_code` (`code`)
    ) ENGINE=InnoDB AUTO_INCREMENT=10886 DEFAULT CHARSET=utf8 COMMENT='县级(区县)';
    
    CREATE TABLE `tb_search_corp_card` (
      `ID` bigint(20) NOT NULL,
      `CORPID` bigint(20) DEFAULT NULL,
      `CORPNAME` varchar(200) NOT NULL,
      `REGISTNO` varchar(50) DEFAULT NULL,
      `CREDITCODE` varchar(18) DEFAULT NULL,
      `REGISTFUND` float(18,6) DEFAULT NULL,
      `REGISTADDRESS` varchar(600) DEFAULT NULL
      PRIMARY KEY (`ID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    文章笔记

    1 异常

    ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.solr.UncategorizedSolrException: IOException occurred when talking to server at: http://127.0.0.1:8983/solr; nested exception is org.apache.solr.client.solrj.SolrServerException: IOException occurred when talking to server at: http://127.0.0.1:8983/solr] with root cause
    org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.
    
    • 1
    • 2

    上面做了这么多,做下解释说明:

    1.在整合过程中发现如果不需要对solr 进行增,删,改操作,当solr 设置了账号可以直接使用http://zyy:123456@127.0.0.1:8983/solr 连接solr,
    可以去掉application bean注入与拦截器SolrAuthInterceptor

    2.如果设置了账号密码对solr 进行增,删,改操作,应该加上 1上面提得到的方法类,否则会抛出异常1

  • 相关阅读:
    论文投稿必看,审稿人意见互相矛盾,作者该怎么办?
    代码训练营第53天:动态规划part12|leetcode309买卖股票的最佳时期含冷静期|leetcode714买卖股票的最佳时机含手续费
    Jenkins的“Build Monitor View” 插件:助力监控所有Pipeline执行状态
    Netty基础概念
    【软件测试】性能测试工具Loadrunner
    【flask扩展】Flask-Migrate的使用
    《算法竞赛·快冲300题》每日一题:“取石子游戏”
    owt-server源码剖析(六)--集群分布及任务调度
    SAP MM ME27 创建公司内STO单
    文心一言 VS 讯飞星火 VS chatgpt (214)-- 算法导论16.2 1题
  • 原文地址:https://blog.csdn.net/weixin_43829047/article/details/126478885