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 操作的更多相关文章

  1. 使用Java客户端操作elasticsearch(二)

    承接上文,使用Java客户端操作elasticsearch,本文主要介绍 常见的配置 和Sniffer(集群探测) 的使用. 常见的配置 前面已介绍过,RestClientBuilder支持同时提供一 ...

  2. Elasticsearch入门系列~通过Java一系列操作Elasticsearch

    Elasticsearch索引的创建.数据的增删该查操作 上一章节已经在Linux系统上安装Elasticsearch并且可以外网访问,这节主要通过Java代码操作Elasticsearch 1.创建 ...

  3. Java实现操作dos命令

    java实现操作dos命令的两种方式 1.读取文件中的命令 package com; import java.io.InputStream; public class cmd { public sta ...

  4. JAVA 链表操作:循环链表

    主要分析示例: 一.循环链表简述 二.单链表循环链表 三.双链表循环链表 一.循环链表简述 循环链表即链表形成了一个循环的结构,尾节点不再指向NULL,而是指向头节点HEAD,此时判定链表的结束是尾节 ...

  5. java日期操作大全

    摘自(http://www.blogjava.net/i369/articles/83483.html) java日期操作 大全 先来一个:  取得指定月份的第一天与取得指定月份的最后一天  http ...

  6. Java CSV操作(导出和导入)

    Java CSV操作(导出和导入)  CSV是逗号分隔文件(Comma Separated Values)的首字母英文缩写,是一种用来存储数据的纯文本格式,通常用于电子表格或数据库软件.在 CSV文件 ...

  7. Java开发--操作MongoDB

    http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过前一篇文章我们 ...

  8. hive-通过Java API操作

    通过Java API操作hive,算是测试hive第三种对外接口 测试hive 服务启动 package org.admln.hive; import java.sql.SQLException; i ...

  9. HDFS的Java客户端操作代码(HDFS的查看、创建)

    1.HDFS的put上传文件操作的java代码: package Hdfs; import java.io.FileInputStream; import java.io.FileNotFoundEx ...

  10. Java文件操作源码大全

    Java文件操作源码大全 1.创建文件夹 52.创建文件 53.删除文件 54.删除文件夹 65.删除一个文件下夹所有的文件夹 76.清空文件夹 87.读取文件 88.写入文件 99.写入随机文件 9 ...

随机推荐

  1. iOS APP包分析工具

    介绍 分享一款用于分析iOSipa包的脚本工具,使用此工具可以自动扫描发现可修复的包体积问题,同时可以生成包体积数据用于查看.这块工具我们团队内部已经使用很长一段时间,希望可以帮助到更多的开发同学更加 ...

  2. 字节跳动今日头条-抖音小程序序html富文本显示解决办法

    我所知道的,目前很多微信小程序开发者大都使用了"wxParse"的一个小程序端富文本解析代码,但对于开发抖音.今日头条小程序的人来说,貌似官方或者第三方也没有出一个解决html富文 ...

  3. 24、Go语言中的OOP思想

    1.是什么? OOP:面向对象 Go语言的解构体嵌套 1.模拟集成性:is - a type A struct { field } type B struct { A // 匿名字段 } 这种方式就会 ...

  4. SpringBoot项目整合微信登录

    一.开通微信登录 去微信开发者平台 1.注册 2.邮箱激活 3.完善开发者资料 4.开发者资质认证 准备营业执照,1-2个工作日审批.300元 5.创建网站应用 6.提交审核,7个工作日审批 7.熟悉 ...

  5. 手动安装pinia、给项目添加pinia实例

    用你喜欢的js包管理器安装pinia: yarn add pinia # 或者使用 npm npm install pinia 创建一个 pinia 实例 (根 store) 并将其传递给应用: 编辑 ...

  6. minio集群部署

    minio集群部署 1.说明: 安装前需要再添加一个磁盘后将磁盘挂载到/opt/minio目录,minio集群部署需要独占磁盘分区,不能使用文件夹代替. 运行分布式 MinIO 实例的服务器时间差不应 ...

  7. 深度解析 PyTorch Autograd:从原理到实践

    本文深入探讨了 PyTorch 中 Autograd 的核心原理和功能.从基本概念.Tensor 与 Autograd 的交互,到计算图的构建和管理,再到反向传播和梯度计算的细节,最后涵盖了 Auto ...

  8. 微信小程序实时噪声分贝

    为了做一个能够检测实时噪声分贝的小程序,网上找了很多例子,基本没有完整的代码,手写了一个,话不多说直接上效果图 实现实时录音的功能,并且能够根据声音分贝大小转动仪表盘显示实时的分贝,运用echart实 ...

  9. HTTP安全头部对jsp页面不生效

    本文于2016年4月底完成,发布在个人博客网站上. 考虑个人博客因某种原因无法修复,于是在博客园安家,之前发布的文章逐步搬迁过来. 诡异的问题 AppScan扫描报告中提示,Web服务器返回js.cs ...

  10. 2023-05-31:给定一个整数数组 A,你可以从某一起始索引出发,跳跃一定次数 在你跳跃的过程中,第 1、3、5... 次跳跃称为奇数跳跃 而第 2、4、6... 次跳跃称为偶数跳跃 你可以按以下

    2023-05-31:给定一个整数数组 A,你可以从某一起始索引出发,跳跃一定次数 在你跳跃的过程中,第 1.3.5... 次跳跃称为奇数跳跃 而第 2.4.6... 次跳跃称为偶数跳跃 你可以按以下 ...