docker+springboot+elasticsearch+kibana+elasticsearch-head整合(詳細說明 ,看這一篇就夠了)


一開始是沒有打算寫這一篇博客的,但是看見好多朋友問關於elasticsearch的坑,決定還是寫一份詳細的安裝說明與簡單的測試demo,只要大家跟着我的步驟一步步來,100%是可以測試成功的。

一.  docker安裝

本人使用的是centos6,安裝命令如下:

1.首先使用epel庫安裝docker

yum install -y http://mirrors.yun-idc.com/epel/6/i386/epel-release-6-8.noarch.rpm
yum install -y docker-io

安裝完成后,使用命令 service docker start 啟動docker

控制台輸入docker ,出現如下界面表示安裝成功

如果提示檢查軟件失敗什么的,是因為之前先裝了docker,再裝了docker-io,直接使用命令 yum remove docker 刪除docker,再執行

yum install -y docker-io 即可。
如果仍然提示 no package avalible...
使用rpm安裝docker:
rpm -ivh docker源的方式 yum install

Ubuntu/Debian: curl -sSL https://get.docker.com | sh

Linux 64bit binary: https://get.docker.com/builds/Linux/x86_64/docker-1.7.1

Darwin/OSX 64bit client binary: https://get.docker.com/builds/Darwin/x86_64/docker-1.7.1

Darwin/OSX 32bit client binary: https://get.docker.com/builds/Darwin/i386/docker-1.7.1

Linux 64bit tgz: https://get.docker.com/builds/Linux/x86_64/docker-1.7.1.tgz

Windows 64bit client binary: https://get.docker.com/builds/Windows/x86_64/docker-1.7.1.exe

Windows 32bit client binary: https://get.docker.com/builds/Windows/i386/docker-1.7.1.exe

Centos 6/RHEL 6: https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm

                              https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm

Centos 7/RHEL 7: https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.centos.x86_64.rpm

Fedora 20: https://get.docker.com/rpm/1.7.1/fedora-20/RPMS/x86_64/docker-engine-1.7.1-1.fc20.x86_64.rpm

Fedora 21: https://get.docker.com/rpm/1.7.1/fedora-21/RPMS/x86_64/docker-engine-1.7.1-1.fc21.x86_64.rpm

Fedora 22: https://get.docker.com/rpm/1.7.1/fedora-22/RPMS/x86_64/docker-engine-1.7.1-1.fc22.x86_64.rpm



2.下載elasticsearch 鏡像
在下載elasticsearch鏡像之前,可以先改一下docker的鏡像加速功能,我是用的阿里雲的鏡像加速,登錄阿里雲官網,產品-->雲計算基礎-->容器鏡像服務, 進入管理控制台,如下圖所示,復制加速器地址。

進入虛擬機,vim /etc/sysconfig/docker,加入下面一行配置

other_args="--registry-mirror=https://xxxx.aliyuncs.com"

:wq 保存退出

service docker restart 重啟docker服務

ps -aux|grep docker 輸入如下命令查看docker信息,出現如下信息則加速器配置成功

 

然后就可以快速pull鏡像了。

docker pull elasticsearch

docker pull kibana

 docker pull mobz/elasticsearch-head:5

將我們需要的三個鏡像拉取下來

 

mkdir -p /opt/elasticsearch/data
vim /opt/elasticsearch/elasticsearch.yml

docker run
--name elasticsearch -p 9200:9200 -p 9300:9300 -p 5601:5601 -e "discovery.type=single-node" -v /opt/elasticsearch/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /opt/elasticsearch/data:/usr/share/elasticsearch/data -d elasticsearch

elasticsearch.yml 配置文件內容:

cluster.name: elasticsearch_cluster
node.name: node-master
node.master: true
node.data: true
http.port: 9200
network.host: 0.0.0.0
network.publish_host: 192.168.6.77
discovery.zen.ping.unicast.hosts: ["192.168.6.77","192.168.6.78"]
http.host: 0.0.0.0
http.cors.enabled: true
http.cors.allow-origin: "*"
bootstrap.memory_lock: false
bootstrap.system_call_filter: false
# Uncomment the following lines for a production cluster deployment
#transport.host: 0.0.0.0
discovery.zen.minimum_master_nodes: 1

注意我的elasticsearch 是在兩台服務器上的,所以集群部署的時候可以省略端口號,因為都是9300,如果你的集群是部署在同一台os上,則需要區分出來端口號。

cluster.name: elasticsearch_cluster 集群名字,所有集群統一。
node.name: node-master 你的節點名稱,所有集群必須區分開。
http.cors.enabled: true http.cors.allow-origin: "*" 支持跨域
discovery.zen.minimum_master_nodes: 1 可被發現作為主節點的數量
network.publish_host: 192.168.6.77 對外公布服務的真實IP
network.host: 0.0.0.0 開發環境可以設置成0.0.0.0,真正的生產環境需要指定IP地址。
 
 
 
        


 

我們啟動elasticsearch容器多加了一個端口映射 -p 5601:5601 目的是讓kibana使用該容器的端口映射,無需指定kibana容器的映射了。

啟動kibana:

docker run --name kibana -e ELASTICSEARCH_URL=http://127.0.0.1:9200 --net=container:elasticsearch -d kibana

--net=container:elasticsearch 命令為指定使用elasticsearch的映射

這個時候,一般elasticsearch是啟動報錯的,我們需要修改一下linux的文件配置,如文件描述符的大小等。

