springboot 整合 nacos、Elasticsearch

1.引入依赖

		<!--es 的依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
<!--nacos 服务发现-->
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
		</dependency>
<!--nacos 配置拉取-->
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
		</dependency>
<!--		springboot 配置-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
		</dependency>
		<!--开启Spring Cloud 应用程序启动时加载bootstrap配置文件-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-bootstrap</artifactId>
			<version>3.1.4</version>
		</dependency>

特别注意:需要在 properties 添加 nacos 和 es 的版本,避免产生冲突,启动失败

		<java.version>17</java.version>
<!--		<spring-boot-start-web.version>2.3.11.RELEASE</spring-boot-start-web.version>-->
<!--		<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>-->
		<spring-boot.version>2.6.13</spring-boot.version>
		<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
<!--		需要再这里添加对应的版本,否则容易出现启动错误,版本冲突-->
		<elasticsearch.version>7.10.2</elasticsearch.version>

2.配置

  • 使用nacos  需要 将对应的配置写入 "bootstrap.yml" 文件,不然nacos启动报错
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/nacos?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&allowMultiQueries=true
    username: root
    password: root
  profiles:
    active: dev
  application:
    name: user-service
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        group: DEFAULT_GROUP
        enabled: true
        prefix: user-service
        namespace: 711d3b17-d7f1-46ad-b770-b78171e081d8
        file-extension: yaml
        # 读取多个nacos配置
        extension-configs:
          - data-id: user-service.dev.yaml
            group: DEFAULT_GROUP
            refresh: true
          - data-id: test
            group: DEFAULT_GROUP
            refresh: true
          - data-id: user-service-mypass
            group: DEFAULT_GROUP
            refresh: true
      # 服务注册到nacos
      discovery:
        server-addr: 127.0.0.1:8848
        username: nacos
        password: nacos
        namespace: 711d3b17-d7f1-46ad-b770-b78171e081d8
        group: DEFAULT_GROUP
  # nacos 配置
  elasticsearch:
    socket-timeout:
    uris: http://localhost:9200
  • 其中 extension-configs 是配置读取多个配置文件,如果只需要读取一个,则将该配置删除,默认读取的配置名称为: {spring.cloud.nacos.config.prefix}-{spring.profiles.active}.{spring.cloud.nacos.config.file-extension}
  • spring.cloud.nacos.config.extension-configs.refresh 配置为 是否启动 动态更新配置

3.使用Elasticsearch

