SpringBoot2.x整合Elasticsearch6.x

SpringBoot2.x整合Elasticsearch6.x

  •  10个月前
  •  1954
  •  Java SpringBoot Elasticsearch 

本文SpringBoot2.x整合Elasticsearch6.x,并展示如何使用RestHighLevelClient和Spring Data Elasticsearch对ES进行基本的操作。

Spring Data Elasticsearch就不再多说了,那么为什么要使用RestHighLevelClient呢?官网是这么说的:

The well known TransportClient is deprecated as of Elasticsearch 7 and will be removed in Elasticsearch 8. (see the Elasticsearch documentation). Spring Data Elasticsearch will support the TransportClient as long as it is available in the used Elasticsearch version.

We strongly recommend to use the High Level REST Client instead of the TransportClient.

The Java High Level REST Client now is the default client of Elasticsearch, it provides a straight forward replacement for the TransportClient as it accepts and returns the very same request/response objects and therefore depends on the Elasticsearch core project. Asynchronous calls are operated upon a client managed thread pool and require a callback to be notified when the request is done.

想看更多请点这里。下面开始粘代码~

环境

  • SpringBoot: 2.1.5.RELEASE
  • Elasticsearch: 6.7.2
  • Kibana: 6.7.2
  • JDK: 1.8

没有安装Elasticsearch的话可以看下这篇文章,环境准备这里就不再赘述了。

Maven依赖

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-elasticsearch</artifactId>
    <version>3.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.7.2</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.7.2</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>x-pack-transport</artifactId>
    <version>6.7.2</version>
</dependency>

如果x-pack-transport无法下载的话需要添加下面的repository:

<repositories>
    <repository>
        <id>elasticsearch-releases</id>
        <url>https://artifacts.elastic.co/maven</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

配置

elastic.host=127.0.0.1
elastic.port=9200
elastic.username=username
elastic.password=password
@Configuration
public class ESConfig {

    @Value("${elastic.host}")
    private String host;

    @Value("${elastic.port}")
    private int port;

    @Value("${elastic.username}")
    private String userName;

    @Value("${elastic.password}")
    private String password;

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

        return new RestHighLevelClient(builder);
    }

    @Bean
    public ElasticsearchRestTemplate elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }

}

Bean

创建实体类对应ES中要存储的文档。

@Data
@Accessors(chain = true)
@Document(indexName = "student", type = "_doc")
public class Student {

    @Id
    private Long id;

    private String name;

    private String hobby;

    private Date birthday;

}

Repository

public interface StudentRepository extends ElasticsearchRepository<Student, Long> {

    List<Student> findByName(String name);

}

单元测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class StudentComponentTest {

    @Autowired
    private StudentRepository studentRepository;

    @Test
    public void save() {
        Student stu = new Student().setId(4L).setName("Bob").setHobby("biu biu biu~~").setBirthday(new Date());
        studentRepository.save(stu);
    }

    @Test
    public void findById() {
        Student stu = studentRepository.findById(1L).orElse(null);
        System.out.println(stu);
    }

    @Test
    public void findByName() {
        List<Student> bob = studentRepository.findByName("Bob");
        bob.forEach(System.out::println);
    }

    @Test
    public void delete() {
        studentRepository.delete(new Student().setId(3L));
    }
    
}

使用Kibana查询  GET student/_doc/4

{
	"_index" : "student",
	"_type" : "_doc",
	"_id" : "4",
	"_version" : 1,
	"_seq_no" : 4,
	"_primary_term" : 1,
	"found" : true,
	"_source" : {
		"id" : 4,
		"name" : "Bob",
		"hobby" : "biu biu biu~~",
		"birthday" : 1574928193874
	}
}

完成~

源码地址:https://github.com/chenpeidong/spring-boot-demo/tree/master/spring-boot-elasticsearch


扫一扫分享到微信

已有 条评论
写评论