java連接ElasticSearch集群操作
我就廢話不多說了,大家還是直接看代碼吧~
/* *es配置類 * */ @Configuration public class ElasticSearchDataSourceConfigurer { private static final Logger LOG = LogManager.getLogger(ElasticSearchDataSourceConfigurer.class); @Bean public TransportClient getESClient() { //設(shè)置集群名稱 Settings settings = Settings.builder().put("cluster.name", "bigData-cluster").put("client.transport.sniff", true).build(); //創(chuàng)建client TransportClient client = null; try { client = new PreBuiltTransportClient(settings) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(""), 9300));//集群ip LOG.info("ESClient連接建立成功"); } catch (UnknownHostException e) { LOG.info("ESClient連接建立失敗"); e.printStackTrace(); } return client; } }
/** * Simple to Introduction * * @Description: [添加類] */ @Repository public class UserDaoImpl implements userDao { private static final String INDEXNAME = "user";//小寫 private static final String TYPENAME = "info"; @Resource TransportClient transportClient; @Override public int addUser(User[] user) { IndexResponse indexResponse = null; int successNum = 0; for (int i = 0; i < user.length; i++) { UUID uuid = UUID.randomUUID(); String str = uuid.toString(); String jsonValue = null; try { jsonValue = JsonUtil.object2JsonString(user[i]); if (jsonValue != null) { indexResponse = transportClient.prepareIndex(INDEXNAME, TYPENAME, str).setSource(jsonValue) .execute().actionGet(); successNum++; } } catch (JsonProcessingException e) { e.printStackTrace(); } } return successNum; } }
/** *批量插入 */ public static void bathAddUser(TransportClient client, List<User> users) { BulkRequestBuilder bulkRequest = transportClient.prepareBulk(); for (int i = 0; i < users.size(); i++) { UUID uuid = UUID.randomUUID(); String str = uuid.toString(); String jsonValue = null; try { jsonValue = JsonUtil.object2JsonString(users.get(i)); } catch (JsonProcessingException e) { e.printStackTrace(); } bulkRequest.add(client.prepareIndex("user", "info", str).setSource(jsonValue)); // 一萬條插入一次 if (i % 10000 == 0) { bulkRequest.execute().actionGet(); } System.out.println("已經(jīng)插入第" + i + "多少條"); } }
補充知識:使用java創(chuàng)建ES(ElasticSearch)連接池
1.首先要有一個創(chuàng)建連接的工廠類
package com.aly.util; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; /** * EliasticSearch連接池工廠對象 * @author 00000 * */ public class EsClientPoolFactory implements PooledObjectFactory<RestHighLevelClient>{ @Override public void activateObject(PooledObject<RestHighLevelClient> arg0) throws Exception { System.out.println("activateObject"); } /** * 銷毀對象 */ @Override public void destroyObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception { RestHighLevelClient highLevelClient = pooledObject.getObject(); highLevelClient.close(); } /** * 生產(chǎn)對象 */ // @SuppressWarnings({ "resource" }) @Override public PooledObject<RestHighLevelClient> makeObject() throws Exception { // Settings settings = Settings.builder().put("cluster.name","elasticsearch").build(); RestHighLevelClient client = null; try { /*client = new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"),9300));*/ client = new RestHighLevelClient(RestClient.builder( new HttpHost("192.168.1.121", 9200, "http"), new HttpHost("192.168.1.122", 9200, "http"), new HttpHost("192.168.1.123", 9200, "http"), new HttpHost("192.168.1.125", 9200, "http"), new HttpHost("192.168.1.126", 9200, "http"), new HttpHost("192.168.1.127", 9200, "http"))); } catch (Exception e) { e.printStackTrace(); } return new DefaultPooledObject<RestHighLevelClient>(client); } @Override public void passivateObject(PooledObject<RestHighLevelClient> arg0) throws Exception { System.out.println("passivateObject"); } @Override public boolean validateObject(PooledObject<RestHighLevelClient> arg0) { return true; } }
2.然后再寫我們的連接池工具類
package com.aly.util; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.elasticsearch.client.RestHighLevelClient; /** * ElasticSearch 連接池工具類 * * @author 00000 * */ public class ElasticSearchPoolUtil { // 對象池配置類,不寫也可以,采用默認(rèn)配置 private static GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); // 采用默認(rèn)配置maxTotal是8,池中有8個client static { poolConfig.setMaxTotal(8); } // 要池化的對象的工廠類,這個是我們要實現(xiàn)的類 private static EsClientPoolFactory esClientPoolFactory = new EsClientPoolFactory(); // 利用對象工廠類和配置類生成對象池 private static GenericObjectPool<RestHighLevelClient> clientPool = new GenericObjectPool<>(esClientPoolFactory, poolConfig); /** * 獲得對象 * * @return * @throws Exception */ public static RestHighLevelClient getClient() throws Exception { // 從池中取一個對象 RestHighLevelClient client = clientPool.borrowObject(); return client; } /** * 歸還對象 * * @param client */ public static void returnClient(RestHighLevelClient client) { // 使用完畢之后,歸還對象 clientPool.returnObject(client); } }
以上這篇java連接ElasticSearch集群操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java注解@Transactional事務(wù)類內(nèi)調(diào)用不生效問題及解決辦法
這篇文章主要介紹了Java注解@Transactional事務(wù)類內(nèi)調(diào)用不生效問題及解決辦法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05Springboot實現(xiàn)Java阿里短信發(fā)送代碼實例
這篇文章主要介紹了springboot實現(xiàn)Java阿里短信發(fā)送代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02Java數(shù)據(jù)結(jié)構(gòu)順序表用法詳解
順序表是計算機內(nèi)存中以數(shù)組的形式保存的線性表,線性表的順序存儲是指用一組地址連續(xù)的存儲單元依次存儲線性表中的各個元素、使得線性表中在邏輯結(jié)構(gòu)上相鄰的數(shù)據(jù)元素存儲在相鄰的物理存儲單元中,即通過數(shù)據(jù)元素物理存儲的相鄰關(guān)系來反映數(shù)據(jù)元素之間邏輯上的相鄰關(guān)系2021-10-10java datetime數(shù)據(jù)類型去掉時分秒的案例詳解
在Java中,如果我們想要表示一個日期而不包括時間(時分秒),我們通常會使用java.time包中的LocalDate類,這篇文章主要介紹了java datetime數(shù)據(jù)類型去掉時分秒,需要的朋友可以參考下2024-06-06Spring Boot集成MyBatis實現(xiàn)通用Mapper的配置及使用
關(guān)于MyBatis,大部分人都很熟悉。MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。這篇文章主要介紹了Spring Boot集成MyBatis實現(xiàn)通用Mapper,需要的朋友可以參考下2018-08-08