文章目录
- 一、介绍
- 1.pom依赖
- 2.yml配置文件
- 主启动类
- 二、代码
- 1.Repository
- 2.Service
- 3.ServiceImpl
- 4.Controller
- 三、使用Logstash同步MySQL数据到ES
- 1.简单介绍一下
- 2.启动测试
- 3.创建mysql.conf
- Bug
一、介绍
我只用的ES版本是7.8
1.pom依赖
# SpringBoot版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
</parent>
# SpringCloud 版本
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<!-- <version>Greenwich.SR1</version>-->
<version>Hoxton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
# SpringDataElasticsearch
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
2.yml配置文件
spring:
elasticsearch:
rest:
uris: http://192.168.103.10:9200
主启动类
因为没有用到数据库,所以没有配置数据源,如果不排除,启动会报错
@EnableEurekaClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SearchApplication {
public static void main(String[] args) {
SpringApplication.run(SearchApplication.class);
}
@Bean
public IdWorker idWorker(){
return new IdWorker(1,1);
}
}
二、代码
1.Repository
直接继承ElasticsearchRepository<ESArticle, String>
,泛型是实体类,String是ID主键的类型。
package com.lsh.repository;
import com.lsh.model.ESArticle;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* @author :LiuShihao
* @date :Created in 2020/10/30 10:16 上午
* @desc :
*/
public interface ArticleRepository extends ElasticsearchRepository<ESArticle, String> {
/**
* 添加如下自定义方法
* @param title
* @param content
* @param pageable
* @return
*/
public Page<ESArticle> findByTitleOrContentLike(String title, String content, Pageable pageable);
}
2.Service
public interface ArticleService {
void save(ESArticle article);
List<ESArticle> findAll();
Page<ESArticle> findByKey(String key, int page, int size);
}
3.ServiceImpl
package com.lsh.service.impl;
import com.lsh.model.ESArticle;
import com.lsh.repository.ArticleRepository;
import com.lsh.service.ArticleService;
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.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author :LiuShihao
* @date :Created in 2020/10/30 10:16 上午
* @desc :
*/
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
ArticleRepository repository;
/**
* 向ES中添加数据
* @param article
*/
@Override
public void save(ESArticle article){
repository.save(article);
}
/**
* 查询ES中的所有数据
* @return
*/
@Override
public List<ESArticle> findAll() {
Iterable<ESArticle> all = repository.findAll();
List<ESArticle> articles = new ArrayList<>();
Iterator<ESArticle> iterator = all.iterator();
while (iterator.hasNext()){
ESArticle article = iterator.next();
articles.add(article);
}
return articles;
}
/**
* 根据条件查询ES中的数据 分页
* @param key
* @param page
* @param size
* @return
*/
@Override
public Page<ESArticle> findByKey(String key, int page, int size) {
Pageable pageable = PageRequest.of(page-1, size);
if (key == null){
Page<ESArticle> all = repository.findAll(pageable);
return all;
}
return repository.findByTitleOrContentLike(key, key, pageable);
}
}
4.Controller
package com.lsh.controller;
import com.lsh.model.ESArticle;
import com.lsh.service.ArticleService;
import com.lsh.util.PageResult;
import com.lsh.util.ResultObject;
import com.lsh.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author :LiuShihao
* @date :Created in 2020/10/30 10:18 上午
* @desc :
*/
@RestController
@RequestMapping("/article")
@CrossOrigin
public class ArticleController {
@Autowired
ArticleService articleService;
@GetMapping
public ResultObject findAll(){
List<ESArticle> lists = articleService.findAll();
return new ResultObject(true, StatusCode.OK, "查询所有成功",lists);
}
@PostMapping
public ResultObject save(@RequestBody ESArticle article) {
articleService.save(article);
return new ResultObject(true, StatusCode.OK, "添加成功");
}
@GetMapping(value = "/{key}/{page}/{size}")
public ResultObject findByKey(@PathVariable String key, @PathVariable int page, @PathVariable int size){
if ("null".equals(key)){
key = null;
}
Page<ESArticle> pageData = articleService.findByKey(key, page, size);
return new ResultObject(true, StatusCode.OK, "查询成功", new PageResult<ESArticle>(pageData.getTotalElements(), pageData.getContent()));
}
}
三、使用Logstash同步MySQL数据到ES
Logstash的版本与ES的版本对应,我安装的也是7.8
1.简单介绍一下
Logstash是一款轻量级的日志搜集处理框架,可以方便的把分散的、多样化的日志搜集
起来,并进行自定义的处理,然后传输到指定的位置,比如某个服务器或者文件。
Logstash是一款开源的数据收集引擎,具备实时管道处理能力。简单来说,logstash作为数据源与数据存储分析工具之间的桥梁,结合 ElasticSearch以及Kibana,能够极大方便数据的处理与分析。
2.启动测试
安装后进入bin目录,启动测试./logstash -e 'input { stdin { } } output { stdout {} }'
-e 执行
–config 或 -f 配置文件,后跟参数类型可以是一个字符串的配置或全路径文件名或全路径
路径(如:/etc/logstash.d/,logstash会自动读取/etc/logstash.d/目录下所有*.conf 的文本文件,然后在自己内存里拼接成一个完整的大配置文件再去执行)
logstash会加上日期和主机名(IP)输出到终端。这就是Logstash最基本的工作模式,接受输入,然后将信息加工后放入到输出。
3.创建mysql.conf
(1)在logstash安装目录下创建文件夹mysqletc (名称随意)
(2)文件夹下创建mysql.conf (名称随意) 。
注意:需要用到MySQL数据库连接的jar包。
注意:根据自己的配置修改mysql.conf的内容
Logstash就是通过这个mysql.conf配置文件将MySQL中的数据每分钟查询出来在写入到ES中的
input {
jdbc {
# mysql jdbc connection string to our backup databse
jdbc_connection_string => "jdbc:mysql://116.62.13.104:3306/tensquare_article?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF8"
# the user we wish to excute our statement as
jdbc_user => "root"
jdbc_password => "123456"
# the path to our downloaded jdbc driver
jdbc_driver_library => "/usr/local/logstash-7.8.0/mysqletc/mysql-connector-java-5.1.46.jar"
# the name of the driver class for mysql
jdbc_driver_class => "com.mysql.jdbc.Driver"
jdbc_paging_enabled => "true"
jdbc_page_size => "20"
#以下对应着要执行的sql的绝对路径。
#statement_filepath => ""
statement => "select id,title,content,state from tb_article"
#定时字段 各字段含义(由左至右)分、时、天、月、年,全部为*默认含义为每分钟都更新(测试结果,不同的话请留言指出)
schedule => "* * * * *"
}
}
output {
elasticsearch {
#ESIP地址与端口
hosts => "192.168.103.10:9200"
#ES索引名称(自己定义的)
index => "tensquare_article"
#自增ID编号
document_id => "%{id}"
document_type => "article"
}
stdout {
#以JSON格式输出
codec => json_lines
}
}
Bug
有一个问题,如果MySQL数据库中的数据发生了删除和更新,ES中的数据无法更新与MySQL一致。
解决方法:
在MySQL数据进行删改操作后,同时使用SpringDataElasticsearch对ES进行同样的操作。来保证数据的一致。