SpringBoot 集成Elasticsearch

1 maven

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

2,创建实体类

package com.aiyuesheng.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

import lombok.Data;

// 指定了索引,类型
@Document(indexName = "myindex", type = "user")  
@Data
public class UserEntity {
    @Id
    private String id;
    private String name;
    private String sex;
    private int age;

}

3,创建接口extends增删改查CrudRepository()

package com.aiyuesheng.dao;

import org.springframework.data.repository.CrudRepository;

import com.aiyuesheng.entity.UserEntity;

public interface UserReposiory extends CrudRepository<UserEntity, String> {

}

4,创建接口层

package com.aiyuesheng.service;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.aiyuesheng.dao.UserReposiory;
import com.aiyuesheng.entity.UserEntity;

@RestController
public class EsController {

    @Autowired
    private UserReposiory userReposiory;

//可以用postman 模拟请求 @RequestMapping(
"/addUser") public UserEntity addUser(@RequestBody UserEntity user) { return userReposiory.save(user); } @RequestMapping("/findUser") public Optional<UserEntity> findUser(String id) { return userReposiory.findById(id); } }

5,启动类:

// 需要加入扫包的范围
@SpringBootApplication @EnableElasticsearchRepositories(basePackages
= "com.aiyuesheng.dao") public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }

7,配置文件:

spring:
  data:
    elasticsearch:
    ####集群名称
     cluster-name: myes
    ####地址 
     cluster-nodes: 192.168.178.110:9300

8,在ElasticSearch 服务中,要把cluster-name 开启,相当于,springboot 程序和ElasticSearch 对接:

vi /usr/local/elasticsearch-6.4.3/config/elasticsearch.yml

cluster.name: myes

猜你喜欢

转载自www.cnblogs.com/pickKnow/p/11450406.html