es客户端创建

ESProps配置类可对接apollo读取:

@ConfigurationProperties(prefix = "elasticsearch")
@Getter
@Setter
public class ESProps {
	private String clusterName;
	private String clusterNodes;

}

ESConfig客户端配置:

@EnableConfigurationProperties(ESProps.class)
public class ESConfig {
	private static final Logger LOGGER = LoggerFactory.getLogger(ESConfig.class);
	private static final String CLUSTER_NODES_SPLIT_SYMBOL = ",";
	private static final String HOST_PORT_SPLIT_SYMBOL = ":";

	private final ESProps esProps;

	@Autowired
	public ESConfig(ESProps esProps) {
		this.esProps = esProps;
	}

	@Bean
	public TransportClient getTransportClient() {
		LOGGER.info("elasticsearch init.");
		System.setProperty("es.set.netty.runtime.available.processors", "false");
		String clusterName = esProps.getClusterName();

		if (StringUtils.isEmpty(esProps.getClusterName())) {
			throw new RuntimeException("elasticsearch.cluster-name is empty.");
		}
		String clusterNodes = esProps.getClusterNodes();
		if (StringUtils.isEmpty(clusterNodes)) {
			throw new RuntimeException("elasticsearch.cluster-nodes is empty.");
		}
		try {
			Settings settings = Settings.builder().put("cluster.name", clusterName.trim())

					.put("client.transport.sniff", true).build();
			TransportClient transportClient = new PreBuiltTransportClient(settings);
			String[] clusterNodeArray = clusterNodes.trim().split(CLUSTER_NODES_SPLIT_SYMBOL);
			for (String clusterNode : clusterNodeArray) {
				String[] clusterNodeInfoArray = clusterNode.trim().split(HOST_PORT_SPLIT_SYMBOL);
				TransportAddress transportAddress = new TransportAddress(
						InetAddress.getByName(clusterNodeInfoArray[0]),
						Integer.parseInt(clusterNodeInfoArray[1]));
				transportClient.addTransportAddress(transportAddress);
			}
			LOGGER.info("elasticsearch init success.");
			return transportClient;
		} catch (Exception e) {
			LOGGER.info("err:", e);
			throw new RuntimeException("elasticsearch init fail.");
		}
	}
}

ES客户端分页查询案例:

@Slf4j
@Component
public class EsHelper {

    @Resource
    private TransportClient transportClient;


    public SearchHits search(String index, String type, Integer pageSize, Integer pageNo,
                             BoolQueryBuilder queryBuilder, Collection sorts)     {

        Integer start = (pageNo - 1) * pageSize;
        Integer limit = pageSize;

        queryBuilder = Optional.ofNullable(queryBuilder).orElseGet(BoolQueryBuilder::new);
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index)
                .setTypes(type)// 设置查询类型
                // 1.SearchType.DFS_QUERY_THEN_FETCH = 精确查询
                // 2.SearchType.SCAN = 扫描查询,无序
                // 3.SearchType.COUNT = 不设置的话,这个为默认值,还有的自己去试试吧
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                // 设置查询关键词
                .setQuery(queryBuilder)
                // 设置查询数据的位置,分页用
                .setFrom(start)
                // 设置查询结果集的最大条数
                .setSize(limit)
                // 设置是否按查询匹配度排序
                .setExplain(true);
        if (!Util.isEmpty(sorts)) {
            sorts.stream().forEachOrdered(v -> {
                searchRequestBuilder.addSort(v.getField(), v.getSortOrder());
            });
        }
        log.info("es-search-request:"+ searchRequestBuilder);

        SearchResponse response = searchRequestBuilder.execute().actionGet();

        SearchHits searchHits = response.getHits();

        //log.info("共匹配到:" + searchHits.getTotalHits() + "条记录!");

        return searchHits;
    }
}

 

你可能感兴趣的:(中间件)