参考书籍《spring boot2 精髓》
安装好elasticsearch 我这里是集群模式 (一个master 二个slave )
下面创建 bean, dao 和 controller,
bean
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import java.util.Date;
@Document(indexName = "springdata",type = "book")
public class BookEntity {
@Id
String id;
String name;
String message;
Date postDate;
String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getPostDate() {
return postDate;
}
public void setPostDate(Date postDate) {
this.postDate = postDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
dao
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface BookDao extends CrudRepository<BookEntity,String>{
public List<BookEntity> getByMessage(String key);
}
controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.swing.text.html.parser.Entity;
import java.util.List;
import java.util.Optional;
@RestController
public class ElasticController {
@Autowired
BookDao bookDao;
@RequestMapping("/springdata/book/{id}")
@ResponseBody
public BookEntity getBookById(@PathVariable String id){
List<BookEntity> bookEntities =bookDao.getByMessage("mysql从删库到跑路");
for (BookEntity bookEntity : bookEntities) {
System.out.println(bookEntity);
}
Optional<BookEntity> opt = bookDao.findById("1");
System.out.println(opt.orElseGet(null));
BookEntity bookEntity = opt.get();
System.out.println(bookEntity);
return bookEntity;
}
}
使用postman 工具插入一条json格式数据 127.0.0.1:9200/springdata/book/1 POST 方式提交
"id" : "1",
"name" : "Andyliu",
"message" : "mysql从删库到跑路",
"postDate" : "2018-03-10",
"type" : "book"
}
这里的json 和上边的bean 字段是对应的。
resource目录下添加下面二行(改成自己对应的集群名字和地址)
集群名字 和 master 节点地址。
spring.data.elasticsearch.cluster-name=es666
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
pom.xml添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.0.0.RELEASE</version
</dependency>
访问 localhost:8080/springdata/book/1 就能看到打印信息了。OK