springboot整合ElasticSearch
2021-03-04 22:28
标签:stop boot str version from 创建 rmq init each yml pom Controller Utils 全局ID生成工具类 springboot整合ElasticSearch 标签:stop boot str version from 创建 rmq init each 原文地址:https://www.cnblogs.com/fengwenzhee/p/14336734.htmlspring:
data:
elasticsearch:
client:
reactive:
endpoints: 192.168.209.160:9200
connection-timeout: 10000#链接到es的超时时间,毫秒为单位,默认10秒(10000毫秒)
socket-timeout: 10000#读取和写入的超时时间,单位为毫秒,默认5秒(5000毫秒)
elasticsearch:
rest:
uris: 192.168.209.160:9200
# 这两个属性在新版本的springboot中已经不建议使用,9300属于elasticsearch各节点之间的通讯接口。
# 属于lowlevelclient。我们推荐使用9200的RestHighLevelClient去链接
# cluster-nodes: 127.0.0.1:9300
# cluster-name: helloElasticsearch
package com.fwz.tproject.testfunction.controller;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fwz.tproject.testfunction.service.ElasticSearchUtils;
import com.fwz.tproject.testfunction.service.IdGeneratorSnowflake;
import com.fwz.tproject.testfunction.service.OrderService;
/**
*
*
* @author 冯文哲
* @version 2018-06-11
*/
@RestController
@RequestMapping(value = "/test")
public class MainController {
@Autowired
private IdGeneratorSnowflake idGenerator;
@Autowired
ElasticSearchUtils utilsService;
@RequestMapping(value = "createIndex")
public String elasticsearch() {
if (utilsService.createIndex("fwztest_index", 5, 1, "")) {
return "创建成功";
} else {
return "创建失败";
}
}
@RequestMapping(value = "addDoc")
public String addDoc() {
for (int j = 0; j 1000; j++) {
Map
package com.fwz.tproject.testfunction.service;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
@Service
@EnableAsync
public class ElasticSearchUtils {
@Autowired
private RestHighLevelClient restClient;
Logger logger = LoggerFactory.getLogger(ElasticSearchUtils.class.getName());
/**
* createIndex
*
* @param indexName //索引名称
* @param shards //主分片
* @param replicas //备份分片
* @param mapping //mapping配置
* @return
*/
public boolean createIndex(String indexName, Integer shards, Integer replicas, String mapping) {
logger.info(restClient.toString());
CreateIndexRequest request = new CreateIndexRequest(indexName);
request.settings(Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 1));
request.mapping(
"{\"properties\":{\"author_id\":{\"type\":\"long\"},\"title\":{\"type\":\"text\",\"analyzer\":\"standard\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"content\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"create_date\":{\"type\":\"date\"}}}",
XContentType.JSON);
request.setTimeout(TimeValue.timeValueMinutes(1));
CreateIndexResponse createIndexResponse;
try {
createIndexResponse = restClient.indices().create(request, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
logger.info("是否获取ACK:" + acknowledged);
return acknowledged;
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error(e.toString());
}
return false;
}
/**
*
* addDocument
*
* @param index 索引名称
* @param id 数据ID(为空则使用es内部ID)
* @param source 数据(json 或 Map)
* @return
* @author fwzz
* @version 创建时间:2021年1月27日 下午5:10:42
*
*/
@Async
public Future
package com.fwz.tproject.testfunction.service;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
@Component
public class IdGeneratorSnowflake {
private long workerId = 0;
private long datacenterId = 1;
private Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
private static final Logger log = LoggerFactory.getLogger(IdGeneratorSnowflake.class.getName());
// 依赖注入完成后执行该方法,进行一些初始化工作
@PostConstruct
public void init() {
try {
workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
log.info("当前机器的workerId: {}", workerId);
} catch (Exception e) {
e.printStackTrace();
log.warn("当前机器的workerId获取失败", e);
// 释放ID
workerId = NetUtil.getLocalhostStr().hashCode();
}
}
// 使用默认机房号获取ID
public synchronized long snowflakeId() {
return snowflake.nextId();
}
// 自己制定机房号获取ID
public synchronized long snowflakeId(long workerId, long datacenterId) {
Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
return snowflake.nextId();
}
/**
* 生成的是不带-的字符审,类似于: 73a64edf935d4952a287739a66f96e06
*
* @return
*/
public String simpleUUID() {
return IdUtil.simpleUUID();
}
/**
* 生成的UUID是带-的字符串,类似于: b12b6401-6f9c-4351-b2b6-d8afc9ab9272
*
* @return
*/
public String randomUUID() {
return IdUtil.randomUUID();
}
public static void main(String[] args) {
IdGeneratorSnowflake f = new IdGeneratorSnowflake();
for (int i = 0; i 1000; i++) {
System.out.println(f.snowflakeId(0, 0));
}
}
}
上一篇:SpringBoot: No active profile set, falling back to default profiles: default , 不一定是依赖的问题
下一篇:Spring AOP
文章标题:springboot整合ElasticSearch
文章链接:http://soscw.com/index.php/essay/60185.html