需要修改的文件一共兩個:

切換到root用戶    
1、vi /etc/security/limits.conf 修改如下配置
* soft nofile 65536
* hard nofile 131072
 
2、vi /etc/sysctl.conf 添加配置
vm.max_map_count=655360 
運行命令 sysctl -p

這個時候配置完了輸入命令

ulimit -Sn

ulimit -Hn 

出現如下信息即配置成功。

可是這個時候重啟容器依然是報錯的,沒報錯是你運氣好,解決辦法是重啟一下docker就OK了。

service docker restart

然后重啟elasticsearch 容器

docker restart elasticsearch 

訪問ip:9200 

出現如下信息,則elasticsearch 啟動成功

{
  "name" : "node-master",
  "cluster_name" : "elasticsearch_cluster",
  "cluster_uuid" : "QzD1rYUOSqmpoXPYQqolqQ",
  "version" : {
    "number" : "5.6.12",
    "build_hash" : "cfe3d9f",
    "build_date" : "2018-09-10T20:12:43.732Z",
    "build_snapshot" : false,
    "lucene_version" : "6.6.1"
  },
  "tagline" : "You Know, for Search"
}
接着同樣的操作,在另外一台os上啟動elasticsearch,兩台不同的地方一是第二台我們不需要做-p 5601:5601的端口映射,第二是elasticsearch.yml配置文件的一些不同:
cluster.name: elasticsearch_cluster
node.name: node-slave
node.master: false
node.data: true
http.port: 9200
network.host: 0.0.0.0
network.publish_host: 192.168.6.78
discovery.zen.ping.unicast.hosts: ["192.168.6.77:9300","192.168.6.78:9300"]
http.host: 0.0.0.0
http.cors.enabled: true
http.cors.allow-origin: "*"
bootstrap.memory_lock: false
bootstrap.system_call_filter: false
# Uncomment the following lines for a production cluster deployment
# #transport.host: 0.0.0.0
# #discovery.zen.minimum_master_nodes: 1
#

兩台os中的elasticsearch都啟動成功后,便可以啟動kibana和head了。

 


重啟kibana
docker restart kibana
訪問http://ip:5601
出現如下頁面則kibana啟動成功

 
        

啟動elasticsearch-head監控es服務

docker run -d -p 9100:9100 mobz/elasticsearch-head:5

訪問ip:9100

出現如下界面即啟動head成功

 

到此我們的准備工作算是完成了,接下來新建springboot項目,pom引入

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

其他mvc mybatis配置在此不再贅述,application.yml配置如下:

spring:
  data:
   elasticsearch:
    cluster-nodes: 192.168.6.77:9300
    repositories.enabled: true
    cluster-name: elasticsearch_cluster

編寫倉庫測試類 UserRepository:

package com.smkj.user.repository;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

import com.smkj.user.entity.XymApiUser;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.repository
 * @email yangyang@dalaoyang.cn
 * @date 2018/5/4
 */
@Component
public interface UserRepository extends ElasticsearchRepository<XymApiUser,String> {
}

實體類中,加上如下注解:

@SuppressWarnings("serial")
@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain=true)
@Document(indexName = "testuser",type = "XymApiUser")

最后一個注解是使用elasticsearch必加的,類似數據庫和數據表映射

上邊的幾個就是貼出來給大家推薦一下lombok這個小東東,挺好用的,具體使用方法可以自行百度,不喜歡的同學可以直接刪掉。

然后編寫controller:

package com.smkj.user.controller;

import java.util.List;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.smkj.user.entity.XymApiUser;
import com.smkj.user.repository.UserRepository;
import com.smkj.user.service.UserService;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;
     @Autowired
        private TransportClient client;
@GetMapping("user/{id}")
    public XymApiUser getUserById(@PathVariable String id) {
    XymApiUser apiuser = userService.selectByPrimaryKey(id);
    userRepository.save(apiuser);
    System.out.println(apiuser.toString());
    return apiuser;
        
    }
/**
 * @param title   搜索標題
 * @param pageable page = 第幾頁參數, value = 每頁顯示條數
 */
@GetMapping("get/{id}")
public ResponseEntity  search(@PathVariable String id,@PageableDefault(page = 1, value = 10) Pageable pageable){
       if (id.isEmpty()) {
           return new ResponseEntity(HttpStatus.NOT_FOUND);
       }
      
    // 通過索引、類型、id向es進行查詢數據
       GetResponse response = client.prepareGet("testuser", "xymApiUser", id).get();
       if (!response.isExists()) {
           return new ResponseEntity(HttpStatus.NOT_FOUND);
       }

       // 返回查詢到的數據
       return new ResponseEntity(response.getSource(), HttpStatus.OK);
}


/**
 * 3、查   +++:分頁、分數、分域(結果一個也不少)
 * @param page
 * @param size
 * @param q
 * @return 
 * @return
 */
@GetMapping("/{page}/{size}/{q}")
public Page<XymApiUser> searchCity(@PathVariable Integer page, @PathVariable Integer size, @PathVariable String q) {

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery( QueryBuilders.prefixQuery("cardNum",q))
            .withPageable(PageRequest.of(page, size))
            .build();
    Page<XymApiUser> pagea = userRepository.search(searchQuery);
    System.out.println(pagea.getTotalPages()); 
    return pagea;

}





}

 

 

訪問 http://localhost:8080/0/10/6212263602070571344

到此結束,不明白的朋友可以留言。

 


免責聲明!

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



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