ClientHelper.java
package es; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.plugin.deletebyquery.DeleteByQueryPlugin; import org.elasticsearch.shield.ShieldPlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.web.bind.annotation.InitBinder; /** * Es服务器初始化类 * @author Administrator * */ public class ClientHelper { //log4j private static Logger logger = LoggerFactory.getLogger(ClientHelper.class); //存放es集群名称以及嗅探设置 private Settings setting; //es客户端存放集合 private Map<String, Client> clientMap = new ConcurrentHashMap<String, Client>(); //ip端口号集合 private Map<String, Integer> ips = new HashMap<String, Integer>(); //默认集群名称 private String clusterName = "elasticsearch"; public ClientHelper(){ init(); } private static class ClientHolder{ private static final ClientHelper INSTANCE = new ClientHelper(); } public static final ClientHelper getInstance(){ return ClientHolder.INSTANCE; } /** * 得到客户端连接 * @return */ public Client getClient() { return getClient(clusterName); } /** * 得到客户端连接 * @return */ public Client getClient(String clusterName) { Client c = clientMap.get(clusterName); return c; } /** * 初始化EsClient */ public void init(){ Resource resource = new ClassPathResource("config/config.properties"); try { Properties properties = PropertiesLoaderUtils.loadProperties(resource); String host = properties.getProperty("host"); String port = properties.getProperty("port"); clusterName = properties.getProperty("clusterName"); String [] hosts = host.split(";"); String [] ports = port.split(";"); for(int i=0;i< hosts.length;i++){ int portNo = Integer.valueOf(ports[i].trim()); ips.put(hosts[i].trim(), portNo); } } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } setting = Settings.settingsBuilder() .put("client.transport.sniff",true) .put("cluster.name",clusterName) .build(); addClient(setting, getAllAddress(ips)); } /** * 查询所有ES服务器地址 * * @return */ public List<InetSocketTransportAddress> getAllAddress(Map<String, Integer>ips){ List<InetSocketTransportAddress> addressList = new ArrayList<InetSocketTransportAddress>(); for(String ip:ips.keySet()){ try { addressList.add(new InetSocketTransportAddress(InetAddress.getByName(ip),ips.get(ip))); } catch (UnknownHostException e) { logger.error(e.getMessage()); e.printStackTrace(); } } return addressList; } /** * 往集群中增加ES服务器 * @param setting 设置 * @param transportAddress 传输地址 */ public void addClient(Settings setting, List<InetSocketTransportAddress> transportAddress) { Client client = new TransportClient.Builder().addPlugin(ShieldPlugin.class).addPlugin(DeleteByQueryPlugin.class).settings(setting).build() .addTransportAddresses(transportAddress .toArray(new InetSocketTransportAddress[transportAddress.size()])); clientMap.put(setting.get("cluster.name"), client); } }
config.properties
#---ip split by ';' eg 127.0.0.1;127.0.0.2 host=192.168.81.87 #---port split by ';' port=19301 clusterName=application_ppy #---ip split by ';' eg 127.0.0.1;127.0.0.2 #host=172.16.10.22 #---port split by ';' #port=19301 #clusterName=elasticsearch
insertRecord.java
package es; import java.net.NetPermission; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class insertRecord { public String insertRecordToES(String index,String type,String id,Map<String, Object> content){ Integer success = 0; ClientHelper clientHelper = new ClientHelper(); Client client = clientHelper.getClient(); //构造请求头信息 IndexRequestBuilder indexRequest = client.prepareIndex(index, type, id); //构造请求数据json XContentBuilder builder = null; Map<String, Object> resultMsg = new HashMap<String, Object>(); try { builder = XContentFactory.jsonBuilder().startObject(); for(String key :content.keySet()){ builder.field(key, content.get(key)); } builder.endObject(); //执行excute操作 IndexResponse response = indexRequest.setSource(builder).execute().get(); //得到返回的shard信息 success = response.getShardInfo().getSuccessful(); } catch (Exception e) { e.printStackTrace(); resultMsg.put("errorMsg", e.getMessage()); } boolean result = success>0?true:false; resultMsg.put("success", result); return JSON.toJSONString(resultMsg); } }
测试test test.java
package es; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.junit.Test; public class test { public static void main(String[] args) { } /** * 测试插入 */ @Test public void insert(){ insertRecord record = new insertRecord(); String index = "es_test4"; String type = "book"; String id = UUID.randomUUID().toString().replace("-", "").toLowerCase(); Map<String, Object> map = new HashMap<String, Object>(); map.put("number", 20); map.put("price", 58.92); map.put("name", "沧浪之水"); map.put("publish_data", new Date()); map.put("id", UUID.randomUUID().toString().replace("-", "").toLowerCase()); map.put("title", "励志"); String msg = record.insertRecordToES(index, type, id, map); System.out.println(msg); } }
结果: