@Configuration
public class ElasticsearchConfiguration {
@Value(“${elasticsearch.host}”)
private String host;
@Value(“${elasticsearch.port}”)
private int port;
@Value(“${elasticsearch.connTimeout}”)
private int connTimeout;
@Value(“${elasticsearch.socketTimeout}”)
private int socketTimeout;
@Value(“${elasticsearch.connectionRequestTimeout}”)
private int connectionRequestTimeout;
@Bean(destroyMethod = “close”, name = “client”)
public RestHighLevelClient initRestClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port))
.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
.setConnectTimeout(connTimeout)
.setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout));
return new RestHighLevelClient(builder);
}
}
定義文檔實(shí)體類(lèi)
首先在?constant
?包下定義常量接口,在接口中定義索引的名字為?user
?:
public interface Constant {
String INDEX = “user”;
}
然后在?document
?包下創(chuàng)建一個(gè)文檔實(shí)體類(lèi):
public class UserDocument {
private String id;
private String name;
private String sex;
private Integer age;
private String city;
// 省略 getter/setter
}
ES 基本操作
在這里主要介紹 ES 的索引、文檔、搜索相關(guān)的簡(jiǎn)單操作,在?service
?包下創(chuàng)建?UserService
類(lèi)。
索引操作
在這里演示創(chuàng)建索引和刪除索引:
創(chuàng)建索引
在創(chuàng)建索引的時(shí)候可以在?CreateIndexRequest
?中設(shè)置索引名稱(chēng)、分片數(shù)、副本數(shù)以及 mappings,在這里索引名稱(chēng)為?user
?,分片數(shù)?number_of_shards
?為 1,副本數(shù)?number_of_replicas
?為 0,具體代碼如下所示:
public boolean createUserIndex(String index) throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
createIndexRequest.settings(Settings.builder()
.put(“index.number_of_shards”, 1)
.put(“index.number_of_replicas”, 0)
);
createIndexRequest.mapping(“{\n” +
" “properties”: {\n" +
" “city”: {\n" +
" “type”: “keyword”\n" +
" },\n" +
" “sex”: {\n" +
" “type”: “keyword”\n" +
" },\n" +
" “name”: {\n" +
" “type”: “keyword”\n" +
" },\n" +
" “id”: {\n" +
" “type”: “keyword”\n" +
" },\n" +
" “age”: {\n" +
" “type”: “integer”\n" +
" }\n" +
" }\n" +
“}”, XContentType.JSON);
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
return createIndexResponse.isAcknowledged();
}
通過(guò)調(diào)用該方法,就可以創(chuàng)建一個(gè)索引?user
?,索引信息如下:
關(guān)于 ES 的 Mapping 可以看下這篇文章:?一文搞懂 Elasticsearch 之 Mapping
刪除索引
在?DeleteIndexRequest
?中傳入索引名稱(chēng)就可以刪除索引,具體代碼如下所示:
public Boolean deleteUserIndex(String index) throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
AcknowledgedResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
return deleteIndexResponse.isAcknowledged();
}
介紹完索引的基本操作,下面介紹文檔的相關(guān)操作:
文檔操作
在這里演示下創(chuàng)建文檔、批量創(chuàng)建文檔、查看文檔、更新文檔以及刪除文檔:
創(chuàng)建文檔
創(chuàng)建文檔的時(shí)候需要在?IndexRequest
?中指定索引名稱(chēng),?id
?如果不傳的話(huà)會(huì)由 ES 自動(dòng)生成,然后傳入 source,具體代碼如下:
public Boolean createUserDocument(UserDocument document) throws Exception {
UUID uuid = UUID.randomUUID();
document.setId(uuid.toString());
IndexRequest indexRequest = new IndexRequest(Constant.INDEX)
.id(document.getId())
.source(JSON.toJSONString(document), XContentType.JSON);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
return indexResponse.status().equals(RestStatus.OK);
}
下面通過(guò)調(diào)用這個(gè)方法,創(chuàng)建兩個(gè)文檔,具體內(nèi)容如下:
批量創(chuàng)建文檔
在一個(gè) REST 請(qǐng)求中,重新建立網(wǎng)絡(luò)開(kāi)銷(xiāo)是十分損耗性能的,因此 ES 提供 Bulk API,?支持在一次 API 調(diào)用中,對(duì)不同的索引進(jìn)行操作?,從而減少網(wǎng)絡(luò)傳輸開(kāi)銷(xiāo),提升寫(xiě)入速率。
下面方法是批量創(chuàng)建文檔,一個(gè)?BulkRequest
?里可以添加多個(gè) Request,具體代碼如下:
public Boolean bulkCreateUserDocument(List documents) throws IOException {
BulkRequest bulkRequest = new BulkRequest();
for (UserDocument document : documents) {
String id = UUID.randomUUID().toString();
document.setId(id);
IndexRequest indexRequest = new IndexRequest(Constant.INDEX)
.id(id)
.source(JSON.toJSONString(document), XContentType.JSON);
bulkRequest.add(indexRequest);
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
return bulkResponse.status().equals(RestStatus.OK);
}
下面通過(guò)該方法創(chuàng)建些文檔,便于下面的搜索演示。
查看文檔
查看文檔需要在?GetRequest
?中傳入索引名稱(chēng)和文檔 id,具體代碼如下所示:
public UserDocument getUserDocument(String id) throws IOException {
GetRequest getRequest = new GetRequest(Constant.INDEX, id);
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
UserDocument result = new UserDocument();
if (getResponse.isExists()) {
String sourceAsString = getResponse.getSourceAsString();
result = JSON.parseObject(sourceAsString, UserDocument.class);
} else {
logger.error(“沒(méi)有找到該 id 的文檔”);
}
return result;
}
下面?zhèn)魅胛臋n id 調(diào)用該方法,結(jié)果如下所示:
更新文檔
更新文檔則是先給?UpdateRequest
?傳入索引名稱(chēng)和文檔 id,然后通過(guò)傳入新的 doc 來(lái)進(jìn)行更新,具體代碼如下:
public Boolean updateUserDocument(UserDocument document) throws Exception {
UserDocument resultDocument = getUserDocument(document.getId());
UpdateRequest updateRequest = new UpdateRequest(Constant.INDEX, resultDocument.getId());
updateRequest.doc(JSON.toJSONString(document), XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
return updateResponse.status().equals(RestStatus.OK);
}
下面將文檔 id 為?9b8d9897-3352-4ef3-9636-afc6fce43b20
?的文檔的城市信息改為?handan
?,調(diào)用方法結(jié)果如下:
自我介紹一下,小編13年上海交大畢業(yè),曾經(jīng)在小公司待過(guò),也去過(guò)華為、OPPO等大廠,18年進(jìn)入阿里一直到現(xiàn)在。
深知大多數(shù)Java工程師,想要提升技能,往往是自己摸索成長(zhǎng)或者是報(bào)班學(xué)習(xí),但對(duì)于培訓(xùn)機(jī)構(gòu)動(dòng)則幾千的學(xué)費(fèi),著實(shí)壓力不小。自己不成體系的自學(xué)效果低效又漫長(zhǎng),而且極易碰到天花板技術(shù)停滯不前!
因此收集整理了一份《2024年Java開(kāi)發(fā)全套學(xué)習(xí)資料》,初衷也很簡(jiǎn)單,就是希望能夠幫助到想自學(xué)提升又不知道該從何學(xué)起的朋友,同時(shí)減輕大家的負(fù)擔(dān)。
既有適合小白學(xué)習(xí)的零基礎(chǔ)資料,也有適合3年以上經(jīng)驗(yàn)的小伙伴深入學(xué)習(xí)提升的進(jìn)階課程,基本涵蓋了95%以上Java開(kāi)發(fā)知識(shí)點(diǎn),真正體系化!
由于文件比較大,這里只是將部分目錄截圖出來(lái),每個(gè)節(jié)點(diǎn)里面都包含大廠面經(jīng)、學(xué)習(xí)筆記、源碼講義、實(shí)戰(zhàn)項(xiàng)目、講解視頻,并且會(huì)持續(xù)更新!
如果你覺(jué)得這些內(nèi)容對(duì)你有幫助,可以?huà)叽a獲取?。。▊渥ava獲?。?/strong>

總結(jié)
大型分布式系統(tǒng)猶如一個(gè)生命,系統(tǒng)中各個(gè)服務(wù)猶如骨骼,其中的數(shù)據(jù)猶如血液,而Kafka猶如經(jīng)絡(luò),串聯(lián)整個(gè)系統(tǒng)。這份Kafka源碼筆記通過(guò)大量的設(shè)計(jì)圖展示、代碼分析、示例分享,把Kafka的實(shí)現(xiàn)脈絡(luò)展示在讀者面前,幫助讀者更好地研讀Kafka代碼。
麻煩幫忙轉(zhuǎn)發(fā)一下這篇文章+關(guān)注我
《一線大廠Java面試題解析+核心總結(jié)學(xué)習(xí)筆記+最新講解視頻+實(shí)戰(zhàn)項(xiàng)目源碼》,點(diǎn)擊傳送門(mén)即可獲??!
可以?huà)叽a獲?。。。▊渥ava獲?。?*

總結(jié)
大型分布式系統(tǒng)猶如一個(gè)生命,系統(tǒng)中各個(gè)服務(wù)猶如骨骼,其中的數(shù)據(jù)猶如血液,而Kafka猶如經(jīng)絡(luò),串聯(lián)整個(gè)系統(tǒng)。這份Kafka源碼筆記通過(guò)大量的設(shè)計(jì)圖展示、代碼分析、示例分享,把Kafka的實(shí)現(xiàn)脈絡(luò)展示在讀者面前,幫助讀者更好地研讀Kafka代碼。
麻煩幫忙轉(zhuǎn)發(fā)一下這篇文章+關(guān)注我
[外鏈圖片轉(zhuǎn)存中…(img-daf5pebx-1711815434669)]文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-846035.html
《一線大廠Java面試題解析+核心總結(jié)學(xué)習(xí)筆記+最新講解視頻+實(shí)戰(zhàn)項(xiàng)目源碼》,點(diǎn)擊傳送門(mén)即可獲?。?/strong>文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-846035.html
到了這里,關(guān)于Spring Boot 集成 Elasticsearch 實(shí)戰(zhàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!