Java ElasticSearch 操作
pom 文件中添加:

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.3.2</version>
</dependency>
如果是SpringBoot工程(这里不是SpringBoot工程,是自己写的简单Demo),在pom文件中的<properties>标签中添加<elasticsearch.version>6.1.4</elasticsearch.version>,否则可能会导致ElasticSearch依赖包的版本不一致使程序无法正常运行。
注意版本是6.3.2,6.1.4版本不支持创建索引
Log2ESUtil代码:

package com.sux.demo.utils; import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; public class Log2ESUtil {
private static final Logger log = LoggerFactory.getLogger(Log2ESUtil.class); RestHighLevelClient client = null; private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ"); public void initES() {
try {
client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("34.8.8.93", 24100, "http"),
new HttpHost("34.8.8.94", 24100, "http"),
new HttpHost("34.8.8.95", 24100, "http"),
new HttpHost("34.8.8.96", 24100, "http"),
new HttpHost("34.8.8.98", 24100, "http"),
new HttpHost("34.8.8.99", 24100, "http"))
.setMaxRetryTimeoutMillis(5 * 60 * 1000));//超时时间设为5分钟
log.info("Log2ESService init 成功");
} catch (Exception e) {
log.error("Log2ESService init 失败", e);
}
} public void closeES() {
try {
client.close();
log.info("Log2ESService close 成功");
} catch (Exception e) {
log.error("Log2ESService close 失败", e);
}
} public void log2ES(boolean success, String index, String app, String msg) throws Exception {
try {
String doc = "doc";
String id = UUID.randomUUID().toString(); //保存到ES的数据
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("app", app);
if (success) {
jsonMap.put("operation_result", "成功");
} else {
jsonMap.put("operation_result", "失败");
}
jsonMap.put("message", msg);
jsonMap.put("log_time", simpleDateFormat.format(new Date())); IndexRequest indexRequest = new IndexRequest(index, doc, id)
.source(jsonMap);
client.index(indexRequest); //log.info("Log2ESService log2ES 成功,数据:" + jsonMap.toString());
} catch (Exception e) {
log.error("Log2ESService log2ES 失败", e);
}
} public boolean indexExists(String indexName) throws IOException {
GetIndexRequest getIndexRequest = new GetIndexRequest();
getIndexRequest.indices(indexName);
return client.indices().exists(getIndexRequest);
} public boolean createIndex(String indexName) throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName); // 配置映射关系
Map<String, Object> mappings = new HashMap<>(); Map<String, Object> type = new HashMap<>();
mappings.put("doc", type);
type.put("dynamic", false); //说明: Map<String, Object> properties = new HashMap<>();
type.put("properties", properties); //文档的id映射
Map<String, Object> idProperties = new HashMap<>();
idProperties.put("type", "integer");
idProperties.put("store", "true");
properties.put("id", idProperties); // 文档的其他字段映射
Map<String, Object> moreProperties = new HashMap<>();
moreProperties.put("type", "text"); //说明:
moreProperties.put("store", "true"); //说明:
properties.put("app", moreProperties); moreProperties = new HashMap<>();
moreProperties.put("type", "text");
moreProperties.put("store", "true");
properties.put("operation_result", moreProperties); moreProperties = new HashMap<>();
moreProperties.put("type", "text");
moreProperties.put("store", "true");
properties.put("message", moreProperties); moreProperties = new HashMap<>();
moreProperties.put("type", "date");
moreProperties.put("store", "true");
moreProperties.put("format", "yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
properties.put("log_time", moreProperties); createIndexRequest.mapping("doc", mappings); CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest);
return createIndexResponse.isAcknowledged();
} public boolean deleteIndex(String indexName) throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);
return deleteIndexResponse.isAcknowledged();
} }
测试代码:
创建索引:

package com.sux.demo; import com.sux.demo.utils.Log2ESUtil;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException; public class TestES_CreateIndex {
private static final Logger log = LoggerFactory.getLogger(TestES_CreateIndex.class); private static Log2ESUtil log2ESUtil = new Log2ESUtil(); private static String indexName = "sux-test"; private static String app = "sux-test"; public static void main(String[] args) throws Exception {
try {
PropertyConfigurator.configure("src/main/resources/log4j.properties"); log2ESUtil.initES(); createIndex(); log2ESUtil.closeES();
} catch (Exception e) {
log.error("TestES_CreateIndex 出错", e);
}
} private static void createIndex() throws IOException {
if (!log2ESUtil.indexExists(indexName)) {
boolean result = log2ESUtil.createIndex(indexName);
if (result) {
log.info("创建索引" + indexName + "成功!");
} else {
log.info("创建索引" + indexName + "失败!");
}
} else {
System.out.println("索引" + indexName + "已存在,不需要创建");
}
}
}
删除索引:

