十次方後端筆記四:搜索微服務

tensquare搜索微服務

搜索微服務創建Module(省略)

準備工作

引入依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>tensquare_parent</artifactId>
        <groupId>com.tensquare</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>tensquare_search</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>com.tensquare</groupId>
            <artifactId>tensquare_common</artifactId>
            <version>${tensquare.version}</version>
        </dependency>
    </dependencies>

</project>

application.yml

server:
  port: 9007
spring:
  application:
    name: tensquare-search
  data:
    elasticsearch:
      cluster-nodes: 192.168.136.104:9300

啓動類

package com.tensquare.search;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

實體類

之前也有一個文章實體類,是Mysql在使用。

這個文章實體類,是ES所使用的實體類。

package com.tensquare.search.pojo;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

import java.io.Serializable;

/**
* 文章實體類
*/
@Document(indexName="tensquare",type="article")
public class Article implements Serializable {
    @Id
    private String id;//ID
    @Field(index= true,analyzer="ik_max_word",searchAnalyzer="ik_max_word")
    private String title;//標題
    @Field(index= true,analyzer="ik_max_word",searchAnalyzer="ik_max_word")
    private String content;//文章正文
    private String state;//審覈狀態
}

添加文章到ES

ArticleSearchController

package com.tensquare.search.controller;

import com.tensquare.search.pojo.Article;
import com.tensquare.search.service.ArticleSearchService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/article")
public class ArticleSearchController {

    @Autowired
    private ArticleSearchService articleSearchService;

    @RequestMapping(method = RequestMethod.POST)
    public Result save(@RequestBody Article article) {
        articleSearchService.save(article);
        return new Result(true, StatusCode.OK, "操作成功");
    }
}

ArticleSearchService

package com.tensquare.search.service;

import com.tensquare.search.dao.ArticleSearchDao;
import com.tensquare.search.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleSearchService {
    @Autowired
    private ArticleSearchDao articleSearchDao;

    /**
     * 增加文章
     *
     * @param article
     */
    public void save(Article article) {
        articleSearchDao.save(article);
    }
}

ArticleSearchDao

package com.tensquare.search.dao;

import com.tensquare.search.pojo.Article;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ArticleSearchDao extends ElasticsearchRepository<Article,String> {
}

文章搜索

ArticleSearchController新增方法

    @RequestMapping(value = "/search/{keywords}/{page}/{size}", method = RequestMethod.GET)
    public Result findByTitleLike(@PathVariable String keywords,
                                  @PathVariable int page, @PathVariable int size) {
        Page<Article> articlePage = articleSearchService.findByTitleLike(keywords, page, size);
        return Result.ok( "查詢成功", new PageResult<>(articlePage.getTotalElements(), articlePage.getContent()));
    }

ArticleSearchService新增方法

    /**
     * 按名稱查詢文章
     *
     * @param keywords
     * @param page
     * @param size
     * @return
     */
    public Page<Article> findByTitleLike(String keywords, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return articleSearchDao.findByTitleOrContentLike(keywords, keywords, pageRequest);
    }

ArticleSearchDao

Page<Article> findByTitleOrContentLike(String title, String content, Pageable pageable);

同步文章數據到ES

安裝logstash(省略)

配置logstash

使用logstash導入數據到ES,任務配置爲:

input {
	jdbc {
		# 數據庫連接地址
		jdbc_connection_string => "jdbc:mysql://192.168.136.104:3306/tensquare_article?characterEncoding=UTF8"
		# 用戶名密碼
		jdbc_user => "root"
		jdbc_password => "123456"
		# 數據庫驅動包路徑
		jdbc_driver_library => "D:/logstash‐5.6.8/mysqletc/mysql-connector-java-5.1.46.jar"
		# driver class
		jdbc_driver_class => "com.mysql.jdbc.Driver"
		jdbc_paging_enabled => "true"
		jdbc_page_size => "50000"
		# 要執行的sql,
		statement => "select id,title,content from tb_article"
		# 定時字段 各字段含義(由左至右)分、時、天、月、年,類似cron表達式
		schedule => "* * * * *"
	}
}
output {
	elasticsearch {
		# ESIP地址與端口
		hosts => "192.168.136.104:9200"
		# ES索引名稱(自己定義的)
		index => "tensquare"
		# 自增ID編號
		document_id => "%{id}"
		document_type => "article"
	}
	stdout {
		# 以JSON格式輸出
		codec => json_lines
	}
}

運行

# 將配置放入logstash.conf,然後執行logstash -f命令並指定執行的文件爲logstash.conf
logstash -f logstash.conf
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章