java連接ElasticSearch集群操作
我就廢話不多說了,大家還是直接看代碼吧~
/* *es配置類 * */ @Configurationpublic class ElasticSearchDataSourceConfigurer { private static final Logger LOG = LogManager.getLogger(ElasticSearchDataSourceConfigurer.class); @Bean public TransportClient getESClient() { //設置集群名稱 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: [添加類] */@Repositorypublic class UserDaoImpl implements userDao { private static final String INDEXNAME = 'user';//小寫private static final String TYPENAME = 'info'; @ResourceTransportClient transportClient; @Overridepublic 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('已經插入第' + 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>{ @Overridepublic void activateObject(PooledObject<RestHighLevelClient> arg0) throws Exception {System.out.println('activateObject');}/** * 銷毀對象 */@Overridepublic void destroyObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {RestHighLevelClient highLevelClient = pooledObject.getObject();highLevelClient.close();}/** * 生產對象 *///@SuppressWarnings({ 'resource' })@Overridepublic 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);} @Overridepublic void passivateObject(PooledObject<RestHighLevelClient> arg0) throws Exception {System.out.println('passivateObject');} @Overridepublic 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 {// 對象池配置類,不寫也可以,采用默認配置private static GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();// 采用默認配置maxTotal是8,池中有8個clientstatic {poolConfig.setMaxTotal(8);}// 要池化的對象的工廠類,這個是我們要實現的類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集群操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. 一文秒懂idea的git插件跟翻譯插件2. 將properties文件的配置設置為整個Web應用的全局變量實現方法3. docker compose idea CreateProcess error=2 系統(tǒng)找不到指定的文件的問題4. Python語言規(guī)范之Pylint的詳細用法5. layui Ajax請求給下拉框賦值的實例6. XML入門的常見問題(四)7. JS中的常見數組遍歷案例詳解(forEach, map, filter, sort, reduce, every)8. python中pandas.read_csv()函數的深入講解9. python爬蟲利用代理池更換IP的方法步驟10. 使用FormData進行Ajax請求上傳文件的實例代碼
