记录一下SpringBoot(2.0.4.RELEASE)+Elasticsearch(6.2.4)+Gradle整合的一个小例子。
1.在Gradle内加入相关jar包的依赖:
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-data-jpa') //添加Spring Data Elasticsearch依赖
compile('org.springframework.boot:spring-boot-starter-data-elasticsearch') //添加JNA依赖
compile('net.java.dev.jna:jna:4.3.0') compile('com.google.guava:guava:26.0-jre')
2.创建实体对象,并加入Elasticsearch的相关注释:
package com.wey.pojo.blog; import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName="blogcenter",type="blog")
//indexName索引名称 可以理解为数据库名 必须为小写不然会报
public class Blog implements Serializable{ private static final long serialVersionUID = 1L; @Id
private String id;
private String title;
private String summary;
private String content; protected Blog() {
super();
} public Blog(String title, String summary, String content) {
this.title = title;
this.summary = summary;
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 getSummary() {
return summary;
} public void setSummary(String summary) {
this.summary = summary;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} @Override
public String toString() {
return "Blog [id=" + id + ", title=" + title + ", summary=" + summary + ", content=" + content + "]";
}
}
3.创建Repository
package com.wey.repository; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component; import com.wey.pojo.blog.Blog; public interface BlogRepository extends ElasticsearchRepository<Blog, String> {
}
4.创建Controller并简单的实现添加及查询
@RestController
@RequestMapping("/blogs")
public class BlogController {
@Autowired
BlogRepository blogRepository; @RequestMapping("/add")
public Blog add(Blog blog) {
return blogRepository.save(blog);
} @GetMapping
public List<Blog> findAll(){
Iterable<Blog> elements = blogRepository.findAll();
ArrayList<Blog> list = Lists.newArrayList(elements);
return list;
} @GetMapping("/delete/{id}")
public String remove(@PathVariable(name="id") String id) {
blogRepository.deleteById(id);
return "success";
}
}
5.打开下载好的Elasticsearch(6.2.4)内的elasticsearch.bat文件,等待一会儿直到启动完成。
6.启动SpringBoot应用并简单的测试
添加一条数据:
查询所有数据: