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. mysql 安装避坑指南 ,mysql 安装后不能启动, mysql 指定版本安装,mysql 5.7.39版本安装,mysql 5.7.36版本安装

    mysql 安装后不能启动,报错如下:请参照本说明第7条的办法解决.mysqld.service: Control process exited, code=exited status=1Please ...

  2. MongoDB 6.0 单实例基于用户角色实现授权登录

    现代数据库系统能够存储和处理大量数据.因此,由任何一个用户单独负责处理与管理数据库相关的所有活动的情况相对较少.通常,不同的数据库用户需要对数据库的某些部分具有不同级别的访问权限:某些用户可能只需要读 ...

  3. jdk11的HttpClient

    我们都知道在jdk11之前都在用okhttp或者org.apache.httpcomponents  其实早在jdk9的时候这个方案就在孵化中 上面的截图来自openjdk的官网,注:openjdk是 ...

  4. java方法的定义与执行

    java中的方法在类中定义. 定义方法格式: 访问修饰符    返回值类型    方法名(参数列表){   ...  执行内容  ...   return 返回值; } 访问修饰符:表示方法在哪里能被 ...

  5. System类的方法

    1.exit() 2.currentTimeMills() 代码练习

  6. iMessage群发,iMessage群发功能,iMessage群发功能设计,iMessage群发系统

    在数字通讯时代,群发消息已经成为我们日常生活中不可或缺的一部分,无论是商务.社交还是日常沟通,群发功能都大大提高了消息传递的效率和便利性. 而在众多的通讯软件中,iMessage无疑是其中的佼佼者,今 ...

  7. LLaMA大型语言模型

    LLaMA (Large Language Model Meta AI)是Meta公司发布的大型语言模型系列,近日LLaMA种子文件被合并到了GitHub 上,同时一些项目维护者给予了批准,目前该项目 ...

  8. uniapp-welive仿微信/抖音直播带货|uni-app+vue3+pinia短视频直播商城

    基于uniapp+vue3+uv-ui跨端H5+小程序+App短视频+直播带货商城Uniapp-WeLive. uni-welive一款全新基于uniapp+vue3+pinia+vk-uview等技 ...

  9. 前端 Git 使用约定

    前端 Git 使用约定 背景 开发前端项目,有以下困惑: 使用哪个分支开发,哪个分支发布 修复线上bug的流程是什么,如何避免修复完了下次却又出现了 cms分支有十多个,是否都有用 如何快速找到之前某 ...

  10. DVWA SQL Injection(blind)(SQL盲注)全等级

    SQL Injection(blind)(盲注) 目录: SQL Injection(blind)(盲注) 1. Low 2.Medium 3.High 4.Impossible 5.运用sqlmap ...