package com.sux.demo; import com.sux.demo.utils.Log2ESUtil;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.IOException; public class TestES_DeleteIndex {
private static final Logger log = LoggerFactory.getLogger(TestES_DeleteIndex.class); private static Log2ESUtil log2ESUtil = new Log2ESUtil(); private static String indexName = "sux-test"; public static void main(String[] args) throws Exception {
try {
PropertyConfigurator.configure("src/main/resources/log4j.properties"); log2ESUtil.initES(); if (log2ESUtil.indexExists(indexName)) {
boolean result = log2ESUtil.deleteIndex(indexName);
if (result) {
log.info("删除索引" + indexName + "成功!");
} else {
log.info("删除索引" + indexName + "失败!");
}
} else {
log.info("索引" + indexName + "不存在,不需要删除!");
} log2ESUtil.closeES();
} catch (Exception e) {
log.error("TestES_DeleteIndex 出错", e);
}
} }
单线程数据写入:

package com.sux.demo; import com.sux.demo.utils.Log2ESUtil;
import com.sux.demo.utils.Speed;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor; public class TestES_SingleInsert {
private static final Logger log = LoggerFactory.getLogger(TestES_Insert.class); private static Log2ESUtil log2ESUtil = new Log2ESUtil(); private static String indexName = "sux-test"; private static String app = "sux-test"; public static void main(String[] args) throws Exception {
try {
PropertyConfigurator.configure("src/main/resources/log4j.properties"); log2ESUtil.initES(); long startTime = System.currentTimeMillis(); int n = 200;
for (int i = 1; i <= n; i++) {
log2ESUtil.log2ES(true, indexName, app, "单线程插入数据" + i);
if (i % 50 == 0) {
log.info("count=" + i);
}
Speed.addCount();
} long endTime = System.currentTimeMillis(); double speed = Speed.getCount() / (double) ((endTime - startTime) / 1000.0);
System.out.println(" 数据插入速度:" + (int) speed + " 条/秒"); log2ESUtil.closeES();
} catch (Exception e) {
log.error("TestES_SingleInsert 出错", e);
}
}
}
多线程数据写入:

package com.sux.demo; import com.sux.demo.utils.Log2ESUtil;
import com.sux.demo.utils.Speed;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor; public class TestES_Insert {
private static final Logger log = LoggerFactory.getLogger(TestES_Insert.class); private static Log2ESUtil log2ESUtil = new Log2ESUtil(); private static String indexName = "sux-test"; private static String app = "sux-test"; private static ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(50); public static void main(String[] args) throws Exception {
try {
PropertyConfigurator.configure("src/main/resources/log4j.properties"); log2ESUtil.initES(); long startTime = System.currentTimeMillis(); int n = 10000;
CountDownLatch countDownLatch = new CountDownLatch(n);
for (int i = 1; i <= n; i++) {
ESInsertRunnable esInsertRunnable = new ESInsertRunnable(countDownLatch, log2ESUtil, i, "多线程插入数据");
threadPool.submit(esInsertRunnable);
} try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} long endTime = System.currentTimeMillis(); double speed = Speed.getCount() / (double) ((endTime - startTime) / 1000.0);
System.out.println(" 数据插入速度:" + (int) speed + " 条/秒"); log2ESUtil.closeES();
threadPool.shutdown();
} catch (Exception e) {
log.error("TestES_Insert 出错", e);
}
}
} class ESInsertRunnable implements Runnable {
private static final Logger log = LoggerFactory.getLogger(ESInsertRunnable.class); private CountDownLatch countDownLatch; private Log2ESUtil log2ESUtil; private int num; private static String indexName = "sux-test"; private static String app = "sux-test"; private String msg; public ESInsertRunnable(CountDownLatch countDownLatch, Log2ESUtil log2ESUtil, int num, String msg) {
this.countDownLatch = countDownLatch;
this.log2ESUtil = log2ESUtil;
this.num = num;
this.msg = msg;
} public void run() {
try {
log2ESUtil.log2ES(true, indexName, app, msg + num);
if (countDownLatch.getCount() % 500 == 0) {
log.info("count=" + countDownLatch.getCount());
}
Speed.addCount();
} catch (Exception e) {
log.error("TestES_Insert 异常", e);
} countDownLatch.countDown();
}
}
实际测试性能(使用现网es集群测试):
单线程:20条/秒
线程池(50个线程):500条/秒
Java ElasticSearch 操作的更多相关文章
- 使用Java客户端操作elasticsearch(二)
承接上文,使用Java客户端操作elasticsearch,本文主要介绍 常见的配置 和Sniffer(集群探测) 的使用. 常见的配置 前面已介绍过,RestClientBuilder支持同时提供一 ...
- Elasticsearch入门系列~通过Java一系列操作Elasticsearch
Elasticsearch索引的创建.数据的增删该查操作 上一章节已经在Linux系统上安装Elasticsearch并且可以外网访问,这节主要通过Java代码操作Elasticsearch 1.创建 ...
- Java实现操作dos命令
java实现操作dos命令的两种方式 1.读取文件中的命令 package com; import java.io.InputStream; public class cmd { public sta ...
- JAVA 链表操作:循环链表
主要分析示例: 一.循环链表简述 二.单链表循环链表 三.双链表循环链表 一.循环链表简述 循环链表即链表形成了一个循环的结构,尾节点不再指向NULL,而是指向头节点HEAD,此时判定链表的结束是尾节 ...
- java日期操作大全
摘自(http://www.blogjava.net/i369/articles/83483.html) java日期操作 大全 先来一个: 取得指定月份的第一天与取得指定月份的最后一天 http ...
- Java CSV操作(导出和导入)
Java CSV操作(导出和导入) CSV是逗号分隔文件(Comma Separated Values)的首字母英文缩写,是一种用来存储数据的纯文本格式,通常用于电子表格或数据库软件.在 CSV文件 ...
- Java开发--操作MongoDB
http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过前一篇文章我们 ...
- hive-通过Java API操作
通过Java API操作hive,算是测试hive第三种对外接口 测试hive 服务启动 package org.admln.hive; import java.sql.SQLException; i ...
- HDFS的Java客户端操作代码(HDFS的查看、创建)
1.HDFS的put上传文件操作的java代码: package Hdfs; import java.io.FileInputStream; import java.io.FileNotFoundEx ...
- Java文件操作源码大全
Java文件操作源码大全 1.创建文件夹 52.创建文件 53.删除文件 54.删除文件夹 65.删除一个文件下夹所有的文件夹 76.清空文件夹 87.读取文件 88.写入文件 99.写入随机文件 9 ...
随机推荐
- offline RL | TD3+BC:在最大化 Q advantage 时添加 BC loss 的极简算法
题目:A Minimalist Approach to Offline Reinforcement Learning ,NeurIPS 2021,8 7 7 5. pdf 版本:https://arx ...
- tortoiseGit教程(常用图文教程)
需求: gitTorise是git的比较好用的一个图形化工具,本文目的在于对tortoiseGit常见使用进行一个总结. 对于git常见的使用有: 1. 建立仓库 2. 提交代码 3. 更新代码 4. ...
- poj3710 (无向图删边博弈)
引入:树上删边博弈 例题:给出一个有 N个点的树,有一个点作为树的根节点.游戏者轮流从树中删去边,删去一条边后,不与根节点相连的部分将被移走.谁无法移动谁输. 结论:叶子节点的SG值为0:中间节点的S ...
- MDI窗体,打开子窗口的时候关闭其他子窗口及去除MainMenuStrip上自动产生的图标
去除MDI子窗体最大化后在MainMenuStrip上自动产生的图标和最大化.最小化以及关闭按钮在MainMenuStrip的ItemAdded事件中添加代码如下: 1 private void me ...
- Pipeline模式应用
本文记录Pipeline设计模式在业务流程编排中的应用 前言 Pipeline模式意为管道模式,又称为流水线模式.旨在通过预先设定好的一系列阶段来处理输入的数据,每个阶段的输出即是下一阶段的输入. 本 ...
- MySQL笔记01: MySQL入门_1.3 MySQL启动停止与登录
1.3 MySQL启动停止与登录 1.3.1 MySQL启动与停止 MySQL数据库分为客户端和服务器端,只有服务器端服务开启以后,才可以通过客户端登录MySQL服务端. 首先,以管理员身份运行&qu ...
- [AGC031E] Snuke the Phantom Thief
Problem Statement A museum exhibits $N$ jewels, Jewel $1, 2, ..., N$. The coordinates of Jewel $i$ a ...
- [GDOIpj222B] 网页浏览
第二题 网页浏览 提交文件: webpage.cpp 输入文件: webpage.in 输出文件: webpage.out 时间空间限制: 1 秒, 256 MB 我们在上网时,从一个网页上的链接打开 ...
- 1 HTTP是什么,HTTP不是什么?
HTTP是什么? HTTP 全程超文本传输协议(HyperText Transfer Protocol). 包含三部分:超文本.传输.协议. 1. 协议 HTTP是一个用在计算机世界里的协议.它使用计 ...
- MySQL索引命名规范
[强制]主键索引名为 pk_字段名:唯一索引名为 uk_字段名:普通索引名则为 idx_字段名 说明:pk_ 即 primary key:uk_ 即 unique key:idx_ 即 index 的 ...