ElasticSearch(三)springboot整合ES

最基礎的整合:html

1、maven依賴node

<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、配置文件application.ymlweb

spring:
  data:
    elasticsearch:
    ####集羣名稱
     cluster-name: myes
    ####地址 
     cluster-nodes: 192.168.212.xxx:9300

3、實體類UserEntityspring

@Document(indexName = "mymayikt", type = "user")
@Data
public class UserEntity {
    @Id
    private String id;
    private String name;
    private int sex;
    private int age;
}

4、dao層代碼(實現CrudRepository就能夠了,裏面封裝不少操做ES的方法)app

public interface UserReposiory extends CrudRepository<UserEntity, String> {

}

5、controller層elasticsearch

@RestController
public class EsController {

    @Autowired
    private UserReposiory userReposiory;

    @RequestMapping("/addUser")
    public UserEntity addUser(@RequestBody UserEntity user) {
        return userReposiory.save(user);
    }

    @RequestMapping("/findUser")
    public Optional<UserEntity> findUser(String id) {
        return userReposiory.findById(id);
    }
}

6、啓動類maven

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.dyh.dao")
public class AppEs {

    public static void main(String[] args) {
        SpringApplication.run(AppEs.class, args);
    }
}

 

直接啓動會報錯:spring-boot

None of the configured nodes are available:spa

  解決方案(項目配置文件cluster-name要與ElasticSearch的配置文件屬性值要相同):code

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

    cluster.name: myes

 

 

也能夠參考這個博客:https://www.cnblogs.com/dalaoyang/p/8990989.html

相關文章
相關標籤/搜索