package com.example.nacosstudy.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.nacosstudy.common.util.Result;
import com.example.nacosstudy.entity.po.BasePO;
import com.example.nacosstudy.entity.po.ElasticSearchUserPO;
import com.example.nacosstudy.entity.vo.ElasticSearchCreatedUserVO;
import com.example.nacosstudy.entity.vo.ElasticSearchQueryUserVO;
import com.example.nacosstudy.entity.vo.ElasticSearchVO;
import com.example.nacosstudy.mapper.ElasticSearchUserRepository;
import com.example.nacosstudy.service.ElasticSearchService;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
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.support.master.AcknowledgedResponse;
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.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    ElasticSearchUserRepository elasticSearchUserRepository;

    /**
     * 创建索引
     */
    @Override
    public Result createdIndex(String indexName) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return Result.ok(createIndexResponse);
    }

    /**
     * 判断索引是否存在
     */
    @Override
    public Result existsIndex(String indexName) throws IOException {
        GetIndexRequest request = new GetIndexRequest(indexName);
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        return Result.ok(exists);
    }

    /**
     * 删除索引
     */
    @Override
    public Result deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        return Result.ok(delete);
    }

    /**
     * 创建文档
     */
    @Override
    public Result createdDoc(ElasticSearchCreatedUserVO elasticSearchUserVO) throws IOException {

        ElasticSearchUserPO elasticSearchUserPO = new ElasticSearchUserPO();
        BeanUtils.copyProperties(elasticSearchUserVO,elasticSearchUserPO);
        createdInitPO(elasticSearchUserPO);
//        ElasticSearchUserPO save = elasticSearchUserRepository.save(elasticSearchUserPO);
        String body = JSON.toJSONString(elasticSearchUserPO);
        IndexRequest request = new IndexRequest(elasticSearchUserVO.getIndexName());
        request.source(body, XContentType.JSON);
        request.id(elasticSearchUserPO.getId());
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        return Result.ok(index);
    }

    /**
     * 跟进 ID 和 索引 获取文档
     */
    @Override
    public Result getDoc(ElasticSearchQueryUserVO elasticSearchUserVO) throws IOException {
        GetRequest request = new GetRequest(elasticSearchUserVO.getIndexName(),elasticSearchUserVO.getId());
        GetResponse documentFields = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        ElasticSearchUserPO elasticSearchUserPO = JSON.parseObject(documentFields.getSourceAsBytes(), ElasticSearchUserPO.class);
        return Result.ok(elasticSearchUserPO);
    }

    /**
     * 更新文档
     */
    @Override
    public Result updateDoc(ElasticSearchCreatedUserVO elasticSearchUserVO) throws IOException {
        GetRequest request = new GetRequest(elasticSearchUserVO.getIndexName(),elasticSearchUserVO.getId());
        GetResponse documentFields = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        ElasticSearchUserPO elasticSearchUserPO = JSON.parseObject(documentFields.getSourceAsBytes(), ElasticSearchUserPO.class);
        BeanUtils.copyProperties(elasticSearchUserVO,elasticSearchUserPO);
        updateInitPO(elasticSearchUserPO);
        UpdateRequest updateRequest = new UpdateRequest(elasticSearchUserVO.getIndexName(),elasticSearchUserVO.getId());
        updateRequest.doc(JSON.toJSONString(elasticSearchUserPO),XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return Result.ok(update);
    }

    /**
     * 删除文档
     */
    @Override
    public Result deleteDoc(ElasticSearchQueryUserVO elasticSearchUserVO) throws IOException {
        DeleteRequest request = new DeleteRequest();
        request.index(elasticSearchUserVO.getIndexName());
        request.id(elasticSearchUserVO.getId());
        DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        return Result.ok(delete);
    }

    /**
     * 条件查询文档
     */
    @Override
    public Result trimQuery(ElasticSearchVO elasticSearchUserVO) throws IOException {
        List<ElasticSearchUserPO> byUsername = elasticSearchUserRepository.findByUsername(elasticSearchUserVO.getUsername());

        SearchRequest request = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        QueryBuilder queryBuilder = new TermQueryBuilder("username",elasticSearchUserVO.getUsername());
        searchSourceBuilder.query(queryBuilder);
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        List<ElasticSearchUserPO> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            String sourceAsString = hit.getSourceAsString();
            ElasticSearchUserPO elasticSearchUserPO = JSON.parseObject(sourceAsString, ElasticSearchUserPO.class);
            list.add(elasticSearchUserPO);
        }
        BoolQueryBuilder builder = new BoolQueryBuilder();


        return Result.ok(byUsername);
    }

    private void createdInitPO(ElasticSearchUserPO basePO){
        basePO.setCreatedBy("USER");
        basePO.setCreatedDate(LocalDateTime.now());
        basePO.setEnabled(Boolean.TRUE);
        basePO.setRemarks("");
        basePO.setLastModifiedBy("USER");
        basePO.setLastModifiedDate(LocalDateTime.now());
    }

    private void updateInitPO(ElasticSearchUserPO basePO){
        basePO.setCreatedBy("USER");
        basePO.setCreatedDate(LocalDateTime.now());
        basePO.setRemarks("");
        basePO.setLastModifiedBy("USER");
        basePO.setLastModifiedDate(LocalDateTime.now());
    }
}

4.总结

新手一枚,持续进步,指出问题,解决问题~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值