您的位置:首页 > 编程语言 > Java开发

SpringBoot集成ElasticSearch

2017-09-28 10:03 477 查看
根据项目要求集成ES

简单DEMO例子 

maven

只需要引入es相关即可
<!-- elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

yaml

基本配置集群名称,集群ip
spring:
data:
elasticsearch:
cluster-name: SOC-15
cluster-nodes: 10.2.4.15:9300,10.2.4.42:9300,10.2.4.43:9300

ElasticsearchRepository

这个是必须的,respository提供了一些基本的方法可以直接使用,如果需要自己定义方法,则在下面的类里面增加方法即可。
import neusoft.beans.EsBean;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-9-27
* Time: 下午4:02
* To change this template use File | Settings | File Templates.
*/
public interface EsBeanRepository extends ElasticsearchRepository<EsBean,String> {

}


与ES交互的Bean

Document注解里面有很多参数,基本的配置有索引名称,库名称,还有分片等等。
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

import java.io.Serializable;

/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-9-27
* Time: 下午4:07
* To change this template use File | Settings | File Templates.
*/
@Document(indexName="test",type="test")
public class EsBean implements Serializable {
@Id
public String id;

@Field
public int gs;

@Field
public int study;

}

Service实现

下面的调用是基本的api调用,只是一个save操作
import com.alibaba.fastjson.JSON;
import neusoft.beans.EsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-9-27
* Time: 下午4:34
* To change this template use File | Settings | File Templates.
*/
@Service
@EnableElasticsearchRepositories
public class EsServiceImpl implements EsService{
@Resource
private EsBeanRepository esBeanRepository;

@Override
public String queryInfoById(String id) {
System.out.println("id:" + id);
//        EsBean eb = (EsBean)esBeanRepository.findOne(id);
EsBean eb = new EsBean();
eb.gs = 250;
eb.study=250;
esBeanRepository.save(eb);
String value = JSON.toJSONString(eb);
System.out.println("value:"+value);
return value;
}
}

结果



其他

源码在个人的github上,感兴趣的可以看看学习 个人Github:https://github.com/GinoyJda/  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: