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 ...
随机推荐
- 本地Stackedit Markdown编辑器设置远程访问
StackEdit是一个受欢迎的Markdown编辑器,在GitHub上拥有20.7k Star!,它支持将Markdown笔记保存到多个仓库,包括Gitee.GitHub和Gitea.此在线笔记工具 ...
- python之object类
object类 如python之继承及其实现方法这一节提到过的,object类是所有类的父类,因此所有类都有object类的属性和方法. 如python之封装及私有方法使用过的,内置函数dir()可以 ...
- 通用串口modbus转PROFIBUS DP网关PM-160在汽车行业的应用案例
通用串口modbus转PROFIBUS DP网关PM-160在汽车行业的应用案例 摘要: PM-160 是泗博公司生产的,可以实现串口与 PROFIBUS DP 协议数据通信的网关.此案例讲述的是通过 ...
- 一篇文章带你掌握Web自动化测试工具——Selenium
一篇文章带你掌握Web自动化测试工具--Selenium 在这篇文章中我们将会介绍Web自动化测试工具Selenium 如果我们需要学习相关内容,我们需要掌握Python,PyTest以及部分前端知识 ...
- 记录一次 postgresql 优化案例( volatility 自定义函数无法并行查询 )
同事最近做个金融适配项目,找我看条SQL,告知ORACLE跑1分钟,PG要跑30分钟(其实并没有这么夸张), 废话不说,贴慢SQL. 慢SQL(关键信息已经加密): explain analyze S ...
- .NET微信网页开发相关文章教程
前言 今天我们主要总结一下.NET微信网页开发的相关文章教程. 微信网页开发详细文档可以看微信官方文档:https://developers.weixin.qq.com/doc/offiaccount ...
- TIOBE 12月榜单: C# 即将成为2023 年度编程语言
TIOBE 公布了 2023 年 12 月的编程语言排行榜. 2022年C# 在挑战成为年度编程语言,但在最后一刻,C++出人意料地夺得了冠军.今年,我们确信 C# 将获胜成为2023年度编程语言.它 ...
- jvm的jshell,学生的工具
jshell 在我眼里,只能作为学校教学的一个玩具,事实上官方也做了解释,以下是官方的解释: 在学习编程语言时,即时反馈很重要,并且 它的 API.学校引用远离Java的首要原因 教学语言是其他语言 ...
- 【2】从零玩转OSS阿里云存储服务之Java代码操作-2-cong-ling-wan-zhuan-oss-a-li-yun-cun-chu-fu-wu-zhi-java-dai-ma-cao-zuo
title: [2]从零玩转OSS阿里云存储服务之Java代码操作 date: 2021-06-09 17:37:14.486 updated: 2021-12-26 17:43:12.779 url ...
- SPSC Queue
在多线程编程中,一个著名的问题是生产者-消费者问题 (Producer Consumer Problem, PC Problem). 对于这类问题,通过信号量加锁 (https://www.cnblo ...