SpringBoot整合Elasticsearch框架


新建SpringBoot項目:

修改pom.xml文件,引入spring-boot-data-elasticsearch Jar 包:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
   <version>2.2.2.RELEASE</version>
</dependency>

修改application.yml文件,引入elasticsearch配置:

spring:
  data:
    elasticsearch:
      ##集群名稱,elasticsearch.yml的cluster.name: chenxi配置
      ##詳情見 http://chenxitag.elasticsearch.cluster.com
      cluster-name: chenxi
      ##集群地址逗號分隔,注意此地方用的端口為9300,Es集群TCP協議端口
      cluster-nodes: 192.168.0.1:9300,192.168.0.2:9300

新建測試Entity:

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


@Document(indexName = "chenxi", type = "user"/*shards = 1, replicas = 2 ##可指定分片數和副本數*/)
@Data
public class UserEntity {
    @Id
    private Integer id;
    private String name;
    private Integer age;
}

新建測試Dao:

import com.es.entity.UserEntity;
import org.springframework.data.repository.CrudRepository;

public interface UserDao extends CrudRepository<UserEntity, Integer> {
}

新建Test類測試:

import com.es.dao.UserDao;
import com.es.entity.UserEntity;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

@SpringBootTest
@Slf4j
class EsTestApplicationTests {

   @Test
   void contextLoads() {
   }

   @Autowired
   private UserDao userDao;

   @Autowired
   private ElasticsearchTemplate esTemplate;

   @Test
   void esSave(){

      UserEntity esEntity = new UserEntity();
      esEntity.setId(1);
      esEntity.setName("chenxi");
      esEntity.setAge(22);

      userDao.save(esEntity);
   }

   @Test
   void esFind(){
      log.info(new Gson().toJson(userDao.findById(1)));
      //info out "{"value":{"id":1,"name":"chenxi","age":22}}"
   }

   @Test
   void esTemplate(){
      log.info(String.valueOf(esTemplate.createIndex("template_index")));
      //info out "true"
   }

錯誤信息:NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{P20ipqqfSNCzjirh0puSTQ}{192.168.0.1}{192.168.0.1:9300}, {#transport#-2}{I4slCrNuTbmVTOSZ3DG7hA}{192.168.0.2}{192.168.0.2:9300}]

請檢查Es是否啟動,以及Es環境elasticsearch.yml集群配置項:

# ———————————- Cluster ———————————–
#
# Use a descriptive name for your cluster:
# 節點集群名稱,保證三台服務器節點集群名稱相同
cluster.name: chenxi

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM