1. 程式人生 > >ElasticSearch與springboot整合

ElasticSearch與springboot整合

還是跟之前一樣,用gradle+springboot+ElasticSearchl來實現一個小例項 也有用到spring data

因為用到ElasticSearch,所以要安裝 啟動,linux下的安裝不做演示。window下啟動就是在bin資料夾下雙擊elasticsearch.bat就可以了

修改build.gradle
// 新增 Spring Data Elasticsearch 的依賴
compile(‘org.springframework.boot:spring-boot-starter-data-elasticsearch’)
// 新增 JNA 的依賴
compile(‘net.java.dev.jna:jna:4.3.0’)

// buildscript 程式碼塊中指令碼優先執行
buildscript {

    // ext 用於定義動態屬
    ext {
        springBootVersion = '1.5.2.RELEASE'
    }

    // 自定義 Elasticsearch 的版本
    //ext['elasticsearch.version'] = '5.2.2'

    // 使用了 Maven 的中央倉庫(你也可以指定其他倉庫)
    repositories {
        //mavenCentral()
        maven {
            url 'http://maven.aliyun.com/nexus/content/groups/public/'
} } // 依賴關係 dependencies { // classpath 宣告說明了在執行其餘的指令碼時,ClassLoader 可以使用這些依賴項 classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } // 使用外掛 apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' // 打包的型別為 jar,並指定了生成的打包的檔名稱和版本
jar { baseName = 'elasticsearch-in-action' version = '1.0.0' } // 指定編譯 .java 檔案的 JDK 版本 sourceCompatibility = 1.8 // 預設使用了 Maven 的中央倉庫。這裡改用自定義的映象庫 repositories { //mavenCentral() maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } } // 依賴關係 dependencies { // 該依賴對於編譯發行是必須的 compile('org.springframework.boot:spring-boot-starter-web') // 新增 Spring Data Elasticsearch 的依賴 compile('org.springframework.boot:spring-boot-starter-data-elasticsearch') // 新增 JNA 的依賴 compile('net.java.dev.jna:jna:4.3.0') // 該依賴對於編譯測試是必須的,預設包含編譯產品依賴和編譯時依 testCompile('org.springframework.boot:spring-boot-starter-test') }

照常,可以的話在cmd命令下用gradlew bootRun執行
開啟瀏覽器瀏覽localhost:8080是否可以跳出一個頁面,只要能跳出就可以了

修改application.properties

# ElasticSearch服務地址
spring.data.elasticsearch.cluster-nodes=localhost:9300
# 設定連線超時時間
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s

建立一個文件實體 Blog.java

@Document(indexName = "blog", type = "blog", shards = 1, replicas = 0, refreshInterval = "-1") //標識是文件
//@XmlRootElement // MediaType 轉為 XML
public class Blog implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id  // 主鍵
    private String id; // 使用者的唯一標識

    private String title;

    private String content;

    protected Blog() {  // spring data JPA 的規範要求無參建構函式;設為 protected 防止直接使用 
    }

    public Blog(String name, String content) {
        this.title = name;
        this.content = content;
    }

    public Blog(String id, String name, String content) {
        this.id = id;
        this.title = name;
        this.content = content;
    }

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return String.format(
                "User[id='%s', title='%s', content='%s']",
                id, title, content);
    }
}

BlogRepository.java

public interface BlogRepository extends ElasticsearchRepository<Blog, String> {
    /**
     * 根據使用者名稱分頁查詢使用者列表 模糊查詢
     * 
     */
    Page<Blog> findByTitleLikeOrContentLike(String title, String content, Pageable pageable);
}

這裡寫圖片描述

寫一個測試類
BlogRepositoryTest.java

@RunWith(SpringRunner.class)  
@SpringBootTest  //傳入上下文
public class BlogRepositoryTest {

    @Autowired
    private BlogRepository blogRepository;

    @Before //junit的方法  在Test執行之前執行
    public void initRepositoryData(){
        //清楚所有資料
        blogRepository.deleteAll();
    }
    @Test
    public void testFindByTitleLikeOrContentLike() {
        blogRepository.save(new Blog("1","跟你談談安裝 Elasticsearch",
                "關於如何來安裝 Elasticsearch,這個請看我的部落格 https://waylau.com"));
        blogRepository.save(new Blog("2","跟你談談 Elasticsearch 的幾個用法",
                "關於如何來用 Elasticsearch,還是得看我的部落格 https://waylau.com,妹"));  // 關鍵字"妹"
        blogRepository.save(new Blog("3","和你一起學 Elasticsearch",
                "如何來學習 Elasticsearch,最終看我的部落格 https://waylau.com,酒")); // 關鍵字"酒"

        blogRepository.save(new Blog("4","03-05 用大白話聊聊分散式系統",
                "一提起“分散式系統”,大家的第一感覺就是好高大上啊,深不可測"));
        blogRepository.save(new Blog("5","02-19 Thymeleaf 3 引入了新的解析系統",
                "如果你的程式碼使用了 HTML5 的標準,而Thymeleaf 版本來停留在 2.x ,那麼如果沒有把閉合"));  
        blogRepository.save(new Blog("6","02-19 使用 GFM Eclipse 外掛時,不在專案裡面生成 HTML 檔案",
                "GFM 是 GitHub Flavored Markdown Viewer 的簡稱,是一款對 GitHub 友好的 Markdown 編輯器 。"));  

        Pageable pageable = new PageRequest(0, 20);
        Page<Blog> page = blogRepository.findByTitleLikeOrContentLike("妹", "酒", pageable);
        assertThat(page.getTotalElements()).isEqualTo(2);
    }
}

在啟動測試之前,記得啟動elasticsearch,否則連線報錯

寫控制層 BlogController.java

@RestController
@RequestMapping("/blogs")
public class BlogController {

    @Autowired
    private BlogRepository blogRepository;

    @GetMapping
    public List<Blog> list(@RequestParam(value="title",required=false,defaultValue="") String title,
            @RequestParam(value="content",required=false,defaultValue="") String content,
            @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex,
            @RequestParam(value="pageSize",required=false,defaultValue="10") int pageSize) {

        // 資料在 Test 裡面先初始化了,這裡只管取資料
        Pageable pageable = new PageRequest(pageIndex, pageSize);
        Page<Blog> page = blogRepository.findByTitleLikeOrContentLike(title, content, pageable);

        return page.getContent();
    }
}

清除之前elasticsearch的資料,在安裝目錄下的data資料夾下 刪除elasticsearch這個檔案
再次啟動/bin/elasticsearch.bat 可以先執行專案,在執行上面的測試類 這樣就有資料了

相關推薦

ElasticSearchspringboot整合

還是跟之前一樣,用gradle+springboot+ElasticSearchl來實現一個小例項 也有用到spring data 因為用到ElasticSearch,所以要安裝 啟動,linux下的安裝不做演示。window下啟動就是在bin資料夾下雙擊e

ElasticSearchSpringBoot整合JPA方法的使用

完整程式碼示例,請參考個人GitHub倉庫:(github.com/KimZing), 包含controller/repository以及測試程式碼。 歡迎star,如有錯誤,歡迎指正_ 一、環境簡介 idea 2016.3 jdk 1.8 ElasticSearch 2.4(之所以不用最

Elasticsearch 分片叢集原理、搭建、SpringBoot整合

單機es可以用,沒毛病,但是有一點我們需要去注意,就是高可用是需要關注的,一般我們可以把es搭建成叢集,2臺以上就能成為es叢集了。叢集不僅可以實現高可用,也能實現海量資料儲存的橫向擴充套件。 新的閱讀體驗地址: http://www.zhouhong.icu/post/138 一、Ela

Elasticsearch Kafka 整合剖析

簡單 prepare 3.2 ger 郵件 核心 pri servers 技術 1.概述   目前,隨著大數據的浪潮,Kafka 被越來越多的企業所認可,如今的Kafka已發展到0.10.x,其優秀的特性也帶給我們解決實際業務的方案。對於數據分流來說,既可以分流到離線存儲

【ActivtiSpringBoot整合後相關核心Api的介紹】

使用編譯器:Eclipse(因為流程圖使用的是Eclipse的繪圖工具,所以程式碼也就直接在上面編輯,編碼Idea也是非常好用的工具,同學如果不習慣的話,可以畫完圖,複製到Idea上,編寫程式碼) 核心Api介紹: # 核心API介紹 ProcessEngine(最核心Api) &n

Elasticsearch Springboot 的簡單連線

1、主要Elasticsearch 包: 2、application.properties 配置   3、 Elasticsearch  java 程式碼 package com.allen.elasticsearch; import jav

18.ShiroSpringboot整合下登陸驗證UserService未注入的問題

Shiro與Springboot整合下登陸驗證UserService未注入的問題 前言: 剛開始整合的情況下,UserService一執行,就會報空指標異常。 看了網上各位大神的講解,什麼不能用service層,直接用dao層獲取。。。。。。 然後跟著一路再坑。。。。。。。 最後的最後,才發現MyR

cas單點登入 (二) 客戶端springboot整合

在springboot專案中實現cas單點登入統一認證,只需要在專案中配置 cas過濾器即可使用. 1. springboot專案pom.xml中 新增web支援依賴 、cas客戶端依賴包 <dependency> <groupId>org

shiro許可權框架-(二)Springboot整合

首先引入shiro與Spring的依賴。 Shiro和Spring整合的依賴 <dependency> <groupId>org.apache.shiro<

FastDFSSpringboot整合

上一篇《FastDFS分佈檔案系統Java客戶端使用》基於官方提供的Java客戶端庫介紹了檔案上傳、下載和刪除的功能。淘寶在今年9月份在官方Java客戶端的基礎上進行了大量重構,且提供了更多豐富的api,主要新增的特性如下:  1> 對關鍵部分程式碼加入了單元測

NettySpringBoot整合

Netty與Spring Boot的整合 ​ 最近有朋友向我詢問一些Netty與SpringBoot整合的相關問題,這裡,我就總結了一下基本整合流程,也就是說,這篇文章 ,預設大家是對netty與Spring,SpringMVC的整合是沒有什麼問題的。現在,就進入正題吧。 Se

Docker入門實踐筆記(三)一篇文章搞懂Docker下安裝Redis,以及RedisSpringBoot整合

@Configuration public class RedisConfig { ​ /** * 注入 RedisConnectionFactory */ @Autowired RedisConnectionFactory redisConnectionFacto

tk-mybatisspringBoot整合使用兩個資料來源

根據專案功能需求,需要與第三方公共庫對接,需要對公共庫進行相關操作,由於不想使用原生jdbc,所以採用mybaits進行多資料配置。 單純的使用mybaits進行多資料配置網上資料很多,但由於前期為了方便開發,採用了tk-mybaits。關於tk-mybaits多資料來源配

RabbitMQ ——SpringBoot整合並實現訊息確認機制

不囉嗦直接上程式碼 目錄結構如下: pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instanc

redis叢集搭建並springboot整合

redis叢集裡面的坑實在太多了,一步錯,步步錯,經過兩個不眠夜終於把這個坑給填上了,由於是在測試,所以以單機版叢集為例,下面就把搭建過程總結一下。 首先,有一個檔案大家必須要找好,就是redis-trib.rb,如圖: 大家網上自己找也好或者去這個地址下載夜行,需要一點資源分:https:

elasticsearch hive整合

ElasticSearch是一個基於Lucene構建的開源,分散式,RESTful搜尋引擎。設計用於雲端計算中,能夠達到實時搜尋,穩定,可靠,快速,安裝使用方便。 hive是一個基於hdfs的資料倉庫,方便使用者可以通過一種類sql(HiveQL)的語言對hdfs上面的打

ActiveMQ訊息中介軟體 原理詳解 &&附demo實現、以及springboot整合的demo

一、 訊息中介軟體概述1. 什麼是訊息中介軟體? 面向訊息的中介軟體(MessageOrlented MiddlewareMOM)較好的解決了以上問題。傳送者將訊息傳送給訊息伺服器, 訊息伺服器將消感

ShiroSpringBoot整合

SpringBoot框架現階段使用的比較頻繁,但是Spring家族中的安全管理框架(Spring Security)的功能雖然強大,但是他是給予Spring的,不能單獨使用,而Shiro則相對簡單,容易上手,所以這裡簡單記錄一下SpringBoot框架整合Shi

mycat安裝及springboot整合

1. mycat下載http://dl.mycat.io/1.6-RELEASE/2.解壓,配置環境變數,path=D:\software\Mycat-server-1.6-RELEASE-20161028204710-win\mycat\bin[mycat安裝地址]3.修改

elasticsearch grafana整合

效果圖: 安裝 grafana systemctl daemon-reload vim /etc/grafana/grafana.ini [paths] logs = /var/log/grafana [server