![a76ff3a8f84e6dc10fcc1b0d872d7b68.png](https://i-blog.csdnimg.cn/blog_migrate/b6fcefcfd4d7d2216d5cbc9c0e05896c.png)
1)使用Spring Boot的DevTools实现热部署
在项目创建之初我们就已经在pom文件中引入了spring-boot-devtools
这个Spring Boot提供的热部署插件,但是可能会遇到热部署不生效的问题,如果你使用的是Intellij Idea开发工具,参见《使用Spring Boot Devtools实现热部署》。
2)创建数据表的实体类
虽说我们要做的是对于博客的全文检索,但是在用户没有给定搜索条件之前,我们还是应该使用Mysql通过主键索引的方式查询出博客数据(当然,简单起见这里没有实现分页查询功能),Mysql的主键查询是很快的,无需使用ES;当用户输入查询条件时,表示需要进行全文检索时我们才使用ES。
Mysql自不用说,ES也是需要实体类来承载数据的,他们的字段结构都是相同的,不同的只是标注在字段上的注解,下面来快速创建他们的实体类:
2.1)创建博客文章Mysql实体类
@Data
@Table(name = "t_article") // 指定实体类对应的数据表
@Entity
public class MysqlArticle {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 使用数据表定义的增长策略(自增)
private Integer id; // 文章ID
private String author; // 文章作者
private String title; // 文章标题
// String类型默认映射的是varchar类型,content字段使用到了mediumtext,需要显式指定一下
@Column(name = "content", columnDefinition = "mediumtext")
private String content; // 文章正文内容
private Date createTime; // 文章创建时间
private Date updateTime; // 文章更新时间
}
2.2)创建博客文章ElasticSearch实体类
@Data
// 指定实体类对应ES的索引名称为blog,类型type是文档类型,使用服务器远程配置
// 为避免每次重启项目都将ES中的数据删除后再同步,createIndex指定为false
@Document(indexName = "blog", type = "_doc",
useServerConfiguration = true, createIndex = false)
public class ElasticArticle {
@Id // org.springframework.data.annotation.Id
private Integer id; // 文章ID
// 指定字段对应的ES类型是Text,analyzer指定分词器为ik_max_word
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String author; // 文章作者
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String title; // 文章标题
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String content; // 文章正文内容
// 指定字段对应ES中的类型是Date,使用自定义的日期格式化,pattern指定格式化
// 规则是“日期时间”或“日期”或“时间毫秒”
@Field(type = FieldType.Date, format = DateFormat.custom,
pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
private Date createTime; // 文章创建时间
@Field(type = FieldType.Date, format = DateFormat.custom,
pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
private Date updateTime; // 文章更新时间
}
3)编写Mysql和ES的数据操作接口
由于使用了Spring-Data-JPA
,这项工作将十分简单,只需要自建接口继承自对应的JpaRepository
和ElasticsearchRepository
接口即可。
创建Mysql数据访问接口
public interface MysqlArticleRepository
extends JpaRepository<MysqlArticle, Integer> {
}
创建ES数据访问接口
public interface ElasticArticleRepository
extends ElasticsearchRepository<ElasticArticle, Integer> {
}