接着上篇
通过上一篇对于es的初步认知,大体上知道es面对的实际问题,和数据结构。本篇文章将跟随本人学习步骤,开始使用es实现它的功能。话不多说,我们开始~
构建
集成项目,引入依赖第一步。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>集成完依赖,在yml配置es相关属性。启动项目连接到es集群。
spring:
data:
elasticsearch:
#集群名
cluster-name: elasticsearch
#连接节点,注意在集群中通信都是9300,否则会报错
cluster-nodes: localhost:9300
#是否本地连接
local: true
repositories:
#仓库中数据存储
enabled: true贴上es配置类的核心配置
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
/**
* 避免初始化失败,es和我项目中mq的netty依赖包冲突
*/
@PostConstruct
public void init(){
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
@Bean("esClient")
public Client getClient(){
try {
Settings settings = Settings.builder()
.put("client.transport.sniff", false)
.put("cluster.name", "集群名")
.build();
TransportClient client = new PreBuiltTransportClient(settings);
//设置ip和端口
String ips = esClientProperties.getIps();
String[] arr = ips.split(",");
for (String item : arr) {
String[] ipAndPort = item.split(":");
String ip = ipAndPort[0];
Integer port = Integer.parseInt(ipAndPort[1]);
client.addTransportAddress(new TransportAddress(InetAddress.getByName(ip), port));
}
if(client!=null){
log.info("-------->es链接成功<---------");
}
return client;
}catch (Exception e){
log.error("===>es初始化失败");
e.printStackTrace();
}
return null;
}使用es
我写了新增接口、删除接口、基础的查询所有接口。一下我展示发送的核心代码
BulkRequestBuilder bulkRequestBuilder = esClient.prepareBulk();
Map<String,Object> source = JSON.parseObject(JSON.toJSONString(message, SerializeConfig.getGlobalInstance()));
IndexRequestBuilder indexRequestBuilder = cmsEsClient.prepareIndex("索引名",
"类型", "唯一id").setSource(source);
bulkRequestBuilder.add(indexRequestBuilder);
BulkResponse response = bulkRequestBuilder.execute().actionGet();以后会更新本人学习的笔记和分享学习历程,点赞支持下,谢谢老板们~
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31509949/viewspace-3139764/ ,如需转载,请注明出处,否则将追究法律责任。