正文
一、引入依赖配置pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.6.2</version> <exclusions> <exclusion> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> </exclusion> <exclusion> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.6.2</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.6.2</version> </dependency>
二、配置application-dev.yml(生产就克隆application-dev改成生产配置)
elasticsearch: host: 192.168.1.1:9200,192.1.2.133:9200,192.168.1.3:9200 cluster-name: laokou-elasticsearch username: password: synonym: path: http://192.168.1.1:9048/laokou-service/synonym
问题思考:比如说,一条文章记录,它有标题,内容,阅读量,在数据存入es时,我需要对es配置分词器,并且能够通过阅读量来筛选数据,你怎么做?
三、配置ES注解
注解可以修饰属性或方法(前提是先配置)
type > 需要在es配置什么类型
participle > 需要配置什么分词器
/** * @author Kou Shenhai */ @Target({ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface FieldInfo { /** * 默认 keyword * @return */ String type() default "keyword"; /** * 0 not_analyzed 1 ik_smart 2.ik_max_word 3.ik-index(自定义分词器) * @return */ int participle() default 0; }
拼接属性对应的类型及分词器
/** * 属性、类型、分词器 * @author Kou Shenhai 2413176044@leimingtech.com * @version 1.0 * @date 2021/2/9 0009 上午 10:20 */ @Data @NoArgsConstructor public class FieldMapping { private String field; private String type; private Integer participle; public FieldMapping(String field, String type, Integer participle) { this.field = field; this.type = type; this.participle = participle; } }
组装每个属性对应的类型及分词器 => List
/** * 每个属性对应的类型及分词器 * @author Kou Shenhai 2413176044@leimingtech.com * @version 1.0 * @date 2021/1/24 0024 下午 7:51 */ @Slf4j public class FieldMappingUtil { public static List<FieldMapping> getFieldInfo(Class clazz) { return getFieldInfo(clazz, null); } public static List<FieldMapping> getFieldInfo(Class clazz, String fieldName) { //返回class中的所有字段(包括私有字段) Field[] fields = clazz.getDeclaredFields(); //创建FieldMapping集合 List<FieldMapping> fieldMappingList = new ArrayList<>(); for (Field field : fields) { //获取字段上的FieldInfo对象 boolean annotationPresent = field.isAnnotationPresent(FieldInfo.class); if (annotationPresent) { FieldInfo fieldInfo = field.getAnnotation(FieldInfo.class); //获取字段名称 String name = field.getName(); fieldMappingList.add(new FieldMapping(name, fieldInfo.type(), fieldInfo.participle())); } else { continue; } } return fieldMappingList; } }
四、配置es及swagger
/** * es配置文件 * @author Kou Shenhai 2413176044@leimingtech.com * @version 1.0 * @date 2020/8/9 0009 下午 2:01 */ @Configuration public class ElasticsearchConfig { private static final String HTTP_SCHEME = "http"; private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchConfig.class); /** * 权限验证 */ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); /** * es主机 */ @Value("${elasticsearch.host}") private String[] host; @Value("${elasticsearch.username}") private String username; @Value("${elasticsearch.password}") private String password; @Bean public RestClientBuilder restClientBuilder() { HttpHost[] hosts = Arrays.stream(host) .map(this::makeHttpHost) .filter(Objects::nonNull) .toArray(HttpHost[]::new); LOGGER.info("host:{}",Arrays.toString(hosts)); //配置权限验证 credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); return RestClient.builder(hosts).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider) .setMaxConnPerRoute(100) //最大连接数 .setMaxConnTotal(100) ).setRequestConfigCallback(builder -> { builder.setConnectTimeout(-1); builder.setSocketTimeout(60000); builder.setConnectionRequestTimeout(-1); return builder; }); } /** * 处理请求地址 * @param address * @return */ private HttpHost makeHttpHost(String address) { assert StringUtils.isNotEmpty(address); String[] hostAddress = address.split(":"); if (hostAddress.length == 2) { String ip = hostAddress[0]; Integer port = Integer.valueOf(hostAddress[1]); return new HttpHost(ip, port, HTTP_SCHEME); } else { return null; } } /** * 配置highLevelClient bean * @param restClientBuilder * @return */ @Bean(name = "restHighLevelClient") public RestHighLevelClient restHighLevelClient(@Autowired RestClientBuilder restClientBuilder) { return new RestHighLevelClient(restClientBuilder); } }
/** * @author Kou Shenhai */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .version("2.0.0") .description("API文档 - Elasticsearch服务") //作者信息 .contact(new Contact("寇申海", "https://blog.csdn.net/qq_39893313", "2413176044@qq.com")) .build(); } }