1. 程式人生 > >elasticsearch安裝及與springboot2.x整合

elasticsearch安裝及與springboot2.x整合

  關於elasticsearch是什麼、elasticsearch的原理及elasticsearch能幹什麼,就不多說了,主要記錄下自己的一個使用過程。

  1、安裝

  elasticsearch是用java編寫的,所以它的執行離不開jdk,jdk的安裝這裡不再囉嗦,我使用的是虛擬機器是centos7,已經裝好了jdk1.8,下面說下自己安裝elasticsearch的過程。

  (1)到官網 https://www.elastic.co/guide/en/elasticsearch/reference/current/install-elasticsearch.html,檢視各個作業系統的安裝方式,找到對應的,我的是centos7,以root身份登入,執行 wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.5.1.tar.gz。

  (2)解壓 tar -zvxf elasticsearch-6.5.1.tar.gz -C /usr/local

  (3)預設ES 6.X 是不允許root使用者執行的,否則ES執行的時候會報錯,所以我們需要建立新的使用者,groupadd es ——>useradd es -g es——>passwd es 按照提示設定密碼即可。修改許可權 chown -R es:es elasticsearch-6.5.1

  (4)修改配置,支援外網訪問(記得關防火牆),在合適的位置建立兩個資料夾,分別用來儲存elasticsearch的資料和日誌,執行vim config/elasticsearch.yml,取消下列對應的項的註釋並修改      

  cluster.name: li-application #叢集名稱,可以自行修改
  node.name: linux-2 #節點名稱,自行修改
  network.host: 0.0.0.0 #主機地址,這裡寫本機IP
  http.port: 9200 #埠
  path.data: /var/lib/es 資料儲存位置
  path.logs: /var/logs/es 日誌儲存位置

  (5)執行vim /etc/security/limits.conf,在結尾加上如下配置,其中es是使用者名稱

  es soft nofile 65536
  es hard nofile 131072
  es soft nproc 4096
  es hard nproc 4096

  (6)執行 vi /etc/sysctl.conf,在檔案末尾新增 vm.max_map_count=655360,儲存,並執行命令 sysctl -p

  (7)切換到es使用者,進入/usr/local/elasticsearch-6.5.1,執行./bin/elasticsearch -d (後臺啟動)。

  (8)執行 curl -i localhost:9200,會有一個測試資訊的響應,表示安裝成功。

  2、整合springboot2.0

  (1)引入依賴

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

        <!--集合工具包-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>

  (2)新增配置,注意埠號是9300

spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=192.168.1.126:9300
spring.data.elasticsearch.repositories.enabled=true
server.port=11111

  (3)編寫對應的程式碼

package com.example.demo;

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

import com.fasterxml.jackson.annotation.JsonProperty;

//indexName代表所以名稱,type代表表名稱
@Document(indexName = "wantu_notice_info", type = "doc")
public class Notice {

    //id
    @JsonProperty("auto_id")
    private Long id;

    //標題
    @JsonProperty("title")
    private String title;

    //公告標籤
    @JsonProperty("exchange_mc")
    private String exchangeMc;

    //公告發布時間
    @JsonProperty("create_time")
    private String originCreateTime;

    //公告閱讀數量
    @JsonProperty("read_count")
    private Integer readCount;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getExchangeMc() {
        return exchangeMc;
    }

    public void setExchangeMc(String exchangeMc) {
        this.exchangeMc = exchangeMc;
    }

    public String getOriginCreateTime() {
        return originCreateTime;
    }

    public void setOriginCreateTime(String originCreateTime) {
        this.originCreateTime = originCreateTime;
    }

    public Integer getReadCount() {
        return readCount;
    }

    public void setReadCount(Integer readCount) {
        this.readCount = readCount;
    }

    public Notice(Long id, String title, String exchangeMc, String originCreateTime, Integer readCount) {
        super();
        this.id = id;
        this.title = title;
        this.exchangeMc = exchangeMc;
        this.originCreateTime = originCreateTime;
        this.readCount = readCount;
    }

    public Notice() {
        super();
    }
    
    
}
package com.example.demo;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public interface NoticeRepository extends ElasticsearchRepository<Notice, Long> {

}
package com.example.demo;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

@RestController
@RequestMapping("/api/v1/article")
public class NoticeController {


    @Autowired
    private NoticeRepository nticeRepository;
    
    @GetMapping("/save")
    public Object save(long id, String title){
    
        Notice article = new Notice();
        article.setId(id);
        article.setReadCount(123);
        article.setTitle(title);
        return nticeRepository.save(article);
    }


    /**
     * @param title   搜尋標題
     * @param pageable page = 第幾頁引數, value = 每頁顯示條數
     */
    @GetMapping("/search")
    public Object search(String title ,@PageableDefault() Pageable pag){

        //按標題進行搜尋
        QueryBuilder builder = QueryBuilders.matchQuery("title", title);
        //如果實體和資料的名稱對應就會自動封裝,pageable分頁引數
        Iterable<Notice> listIt =  nticeRepository.search(builder, pag);
        //Iterable轉list
        List<Notice> list= Lists.newArrayList(listIt);
        
       return list;
    }
    
    
    @RequestMapping("/all")
    public List<Notice> all() throws Exception {
        Iterable<Notice> data = nticeRepository.findAll();
        List<Notice> ds = new ArrayList<>();
        for (Notice d : data) {
            ds.add(d);
        }
        return ds;
    }
    @RequestMapping("/id")
    public Object findid(long id) throws Exception {
         return nticeRepository.findById(id).get();
        
        
    }
    
}

  啟動專案,先新增幾條資料,然後依次訪問全部記錄、帶"三"的記錄、帶"吃飯"的記錄,效果如下: