Linux搭建ElasticSearch请参阅:https://blog.csdn.net/NewxCJY/article/details/105265169
继上次搭建好ElasticSearch后,本篇博文介绍springboot集成ElasticSearch,使用swagger2作为Api测试工具。
JDK版本:openJDK8
springboot版本:2.2.1
demo目录:
springboot集成es:
pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xinx</groupId>
<artifactId>es</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>es</name>
<description>Demo project for Spring Boot and ElasticSearch</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml文件:
server:
port: 9999
tomcat:
uri-encoding: UTF-8
spring:
data:
elasticsearch:
client:
reactive:
socket-timeout: 120s
endpoints: localhost:9200
swagger2:
defaultGroupName: "Xinx"
defaultBasePackage: "com.xinx.es.controller"
defaultTitle: "Api document"
defaultDescription: "......"
defaultTermsOfServiceUrl: "{host}/doc.html"
defaultVersion: "v1.0"
swagger配置:
package com.xinx.es.config;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfiguration {
@Autowired
private SwaggerConfigProperties swaggerConfigProperties;
@Bean
public Docket defaultRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName(swaggerConfigProperties.defaultGroupName)
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerConfigProperties.defaultBasePackage))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(swaggerConfigProperties.defaultTitle)
.description(swaggerConfigProperties.defaultDescription)
.termsOfServiceUrl(swaggerConfigProperties.defaultTermsOfServiceUrl)
// .contact()
.version("1.0")
.build();
}
@Data
@Component
@ConfigurationProperties(prefix = "swagger2")
private class SwaggerConfigProperties {
private String defaultGroupName;
private String defaultBasePackage;
private String defaultTitle;
private String defaultDescription;
private String defaultTermsOfServiceUrl;
private String defaultVersion;
}
}
controller(注意区别findByFoodsName相关方法的区别):
package com.xinx.es.controller;
import com.xinx.es.domain.FoodsEntity;
import com.xinx.es.repository.IFoodsRepository;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author xinx
* @date 2020/4/1 17:17
*/
@Api(tags = "elastic-search")
@RequestMapping(value = "/es")
@RestController
public class EsFoodsController {
@Autowired
IFoodsRepository foodsRepository;
@PostMapping
public boolean save(@RequestBody List<FoodsEntity> foodsList) {
foodsRepository.saveAll(foodsList);
return true;
}
@PutMapping
public FoodsEntity update(@RequestBody FoodsEntity foods) {
foodsRepository.save(foods);
// return foodsRepository.findById(foods.getFoodsId()).;
return null;
}
@DeleteMapping
public boolean delete(@RequestBody FoodsEntity foods) {
foodsRepository.delete(foods);
return true;
}
@GetMapping("/containing")
public List<FoodsEntity> findByFoodsNameContaining(String foodsName) {
try {
return foodsRepository.findByFoodsNameContaining(foodsName);
}catch (Exception e){
System.out.println("ES发生异常");
return null;
}
}
@GetMapping("/contains")
public List<FoodsEntity> findByFoodsNameContains(String foodsName) {
try {
return foodsRepository.findByFoodsNameContains(foodsName);
}catch (Exception e){
System.out.println("ES发生异常");
return null;
}
}
@GetMapping("/matches")
public List<FoodsEntity> findByFoodsNameMatches(String foodsName) {
try {
return foodsRepository.findByFoodsNameMatches(foodsName);
}catch (Exception e){
System.out.println("ES发生异常");
return null;
}
}
@GetMapping("exits")
public List<FoodsEntity> findByFoodsNameExists(String foodsName) {
try {
return foodsRepository.findByFoodsNameExists(foodsName);
}catch (Exception e){
System.out.println("ES发生异常");
return null;
}
}
@GetMapping("like")
public List<FoodsEntity> findByFoodsNameLike(String foodsName) {
try {
return foodsRepository.findByFoodsNameLike(foodsName);
}catch (Exception e){
System.out.println("ES发生异常");
return null;
}
}
}
domain(此处注意,analyzer必须要安装后才能指定,建议大家自行去了解es官方提供的smartcn分词器与ik分词器的区别。ik分词器又包含“ik_max_word”和“ik_smart”两种,大家可自行测试两种的分词效果):
package com.xinx.es.domain;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author xinx
* @date 2020/4/1 16:56
*/
@Data
@Document(indexName = "foods", type = "docs", shards = 1, replicas = 0)
public class FoodsEntity {
@Id
private Integer foodsId;
private String foodsCode;
@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
private String foodsName;
private Integer calories;
private Integer weight;
private Integer healthLight;
private Integer liquid;
private String foodsListImg;
private String foodsDetailImg;
private String foodsUnits;
}
repository:
package com.xinx.es.repository;
import com.xinx.es.domain.FoodsEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
public interface IFoodsRepository extends ElasticsearchRepository<FoodsEntity, Integer> {
List<FoodsEntity> findByFoodsNameMatches(String foodsName);
}
启动类:
package com.xinx.es;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EsApplication {
public static void main(String[] args) {
SpringApplication.run(EsApplication.class, args);
}
}
项目启动后,可在浏览器地址输入:localhost:9999/doc.html,即可看到如下截图(动手调接口玩玩)。
附:
demo写好之后,在集成到项目中时遇到如下报错:
nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]
我网上查询了一下,有人说是因为整合了Redis的原因。但是我把Redis相关的配置去掉后,问题还是没有解决,最后有人说是因为netty冲突的问题。
也有人给出了解决方式就是在项目初始化前设置如下的属性。在初始化之前加上System.setProperty(“es.set.netty.runtime.available.processors”, “false”);
@Configuration
public class ElasticSearchConfig {
@PostConstruct
void init() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
}
我按照这种方法还是没有解决我这边项目的问题。
最后再启动类中进行如下设置解决问题:
@SpringBootApplication
public class EsApplication{
public static void main(String[] args) {
/**
* Springboot整合Elasticsearch 在项目启动前设置一下的属性,防止报错
* 解决netty冲突后初始化client时还会抛出异常
* java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]
*/
System.setProperty("es.set.netty.runtime.available.processors", "false");
SpringApplication.run(EsApplication.class, args);
}
}