diff --git a/bawei-base/base-es/base-es-common/pom.xml b/bawei-base/base-es/base-es-common/pom.xml index 6c6c50c..6c30fb9 100644 --- a/bawei-base/base-es/base-es-common/pom.xml +++ b/bawei-base/base-es/base-es-common/pom.xml @@ -2,12 +2,13 @@ - - base-es - com.bawei - 3.6.0 - 4.0.0 + + com.bawei + bawei-base + 3.6.0 + ../../pom.xml + base-es-common @@ -16,7 +17,6 @@ 8 UTF-8 - @@ -25,4 +25,5 @@ bawei-common-core + diff --git a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/common/domain/ConmtMap.java b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/common/domain/ConmtMap.java new file mode 100644 index 0000000..0de0899 --- /dev/null +++ b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/common/domain/ConmtMap.java @@ -0,0 +1,16 @@ +package com.bawei.common.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ConmtMap { + + private long total; + + private Map objectMap; +} diff --git a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/CommonMap.java b/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/CommonMap.java deleted file mode 100644 index ac3042e..0000000 --- a/bawei-base/base-es/base-es-common/src/main/java/com/bawei/es/domain/CommonMap.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.bawei.es.domain; - -import lombok.Data; - -import java.util.Map; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bawei.es.domain - * @ClassName: CommonMap - * @Description: 请在此处填写具体描述 - * @Date: 2024/4/23 14:29 - */ -@Data -public class CommonMap { - - /** - * 个数 - */ - private long total; - - /** - * 查询数据 - */ - private Map objectMap; -} diff --git a/bawei-base/base-es/base-es-remote/pom.xml b/bawei-base/base-es/base-es-remote/pom.xml index 86a47cf..e92d62a 100644 --- a/bawei-base/base-es/base-es-remote/pom.xml +++ b/bawei-base/base-es/base-es-remote/pom.xml @@ -2,12 +2,13 @@ - - base-es - com.bawei - 3.6.0 - 4.0.0 + + com.bawei + bawei-base + 3.6.0 + ../../pom.xml + base-es-remote @@ -16,13 +17,11 @@ 8 UTF-8 - - - com.bawei base-es-common + 3.6.0 diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/EsDocRemoteService.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/EsDocRemoteService.java new file mode 100644 index 0000000..c08796b --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/EsDocRemoteService.java @@ -0,0 +1,23 @@ +package com.bawei.es.remote; + +import com.bawei.common.core.constant.ServiceNameConstants; +import com.bawei.common.core.domain.R; +import com.bawei.common.core.web.domain.AjaxResult; +import com.bawei.es.remote.factory.EsDocRemoteFactory; +import com.bawei.es.remote.factory.EsIndexRemoteFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; +@FeignClient(contextId = "EsDocRemoteService", value = ServiceNameConstants.BAWEI_BASE_ES, + fallbackFactory = EsDocRemoteFactory.class, + path = "/doc") +public interface EsDocRemoteService { + @GetMapping("/queryList/{indexName}") + public R queryList(@PathVariable("indexName") String indexName, @RequestParam Map docMsg); + @PutMapping("/batchAddDoc/{indexName}") + public R batchAddDoc(@PathVariable("indexName") String indexName, @RequestBody Map docMsg); + @DeleteMapping("/bathDeleteDoc/{indexName}") + public R bathDeleteDoc(@PathVariable("indexName") String indexName, @RequestBody List ids); +} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/EsIndexRemoteService.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/EsIndexRemoteService.java new file mode 100644 index 0000000..8c797b1 --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/EsIndexRemoteService.java @@ -0,0 +1,23 @@ +package com.bawei.es.remote; + +import com.bawei.common.core.constant.ServiceNameConstants; +import com.bawei.common.core.domain.R; +import com.bawei.es.remote.factory.EsIndexRemoteFactory; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; +@FeignClient(contextId = "EsIndexRemoteService",value = ServiceNameConstants.BAWEI_BASE_ES,fallbackFactory = EsIndexRemoteFactory.class,path = "/index") +public interface EsIndexRemoteService { + @PostMapping("/createIndex/{indexName}") + public R createIndex(@PathVariable("indexName") String indexName, @RequestBody Map docMsg); + @PostMapping("/deleteIndex/{indexName}") + public R deleteIndex(@PathVariable("indexName") String indexName); + @PutMapping("/updateIndex/{indexName}") + public R updateIndex(@PathVariable("indexName") String indexName,@RequestBody Map docMsg); + @GetMapping("/findIndex/{indexName}") + public R findIndex(@PathVariable("indexName") String indexName); + @PostMapping("/getMapping/{indexName}") + public R getMapping(@PathVariable("indexName") String indexName); +} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteDocumentService.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteDocumentService.java deleted file mode 100644 index 2573e3b..0000000 --- a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteDocumentService.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.bawei.es.remote.api; - -import com.bawei.common.core.constant.ServiceNameConstants; -import com.bawei.common.core.domain.R; -import com.bawei.es.remote.factory.RemoteDocumentFallbackFactory; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; - -/** - * 文件服务 - * - * @author bawei - */ -@FeignClient(contextId = "remoteDocumentService", value = ServiceNameConstants.ES_SERVICE, fallbackFactory = RemoteDocumentFallbackFactory.class) -public interface RemoteDocumentService -{ - @PostMapping("/doc/{indexName}") - R queryList(@PathVariable(value = "indexName") String indexName, @RequestBody Map conditions); - - @PutMapping("/doc/{indexName}") - R batchDocument(@PathVariable(value = "indexName") String indexName, @RequestBody List dataJson); - - @DeleteMapping("/doc/{indexName}") - R batchDeleteDocument(@PathVariable(value = "indexName") String indexName, @RequestBody List dataJson); -} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteIndexService.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteIndexService.java deleted file mode 100644 index df0eb0a..0000000 --- a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/api/RemoteIndexService.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.bawei.es.remote.api; - -import com.bawei.common.core.constant.ServiceNameConstants; -import com.bawei.common.core.domain.R; -import com.bawei.es.remote.factory.RemoteIndexFallbackFactory; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.*; - -import java.util.Map; - -/** - * 文件服务 - * - * @author bawei - */ -@FeignClient(contextId = "remoteIndexService", value = ServiceNameConstants.ES_SERVICE, fallbackFactory = RemoteIndexFallbackFactory.class) -public interface RemoteIndexService -{ - @GetMapping("/index/{indexName}") - public R exist(@PathVariable(value = "indexName") String indexName); - - @GetMapping("/index/getMapping/{indexName}") - public R getMapping(@PathVariable(value = "indexName") String indexName); - - @PostMapping("/index/{indexName}") - public R index(@PathVariable(value = "indexName") String indexName,@RequestBody Map mappings); - - @PutMapping("/index/{indexName}") - public R updateIndex(@PathVariable(value = "indexName") String indexName,@RequestBody Map mappings); - - @DeleteMapping("/index/{indexName}") - public R deleteIndex(@PathVariable(value = "indexName") String indexName); -} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/EsDocRemoteFactory.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/EsDocRemoteFactory.java new file mode 100644 index 0000000..4b6f5f3 --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/EsDocRemoteFactory.java @@ -0,0 +1,38 @@ +package com.bawei.es.remote.factory; + +import com.bawei.common.core.domain.R; +import com.bawei.common.core.web.domain.AjaxResult; +import com.bawei.es.remote.EsDocRemoteService; +import lombok.extern.log4j.Log4j2; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; + +@Component +@Log4j2 +public class EsDocRemoteFactory implements FallbackFactory { + @Override + public EsDocRemoteService create(Throwable cause) { + return new EsDocRemoteService() { + @Override + public R queryList(String indexName, Map docMsg) { + log.error("调用查询信息远程服务失败{}-{}-{}-{}",indexName,docMsg,cause.getMessage(),cause); + return R.fail(); + } + + @Override + public R batchAddDoc(String indexName, Map docMsg) { + log.error("调用批量添加信息远程服务失败{}-{}-{}",indexName,cause.getMessage(),cause); + return R.fail(); + } + + @Override + public R bathDeleteDoc(String indexName, List ids) { + log.error("调用批量删除信息远程服务失败{}-{}-{}-{}",indexName,ids,cause.getMessage(),cause); + return R.fail(); + } + }; + } +} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/EsIndexRemoteFactory.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/EsIndexRemoteFactory.java new file mode 100644 index 0000000..4456a95 --- /dev/null +++ b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/EsIndexRemoteFactory.java @@ -0,0 +1,48 @@ +package com.bawei.es.remote.factory; + +import com.bawei.common.core.domain.R; +import com.bawei.es.remote.EsIndexRemoteService; +import lombok.extern.log4j.Log4j2; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +@Log4j2 +public class EsIndexRemoteFactory implements FallbackFactory { + @Override + public EsIndexRemoteService create(Throwable cause) { + return new EsIndexRemoteService() { + @Override + public R createIndex(String indexName, Map docMsg) { + log.error("远程调用创建索引服务失败:{}-{}-{}-{}",indexName,docMsg,cause.getMessage(),cause); + return R.fail(); + } + + @Override + public R findIndex(String indexName) { + log.error("远程调用查询索引服务失败:{}-{}-{}",indexName,cause.getMessage(),cause); + return R.fail(); + } + + @Override + public R getMapping(String indexName) { + log.error("远程调用获取Mapping服务失败:{}-{}-{}",indexName,cause.getMessage(),cause); + return R.fail(); + } + + @Override + public R deleteIndex(String indexName) { + log.error("远程调用删除索引服务失败:{}-{}-{}",indexName,cause.getMessage(),cause); + return R.fail(); + } + + @Override + public R updateIndex(String indexName, Map docMsg) { + log.error("远程调用修改索引服务失败:{}-{}-{}{}",indexName,docMsg,cause.getMessage(),cause); + return R.fail(); + } + }; + } +} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteDocumentFallbackFactory.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteDocumentFallbackFactory.java deleted file mode 100644 index 396d471..0000000 --- a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteDocumentFallbackFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.bawei.es.remote.factory; - -import com.bawei.common.core.domain.R; -import com.bawei.es.remote.api.RemoteDocumentService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.openfeign.FallbackFactory; -import org.springframework.stereotype.Component; - -import java.util.List; -import java.util.Map; - -/** - * 文件服务降级处理 - * - * @author bawei - */ -@Component -public class RemoteDocumentFallbackFactory implements FallbackFactory -{ - private static final Logger log = LoggerFactory.getLogger(RemoteDocumentFallbackFactory.class); - - - @Override - public RemoteDocumentService create(Throwable cause) { - return new RemoteDocumentService() { - @Override - public R queryList(String indexName, Map conditions) { - return R.fail(); - } - - @Override - public R batchDocument(String indexName, List dataJson) { - return R.fail(); - } - - @Override - public R batchDeleteDocument(String indexName, List dataJson) { - return R.fail(); - } - }; - } -} diff --git a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteIndexFallbackFactory.java b/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteIndexFallbackFactory.java deleted file mode 100644 index 469cd1c..0000000 --- a/bawei-base/base-es/base-es-remote/src/main/java/com/bawei/es/remote/factory/RemoteIndexFallbackFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.bawei.es.remote.factory; - -import com.bawei.common.core.domain.R; -import com.bawei.es.remote.api.RemoteIndexService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.openfeign.FallbackFactory; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * 文件服务降级处理 - * - * @author bawei - */ -@Component -public class RemoteIndexFallbackFactory implements FallbackFactory -{ - private static final Logger log = LoggerFactory.getLogger(RemoteIndexFallbackFactory.class); - - - @Override - public RemoteIndexService create(Throwable cause) { - return new RemoteIndexService() { - @Override - public R exist(String indexName) { - return R.fail(); - } - - @Override - public R getMapping(String indexName) { - return R.fail(); - } - - @Override - public R index(String indexName, Map mappings) { - return R.fail(); - } - - @Override - public R updateIndex(String indexName, Map mappings) { - return R.fail(); - } - - @Override - public R deleteIndex(String indexName) { - return R.fail(); - } - }; - } -} diff --git a/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index e80fcff..0c711ba 100644 --- a/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/bawei-base/base-es/base-es-remote/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,2 +1,2 @@ -com.bawei.es.remote.factory.RemoteIndexFallbackFactory -com.bawei.es.remote.factory.RemoteDocumentFallbackFactory +com.bawei.es.remote.factory.EsIndexRemoteFactory +com.bawei.es.remote.factory.EsDocRemoteFactory diff --git a/bawei-base/base-es/base-es-server/pom.xml b/bawei-base/base-es/base-es-server/pom.xml index 479410e..e3c097b 100644 --- a/bawei-base/base-es/base-es-server/pom.xml +++ b/bawei-base/base-es/base-es-server/pom.xml @@ -2,12 +2,13 @@ - - base-es - com.bawei - 3.6.0 - 4.0.0 + + com.bawei + bawei-base + 3.6.0 + ../../pom.xml + base-es-server @@ -16,9 +17,12 @@ 8 UTF-8 - - + + com.github.xiaoymin + knife4j-openapi3-spring-boot-starter + 4.1.0 + com.alibaba.cloud @@ -51,7 +55,23 @@ com.bawei - bawei-common-security + bawei-common-core + + + + org.hibernate.validator + hibernate-validator + + + + org.elasticsearch.plugin + transport-netty4-client + 6.7.2 + + + + org.springframework.boot + spring-boot-starter-web @@ -59,7 +79,7 @@ elasticsearch-rest-high-level-client - + com.bawei base-es-common diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/BaWeiEsApplication.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/EsApplication.java similarity index 68% rename from bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/BaWeiEsApplication.java rename to bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/EsApplication.java index e00aed4..2a18888 100644 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/BaWeiEsApplication.java +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/EsApplication.java @@ -7,11 +7,8 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @EnableCustomSwagger2 @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) -public class BaWeiEsApplication { - +public class EsApplication { public static void main(String[] args) { - SpringApplication.run(BaWeiEsApplication.class, args); - System.out.println("(♥◠‿◠)ノ゙ es服务模块启动成功 ლ(´ڡ`ლ)゙ "); + SpringApplication.run(EsApplication.class, args); } - } diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/Config.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/Config.java new file mode 100644 index 0000000..2328848 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/Config.java @@ -0,0 +1,29 @@ +package com.bawei.es.config; + +import lombok.Data; +import org.apache.http.HttpHost; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestHighLevelClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "es") +@Data +public class Config { + @Value("${es.host}") + private String host; + @Value("${es.port}") + private int port; + @Value("${es.scheme}") + private String scheme; + + @Bean + public RestHighLevelClient restHighLevelClient(){ + return new RestHighLevelClient( + RestClient.builder(new HttpHost(host,port,scheme)) + ); + } +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/ElasticSearchConfig.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/ElasticSearchConfig.java deleted file mode 100644 index a4b8d51..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/config/ElasticSearchConfig.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.bawei.es.config; - -import org.apache.http.HttpHost; -import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.RestHighLevelClient; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bwie.es.config - * @ClassName: ElasticSearchConfig - * @Description: 请在此处填写具体描述 - * @Date: 2024/4/22 20:50 - */ -@Configuration -public class ElasticSearchConfig { - - @Value("${es.host}") - private String host; - - @Value("${es.port}") - private int port; - - @Value("${es.scheme}") - private String scheme; - - @Bean - public RestHighLevelClient restHighLevelClient(){ - return new RestHighLevelClient( - RestClient.builder(new HttpHost(host, port, scheme))); - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getScheme() { - return scheme; - } - - public void setScheme(String scheme) { - this.scheme = scheme; - } -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocumentController.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocumentController.java deleted file mode 100644 index 452878d..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/DocumentController.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.bawei.es.controller; - -import com.bawei.common.core.domain.R; -import com.bawei.es.service.DocumentService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import java.util.List; -import java.util.Map; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bwie.es.controller - * @ClassName: DocumentController - * @Description: 请在此处填写具体描述 - * @Date: 2024/4/22 20:57 - */ -@RestController -@RequestMapping("/doc") -@Api(tags = "es文档接口") -public class DocumentController { - - @Resource(name = "documentServiceImpl") - private DocumentService documentService; - - @PostMapping("/{indexName}") - @ApiOperation(value = "条件查询文档数据") - public R queryList(@PathVariable String indexName, @RequestBody Map conditions){ - return documentService.queryList(indexName,conditions); - } - - @PutMapping("/{indexName}") - @ApiOperation(value = "批量操作数据") - public R batchDocument(@PathVariable String indexName, @RequestBody Map dataJson){ - documentService.batchOperation(indexName,dataJson); - return R.ok(null, "批量操作成功"); - } - - @DeleteMapping("/{indexName}") - @ApiOperation(value = "批量删除") - public R batchDeleteDocument(@PathVariable String indexName, @RequestBody List dataJson){ - documentService.batchDeletion(indexName,dataJson); - return R.ok(null, "批量删除成功"); - } - -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/EsDocController.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/EsDocController.java new file mode 100644 index 0000000..e5108aa --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/EsDocController.java @@ -0,0 +1,34 @@ +package com.bawei.es.controller; + +import com.bawei.common.core.domain.R; +import com.bawei.common.core.web.domain.AjaxResult; +import com.bawei.es.service.EsDocService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/doc") +public class EsDocController { + @Autowired + private EsDocService esDocService; + + @GetMapping("/queryList/{indexName}") + public R queryList(@PathVariable String indexName, @RequestParam Map docMsg){ + return R.ok(esDocService.queryList(indexName,docMsg),"数据查询成功"); + } + + @PutMapping("/batchAddDoc/{indexName}") + public R batchAddDoc(@PathVariable String indexName, @RequestBody Map docMsg){ + esDocService.batchAddDoc(indexName,docMsg); + return R.ok(null,"批量操作文档数据成功"); + } + + @DeleteMapping("/bathDeleteDoc/{indexName}") + public R bathDeleteDoc(@PathVariable String indexName, @RequestBody List ids){ + esDocService.bathDeleteDoc(indexName,ids); + return R.ok(null,"批量删除文档数据成功"); + } +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/EsIndexController.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/EsIndexController.java new file mode 100644 index 0000000..0829d32 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/EsIndexController.java @@ -0,0 +1,43 @@ +package com.bawei.es.controller; + +import com.bawei.common.core.domain.R; +import com.bawei.common.core.web.domain.AjaxResult; +import com.bawei.es.service.EsIndexService; +import org.apache.ibatis.annotations.Update; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/index") +public class EsIndexController { + @Autowired + private EsIndexService esindexService; + + + + @PostMapping("/createIndex/{indexName}") + public R createIndex(@PathVariable String indexName, @RequestBody Map docMsg) { + return R.ok(esindexService.createIndex(indexName,docMsg),"索引添加成功"); + } + @PostMapping("/deleteIndex") + public R deleteIndex(String indexName) { + return R.ok(esindexService.deleteIndex(indexName),"es索引删除成功"); + } + + @PutMapping("/updateIndex") + public R updateIndex(@PathVariable String indexName,@RequestBody Map docMsg){ + return R.ok(esindexService.updateIndex(indexName,docMsg),"es索引修改成功"); + } + + @GetMapping("/findIndex/{indexName}") + public R findIndex(@PathVariable String indexName) { + return esindexService.findIndex(indexName) ? R.ok("es索引存在") : R.fail(500,"es索引不存在"); + } + + @PostMapping("/getMapping/{indexName}") + public R getMapping(@PathVariable String indexName) { + return R.ok(esindexService.getMapping(indexName),"索引映射存在"); + } +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/IndexController.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/IndexController.java deleted file mode 100644 index 7fca60b..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/controller/IndexController.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.bawei.es.controller; - -import com.bawei.common.core.domain.R; -import com.bawei.es.service.IndexService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import java.util.Map; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bwie.es.controller - * @ClassName: IndexController - * @Description: 请在此处填写具体描述 - * @Date: 2024/4/22 20:45 - */ -@RestController -@RequestMapping("/index") -@Api(tags = "es索引接口") -public class IndexController { - - @Resource(name = "indexServiceImpl") - private IndexService indexService; - - @GetMapping("/{indexName}") - @ApiOperation(value = "查询es索引是否存在") - public R exist(@PathVariable String indexName){ - return R.ok(indexService.exist(indexName),"es索引存在"); - } - - @GetMapping("/getMapping/{indexName}") - @ApiOperation(value = "获取索引映射") - public R getMapping(@PathVariable String indexName){ - return R.ok(indexService.getMapping(indexName),"索引映射存在"); - } - - @PostMapping("/{indexName}") - @ApiOperation(value = "添加索引") - public R index(@PathVariable String indexName,@RequestBody Map mappings){ - return R.ok(indexService.index(indexName,mappings),"es索引添加成功"); - } - - @PutMapping("/{indexName}") - @ApiOperation(value = "修改索引") - public R updateIndex(@PathVariable String indexName,@RequestBody Map mappings){ - return R.ok(indexService.updataIndex(indexName,mappings),"es索引修改成功"); - } - - @DeleteMapping("/{indexName}") - @ApiOperation(value = "删除索引") - public R deleteIndex(@PathVariable String indexName){ - return R.ok(indexService.deleteIndex(indexName),"es索引删除成功"); - } - -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/handler/GlobalExceptionHandler.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..a099b3d --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/handler/GlobalExceptionHandler.java @@ -0,0 +1,137 @@ +package com.bawei.es.handler; + +import com.bawei.common.core.constant.HttpStatus; +import com.bawei.common.core.exception.DemoModeException; +import com.bawei.common.core.exception.InnerAuthException; +import com.bawei.common.core.exception.ServiceException; +import com.bawei.common.core.exception.auth.NotPermissionException; +import com.bawei.common.core.exception.auth.NotRoleException; +import com.bawei.common.core.utils.StringUtils; +import com.bawei.common.core.web.domain.AjaxResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.validation.BindException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import javax.servlet.http.HttpServletRequest; + +/** + * 全局异常处理器 + * + * @author bawei + */ +@RestControllerAdvice +public class GlobalExceptionHandler +{ + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** + * 权限码异常 + */ + @ExceptionHandler(NotPermissionException.class) + public AjaxResult handleNotPermissionException(NotPermissionException e, HttpServletRequest request) + { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage(), e); + return AjaxResult.error(HttpStatus.FORBIDDEN, "没有访问权限,请联系管理员授权"); + } + + /** + * 角色权限异常 + */ + @ExceptionHandler(NotRoleException.class) + public AjaxResult handleNotRoleException(NotRoleException e, HttpServletRequest request) + { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage()); + return AjaxResult.error(HttpStatus.FORBIDDEN, "没有访问权限,请联系管理员授权"); + } + + /** + * 请求方式不支持 + */ + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, + HttpServletRequest request) + { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod()); + return AjaxResult.error(e.getMessage()); + } + + /** + * 业务异常 + */ + @ExceptionHandler(ServiceException.class) + public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) + { + log.error(e.getMessage(), e); + Integer code = e.getCode(); + return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage()); + } + + /** + * 拦截未知的运行时异常 + */ + @ExceptionHandler(RuntimeException.class) + public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) + { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',发生未知异常.", requestURI, e); + return AjaxResult.error(e.getMessage()); + } + + /** + * 系统异常 + */ + @ExceptionHandler(Exception.class) + public AjaxResult handleException(Exception e, HttpServletRequest request) + { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',发生系统异常.", requestURI, e); + return AjaxResult.error(e.getMessage()); + } + + /** + * 自定义验证异常 + */ + @ExceptionHandler(BindException.class) + public AjaxResult handleBindException(BindException e) + { + log.error(e.getMessage(), e); + String message = e.getAllErrors().get(0).getDefaultMessage(); + return AjaxResult.error(message); + } + + /** + * 自定义验证异常 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) + { + log.error(e.getMessage(), e); + String message = e.getBindingResult().getFieldError().getDefaultMessage(); + return AjaxResult.error(message); + } + + /** + * 内部认证异常 + */ + @ExceptionHandler(InnerAuthException.class) + public AjaxResult handleInnerAuthException(InnerAuthException e) + { + return AjaxResult.error(e.getMessage()); + } + + /** + * 演示模式异常 + */ + @ExceptionHandler(DemoModeException.class) + public AjaxResult handleDemoModeException(DemoModeException e) + { + return AjaxResult.error("演示模式,不允许操作"); + } +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocumentService.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocumentService.java deleted file mode 100644 index a3dfeb3..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/DocumentService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.bawei.es.service; - -import com.bawei.common.core.domain.R; - -import java.util.List; -import java.util.Map; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bwie.es.service - * @ClassName: DocumentService - * @Description: 请在此处填写具体描述 - * @Date: 2024/4/22 20:58 - */ -public interface DocumentService { - R queryList(String indexName, Map conditions); - - void batchOperation(String indexName, Map dataJson); - - void batchDeletion(String indexName, List dataJson); -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/EsDocService.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/EsDocService.java new file mode 100644 index 0000000..884898d --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/EsDocService.java @@ -0,0 +1,15 @@ +package com.bawei.es.service; + +import com.bawei.common.core.domain.R; +import com.bawei.common.core.web.domain.AjaxResult; + +import java.util.List; +import java.util.Map; + +public interface EsDocService { + void batchAddDoc(String indexName, Map docMsg); + + void bathDeleteDoc(String indexName, List ids); + + R queryList(String indexName, Map docMsg); +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/EsIndexService.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/EsIndexService.java new file mode 100644 index 0000000..ca90913 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/EsIndexService.java @@ -0,0 +1,15 @@ +package com.bawei.es.service; + +import java.util.Map; + +public interface EsIndexService { + boolean findIndex(String indexName); + + boolean createIndex(String indexName,Map docMsg); + + boolean deleteIndex(String indexName); + + Map getMapping(String indexName); + + boolean updateIndex(String indexName, Map docMsg); +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/IndexService.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/IndexService.java deleted file mode 100644 index 20026e5..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/IndexService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.bawei.es.service; - -import java.util.Map; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bwie.es.service - * @ClassName: EsService - * @Description: 请在此处填写具体描述 - * @Date: 2024/4/22 20:56 - */ -public interface IndexService { - boolean exist(String indexName); - - boolean index(String indexName, Map mappings); - - boolean updataIndex(String indexName, Map mappings); - - boolean deleteIndex(String indexName); - - Map getMapping(String indexName); -} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocumentServiceImpl.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocumentServiceImpl.java deleted file mode 100644 index 4851072..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/DocumentServiceImpl.java +++ /dev/null @@ -1,320 +0,0 @@ -package com.bawei.es.service.impl; - -import com.alibaba.fastjson2.JSONObject; -import com.bawei.common.core.domain.R; -import com.bawei.common.core.exception.ServiceException; -import com.bawei.common.core.utils.StringUtils; -import com.bawei.es.domain.CommonMap; -import com.bawei.es.service.DocumentService; -import org.elasticsearch.action.bulk.BulkRequest; -import org.elasticsearch.action.bulk.BulkResponse; -import org.elasticsearch.action.delete.DeleteRequest; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.client.RequestOptions; -import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.common.text.Text; -import org.elasticsearch.index.query.BoolQueryBuilder; -import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.index.query.RangeQueryBuilder; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; -import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; -import org.elasticsearch.search.sort.SortOrder; -import org.elasticsearch.xcontent.XContentType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import javax.annotation.Resource; -import java.io.IOException; -import java.util.*; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bwie.es.service.impl - * @ClassName: DocumentServiceImpl - * @Description: Elasticsearch 文档服务实现类 - * @Date: 2024/4/22 20:58 - */ -@Service -public class DocumentServiceImpl implements DocumentService { - - private static final Logger log = LoggerFactory.getLogger(DocumentServiceImpl.class); - - @Resource(name = "restHighLevelClient") - private RestHighLevelClient restHighLevelClient; - - @Override - public R queryList(String indexName, Map conditions) { - // 验证索引名 - validateIndexName(indexName); - - // 构建搜索请求 - SearchRequest searchRequest = buildSearchRequest(indexName, conditions); - - // 执行搜索 - SearchResponse searchResponse; - try { - searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); - } catch (IOException e) { - log.error("Failed to execute search request", e); - return R.fail("Query failed: " + e.getMessage()); - } - - // 解析搜索结果 - CommonMap result = processSearchResponse(searchResponse); - - return R.ok(result); - } - - private SearchRequest buildSearchRequest(String indexName, Map conditions) { - SearchRequest searchRequest = new SearchRequest(indexName); - SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); - - // 构造查询条件 - QueryBuilder queryBuilder = buildQueryBuilder(conditions); - sourceBuilder.query(queryBuilder); - - // 设置分页参数 - setPaginationParameters(conditions, sourceBuilder); - - // 设置排序参数 - setSortParameters(conditions, sourceBuilder); - - // 设置高亮参数 - setHighlightParameters(conditions, sourceBuilder); - - searchRequest.source(sourceBuilder); - - // 记录搜索请求的详细信息(仅用于调试) - log.debug("ES search request DDL: {}", sourceBuilder.toString()); - - return searchRequest; - } - - @Override - public void batchOperation(String indexName, Map dataJson) { - BulkRequest bulkRequest = new BulkRequest(); - - // 根据dataJson中的key,进行批量操作 - for (Map.Entry entry : dataJson.entrySet()) { - String id = entry.getKey(); - Map document = (Map) entry.getValue(); - - // 示例代码仅处理索引(index)和删除(delete)操作 - IndexRequest indexRequest = new IndexRequest(indexName).id(id).source(document, XContentType.JSON); - bulkRequest.add(indexRequest); - } - - try { - BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); - - // 检查批量操作结果,返回R对象 - if (bulkResponse.hasFailures()) { - throw new ServiceException("Bulk operation failed: " + bulkResponse.buildFailureMessage()); - } - } catch (IOException e) { - throw new ServiceException("批量操作失败: " + e.getMessage()); - } - } - - @Override - public void batchDeletion(String indexName, List ids) { - // 参数校验 - validateIndexName(indexName); - if (CollectionUtils.isEmpty(ids)) { - throw new IllegalArgumentException("请输入需要删除的文档ID集合"); - } - - BulkRequest bulkRequest = new BulkRequest(); - // 构建批量删除请求 - for (String id : ids) { - bulkRequest.add(new DeleteRequest(indexName, id)); - } - - try { - // 执行批量删除操作 - BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); - // 检查批量删除结果 - if (bulkResponse.hasFailures()) { - throw new RuntimeException("批量删除失败: " + bulkResponse.buildFailureMessage()); - } - } catch (IOException e) { - throw new RuntimeException("执行批量删除操作时发生错误: " + e.getMessage(), e); - } - } - - /** - * 校验索引名称是否为空 - * @param indexName 索引名称 - */ - private void validateIndexName(String indexName) { - if (StringUtils.isBlank(indexName)) { - throw new ServiceException("索引名为空,请重试!"); - } - } - - private void setPaginationParameters(Map conditions, SearchSourceBuilder sourceBuilder) { - // 从条件中获取分页信息 - Map pagination = (Map) conditions.get("pagination"); - if (pagination == null) { - // 如果没有分页信息,则不设置分页参数 - return; - } - - // 校验并获取分页参数 - int page; - int limit; - try { - page = Integer.parseInt(pagination.getOrDefault("page", "1").toString()); - limit = Integer.parseInt(pagination.getOrDefault("limit", "10").toString()); - } catch (NumberFormatException e) { - // 如果分页参数不是整数,则抛出异常 - throw new IllegalArgumentException("Invalid pagination parameters: page and limit must be integers", e); - } - - // 设置分页参数 - int from = (page - 1) * limit; - sourceBuilder.from(from).size(limit); - - // 记录日志(可选,根据实际需求决定是否记录) - log.debug("Pagination parameters set: page={}, limit={}, from={}", page, limit, from); - } - - private void setSortParameters(Map conditions, SearchSourceBuilder sourceBuilder) { - Map sort = (Map) conditions.get("sort"); - if (sort != null) { - Object sortOrderObject = sort.get("sortOrder"); - Object fieldObject = sort.get("field"); - - if (sortOrderObject instanceof String && fieldObject instanceof String) { - String sortOrder = (String) sortOrderObject; - String field = (String) fieldObject; - - if ("asc".equalsIgnoreCase(sortOrder) || "desc".equalsIgnoreCase(sortOrder)) { - SortOrder sortOrderEnum = "asc".equalsIgnoreCase(sortOrder) ? SortOrder.ASC : SortOrder.DESC; - log.info("Applying sort: field={}, sortOrder={}", field, sortOrder); - sourceBuilder.sort(field, sortOrderEnum); - } else { - SortOrder sortOrderEnum = SortOrder.ASC; - log.info("Applying sort: field={}, sortOrder={}", field, sortOrder); - sourceBuilder.sort(field, sortOrderEnum); - } - } else { - throw new IllegalArgumentException("Invalid sort parameters. Both 'sortOrder' and 'field' must be strings."); - } - } - } - private void setHighlightParameters(Map conditions, SearchSourceBuilder sourceBuilder) { - Map highlightParams = (Map) conditions.get("highlight"); - if (highlightParams != null) { - HighlightBuilder highlightBuilder = new HighlightBuilder(); - List fieldNames = (List) highlightParams.getOrDefault("fields", Collections.emptyList()); - String preTag = (String) highlightParams.getOrDefault("preTag", ""); - String postTag = (String) highlightParams.getOrDefault("postTag", ""); - - for (String fieldName : fieldNames) { - highlightBuilder.field(fieldName); - } - - highlightBuilder.preTags(preTag); - highlightBuilder.postTags(postTag); - - sourceBuilder.highlighter(highlightBuilder); - } - } - - private CommonMap processSearchResponse(SearchResponse searchResponse) { - CommonMap result = new CommonMap(); - long totalHits = searchResponse.getHits().getTotalHits().value; - result.setTotal(totalHits); - - LinkedHashMap objectMap = new LinkedHashMap<>(); - for (SearchHit hit : searchResponse.getHits().getHits()) { - String sourceAsString = hit.getSourceAsString(); - HashMap parsedObject = JSONObject.parseObject(sourceAsString, HashMap.class); - String id = hit.getId(); - // 添加高亮信息到解析后的文档 - addHighlightedFields(hit.getHighlightFields(), parsedObject); - - objectMap.put(id, parsedObject); - log.info("查询出来的数据为:{}",JSONObject.toJSONString(parsedObject)); - } - log.info("查询出来的数据为:{}",JSONObject.toJSONString(objectMap)); - result.setObjectMap(objectMap); - - return result; - } - - private void addHighlightedFields(Map highlightFields, Map parsedObject) { - if (!highlightFields.isEmpty()) { - for (Map.Entry entry : highlightFields.entrySet()) { - String fieldName = entry.getKey(); - Text[] fragments = entry.getValue().fragments(); - StringBuilder highlightedValue = new StringBuilder(); - for (Text fragment : fragments) { - highlightedValue.append(fragment); - } - parsedObject.put(fieldName, highlightedValue); - } - } - } - - /** - * 根据条件构建Elasticsearch查询构建器 - * - * @param conditions 查询条件(键值对形式) - * @return Elasticsearch查询构建器 - */ - private QueryBuilder buildQueryBuilder(Map conditions) { - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - - if (conditions != null && !conditions.isEmpty()) { - for (Map.Entry entry : conditions.entrySet()) { - String field = entry.getKey(); - Object value = entry.getValue(); - - // 处理范围查询条件 - if (value instanceof Map && ((Map) value).containsKey("range")) { - Map rangeParams = (Map) value; - RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(field); - - String gt = (String) rangeParams.get("gt"); - if (gt != null) { - rangeQueryBuilder.gt(gt); - } - - String gte = (String) rangeParams.get("gte"); - if (gte != null) { - rangeQueryBuilder.gte(gte); - } - - String lt = (String) rangeParams.get("lt"); - if (lt != null) { - rangeQueryBuilder.lt(lt); - } - - String lte = (String) rangeParams.get("lte"); - if (lte != null) { - rangeQueryBuilder.lte(lte); - } - - boolQueryBuilder.filter(rangeQueryBuilder); - } - // 处理其他查询条件(如 match 查询) - else if (value instanceof String) { - boolQueryBuilder.filter(QueryBuilders.matchQuery(field, value)); - } - } - } - - return boolQueryBuilder; - } - -} \ No newline at end of file diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/EsDocServiceImpl.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/EsDocServiceImpl.java new file mode 100644 index 0000000..c017c59 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/EsDocServiceImpl.java @@ -0,0 +1,287 @@ +package com.bawei.es.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.bawei.common.core.domain.R; +import com.bawei.common.core.exception.ServiceException; +import com.bawei.common.core.utils.StringUtils; +import com.bawei.common.core.web.domain.AjaxResult; +import com.bawei.common.domain.ConmtMap; +import com.bawei.es.service.EsDocService; +import lombok.extern.log4j.Log4j2; +import org.elasticsearch.action.bulk.BulkRequest; +import org.elasticsearch.action.bulk.BulkResponse; +import org.elasticsearch.action.delete.DeleteRequest; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.common.text.Text; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.RangeQueryBuilder; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.SearchHits; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; +import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; +import org.elasticsearch.xcontent.XContentType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.elasticsearch.search.sort.SortOrder; + +import javax.swing.text.Highlighter; +import java.io.IOException; +import java.util.*; + +@Service +@Log4j2 +public class EsDocServiceImpl implements EsDocService { + @Autowired + private RestHighLevelClient restHighLevelClient; + + @Override + public void batchAddDoc(String indexName, Map docMsg) { + BulkRequest bulkRequest = new BulkRequest(); + for (Map.Entry entry : docMsg.entrySet()){ + String id = entry.getKey(); + Map value = (Map) entry.getValue(); + IndexRequest source = new IndexRequest(indexName).id(id).source(value, XContentType.JSON); + bulkRequest.add(source); + } + + try { + BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); + if(bulk.hasFailures()){ + throw new RuntimeException("Bulk operation failed: "+ bulk.buildFailureMessage()); + } + } catch (IOException e) { + throw new ServiceException("批量操作失败: "+e.getMessage()); + } + } + + @Override + public void bathDeleteDoc(String indexName, List ids) { + BulkRequest bulkRequest = new BulkRequest(); + + for (String id : ids){ + DeleteRequest deleteRequest = new DeleteRequest(indexName, String.valueOf(id)); + bulkRequest.add(deleteRequest); + } + + try { + BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT); + if(bulk.hasFailures()){ + throw new RuntimeException("批量删除失败: "+ bulk.buildFailureMessage()); + } + } catch (IOException e) { + throw new RuntimeException("批量删除失败:"+ e.getMessage()); + } + + + } + + @Override + public R queryList(String indexName, Map docMsg) { + // 验证索引名称 + checkedIndexName(indexName); + // 构造搜索请求 + SearchRequest searchRequest = builderRequest(indexName,docMsg); + // 执行搜索 + SearchResponse searchResponse; + try { + searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); + } catch (IOException e) { + log.error("ES 搜索 异常: {}",e.getMessage()); + return R.fail("ES 搜索 异常: "+e.getMessage()); + } + // 处理搜索结果 + ConmtMap response = processSearchResponse(searchResponse); + + return R.ok(response); + } + + private ConmtMap processSearchResponse(SearchResponse searchResponse) { + ConmtMap conmtMap = new ConmtMap(); + long total = searchResponse.getHits().getTotalHits().value; + conmtMap.setTotal(total); + + LinkedHashMap stringObjectLinkedHashMap = new LinkedHashMap<>(); + for (SearchHit hit : searchResponse.getHits().getHits()) { + String sourceAsString = hit.getSourceAsString(); + HashMap map = JSONObject.parseObject(sourceAsString, HashMap.class); + String id = hit.getId(); + // 添加高亮信息到最后解析的文档 + addHighlightedFields(hit.getHighlightFields(),map); + + stringObjectLinkedHashMap.put(id,map); + log.info("查询出来的数据是: {}",JSONObject.toJSONString(map)); + } + log.info("查询出来的数据是: {}",JSONObject.toJSONString(stringObjectLinkedHashMap)); + conmtMap.setObjectMap(stringObjectLinkedHashMap); + return conmtMap; + } + + private void addHighlightedFields(Map highlightFields, Map parsedObject) { + if (!highlightFields.isEmpty()) { + for (Map.Entry entry : highlightFields.entrySet()) { + String fieldName = entry.getKey(); + Text[] fragments = entry.getValue().fragments(); + StringBuilder highlightedValue = new StringBuilder(); + for (Text fragment : fragments) { + highlightedValue.append(fragment); + } + parsedObject.put(fieldName, highlightedValue); + } + } + } + + private SearchRequest builderRequest(String indexName,Map docMsg) { + SearchRequest request = new SearchRequest(indexName); + SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); + + // 构造查询条件 + QueryBuilder queryBuilder = builderQuery(docMsg); + sourceBuilder.query(queryBuilder); + + // 设置分页参数 + setPaginationParameters(docMsg,sourceBuilder); + + // 设置排序参数 + setSortParameters(docMsg,sourceBuilder); + + // 设置高亮参数 + setHighlightParameters(docMsg,sourceBuilder); + + request.source(sourceBuilder); + + // 打印请求参数 + log.debug("ES 搜索 请求参数: {}",sourceBuilder.toString()); + return request; + } + + private void setHighlightParameters(Map docMsg, SearchSourceBuilder sourceBuilder) { + // 获取高亮参数 + Map highlight = (Map) docMsg.get("highlight"); + // 判断是否需要高亮 + if(highlight != null){ + // 创建高亮构建器 + HighlightBuilder highlightBuilder = new HighlightBuilder(); + // 获取高亮字段 + List fields = (List) highlight.getOrDefault("fields", Collections.emptyList()); + // 获取高亮前缀 + String preTag = (String) highlight.getOrDefault("preTag", ""); + // 获取高亮后缀 + String postTag = (String) highlight.getOrDefault("postTag", ""); + // 循环设置高亮字段 + for (String field : fields) { + highlightBuilder.field(field); + } + // 设置高亮包裹 + highlightBuilder.preTags(preTag).postTags(postTag); + // 设置高亮 + sourceBuilder.highlighter(highlightBuilder); + } + } + + private void setSortParameters(Map docMsg, SearchSourceBuilder sourceBuilder) { + Map sort = (Map) docMsg.get("sort"); + if(sort != null){ + Object sortOrderObject = sort.get("sortOrder"); + Object fieldObject = sort.get("field"); + + if(sortOrderObject instanceof String && fieldObject instanceof String){ + String sortOrder = (String) sortOrderObject; + String field = (String) fieldObject; + + if("asc".equalsIgnoreCase(sortOrder) || "desc".equalsIgnoreCase(sortOrder)){ + SortOrder sortOrderEnum = "asc".equalsIgnoreCase(sortOrder) ? SortOrder.ASC : SortOrder.DESC; + log.info("排序字段:"+field+",排序方式:"+sortOrderEnum); + sourceBuilder.sort(field,sortOrderEnum); + }else { + SortOrder sortOrderEnum = SortOrder.ASC; + log.info("排序字段:"+field+",排序方式:"+sortOrderEnum); + sourceBuilder.sort(field,sortOrderEnum); + } + }else { + throw new IllegalArgumentException("排序参数有误"); + } + } + } + + private void setPaginationParameters(Map docMsg, SearchSourceBuilder sourceBuilder) { + // 从条件中获取分页信息 + Map pagination = (Map) docMsg.get("pagination"); + // 如果没有分页信息,则不设置分页参数 + if(pagination == null){ + return; + } + // 获取分页参数 + int page; + int limit; + try { + // 获取分页参数 + page = Integer.parseInt(pagination.getOrDefault("page","1").toString()); + limit = Integer.parseInt(pagination.getOrDefault("limit","10").toString()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("分页参数有误", e); + } + // 计算分页参数 + int form = (page - 1) * limit; + // 设置分页参数 + sourceBuilder.from(form).size(limit); + // 打印分页参数 + log.debug("Pagination parameters set: page={}, limit={}, from={}" , page, limit, form); + } + + + private QueryBuilder builderQuery(Map docMsg) { + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + + if(docMsg != null && !docMsg.isEmpty()){ + for (Map.Entry entry : docMsg.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + + if(value instanceof Map && ((Map) value).containsKey("range")){ + Map rangeParms = (Map) value; + RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(key); + + String gt = (String) rangeParms.get("gt"); + + if(StringUtils.isNotBlank(gt)){ + rangeQueryBuilder.gt(gt); + } + + String gte = (String) rangeParms.get("gte"); + if(StringUtils.isNotBlank(gte)){ + rangeQueryBuilder.gte(gte); + } + + String lt = (String) rangeParms.get("lt"); + if(StringUtils.isNotBlank(lt)){ + rangeQueryBuilder.lt(lt); + } + + String lte = (String) rangeParms.get("lte"); + if(StringUtils.isNotBlank(lte)){ + rangeQueryBuilder.lte(lte); + } + + boolQueryBuilder.filter(rangeQueryBuilder); + }else if(value instanceof String) { + boolQueryBuilder.filter(QueryBuilders.matchQuery(key,value)); + } + } + } + return boolQueryBuilder; + } + + public void checkedIndexName(String indexName){ + if(StringUtils.isBlank(indexName)){ + throw new ServiceException("索引名称为空,请重试"); + } + } +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/EsIndexServiceImpl.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/EsIndexServiceImpl.java new file mode 100644 index 0000000..1549a16 --- /dev/null +++ b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/EsIndexServiceImpl.java @@ -0,0 +1,203 @@ +package com.bawei.es.service.impl; + +import com.bawei.common.core.exception.ServiceException; +import com.bawei.common.core.utils.StringUtils; +import com.bawei.es.service.EsIndexService; +import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; +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.client.indices.GetIndexResponse; +import org.elasticsearch.cluster.metadata.MappingMetadata; +import org.elasticsearch.common.settings.Setting; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.xcontent.XContentBuilder; +import org.elasticsearch.xcontent.XContentFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.io.IOException; +import java.util.Map; + +@Service +public class EsIndexServiceImpl implements EsIndexService { + @Resource + private RestHighLevelClient restHighLevelClient; + private static final Logger logger = LoggerFactory.getLogger(EsIndexService.class); + + @Override + public boolean findIndex(String indexName) { + if (indexName == null || indexName.isEmpty()){ + throw new ServiceException("索引名称不能为空"); + } + try { + GetIndexRequest request = new GetIndexRequest(indexName); + GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT); + // 直接使用 response.indices() 是否包含 indexName 来判断 + String[] indices = response.getIndices(); + for (String index : indices) { + if (index.equals(indexName)) { + return true; + } + } + return false; + } catch (Exception e) { + // 特别处理 index_not_found_exception + if (e.getMessage().contains("no such index")) { + logger.info("索引 [{}] 不存在", indexName); + return false; + } else { + // 记录其他类型的异常 + logger.error("查询索引 [{}] 状态时发生错误: {}", indexName, e.getMessage(), e); + throw new ServiceException("查询索引状态时发生错误"); + } + } + } + + @Override + public boolean createIndex(String indexName, Map docMsg) { + if (StringUtils.isBlank(indexName)) { + throw new ServiceException("索引名称不可为空"); + } + // 判断索引是否存在 + boolean index = this.findIndex(indexName); + if(index){ + throw new ServiceException("索引" + indexName + "已存在"); + } + try { + // + Settings.Builder settingsBuilder = Settings.builder(); + XContentBuilder mappingBuilder = null; + + if(docMsg != null && !docMsg.isEmpty()){ + mappingBuilder = createMapping(docMsg); + } + CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName) + .settings(settingsBuilder); + if(mappingBuilder != null){ + createIndexRequest.mapping(mappingBuilder); + } + CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT); + return createIndexResponse.isAcknowledged(); + } + catch (IOException e) { + System.out.println("创建索引时发生错误: " + e.getMessage()); + throw new ServiceException("创建索引时发生错误"); + } + } + + /** + * 创建文档映射 + * @param docMsg 包含文档字段及其类型的映射 + * @return XContentBuilder 对象,包含构建的文档映射结构 + * @throws IOException 如果构建过程中发生IO异常 + */ + private XContentBuilder createMapping(Map docMsg) throws IOException { + // 初始化XContentBuilder对象,开始构建JSON对象 + XContentBuilder xContentBuilder = XContentFactory.jsonBuilder() + .startObject() + .startObject("properties"); + + // 遍历docMsg,为每个字段构建映射 + for (Map.Entry entry : docMsg.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + xContentBuilder.startObject(key); + + if(value instanceof Map){ + // 如果字段值是Map类型,则递归处理 + Map stringObjectMap = (Map) value; + // 遍历内部映射,添加到当前字段 + for (Map.Entry stringObjectEntry : stringObjectMap.entrySet()) { + String key1 = stringObjectEntry.getKey(); + Object value1 = stringObjectEntry.getValue(); + xContentBuilder.field(key1,value1); + } + }else { + // 如果字段值不是Map类型,将其作为类型字段添加 + xContentBuilder.field("type",value.toString()); + } + xContentBuilder.endObject(); + } + // 结束"properties"对象和整个JSON对象的构建 + xContentBuilder.endObject().endObject(); + return xContentBuilder; + } + + + @Override + public boolean deleteIndex(String indexName) { + // 判空 + if(StringUtils.isBlank(indexName)){ + throw new ServiceException("索引名称不可为空"); + } + // 删除索引 + try { + restHighLevelClient.indices().delete(new DeleteIndexRequest(indexName), RequestOptions.DEFAULT); + return true; + } catch (Exception e) { + System.err.println("删除索引失败: " + e.getMessage()); + throw new ServiceException("删除索引失败"); + } + } + + @Override + public Map getMapping(String indexName) { + if(StringUtils.isBlank(indexName)){ + throw new RuntimeException("索引名称不能为空"); + } + // 创建索引请求 + GetIndexRequest getIndexRequest = new GetIndexRequest(indexName); + try { + // 获取索引 + GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT); + for (String index : getIndexResponse.getIndices()) { + // 判断索引 + if(index.equals(indexName)){ + // 获取映射 + Map mappings = getIndexResponse.getMappings(); + MappingMetadata mappingMetadata = mappings.get(indexName); + // 判断映射是否为空 + if(mappingMetadata != null){ + // 获取映射 + Map properties = (Map) mappingMetadata.getSourceAsMap().get("properties"); + // 判断映射是否为空 + if(properties == null){ + throw new ServiceException("索引映射为空"); + } + // 返回映射 + return properties; + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + throw new ServiceException("索引不存在,请重试"); + } + + @Override + public boolean updateIndex(String indexName, Map docMsg) { + try { + if (indexName!=null && !indexName.isEmpty()){ + if (Boolean.FALSE.equals(findIndex(indexName))) { + createIndex(indexName,docMsg); + return true; + }else { + deleteIndex(indexName); + createIndex(indexName,docMsg); + return true; + } + }else { + throw new ServiceException("索引名字为空,请重试!!!"); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/IndexServiceImpl.java b/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/IndexServiceImpl.java deleted file mode 100644 index 5599053..0000000 --- a/bawei-base/base-es/base-es-server/src/main/java/com/bawei/es/service/impl/IndexServiceImpl.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.bawei.es.service.impl; - -import com.bawei.common.core.exception.ServiceException; -import com.bawei.es.service.IndexService; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; -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.client.indices.GetIndexResponse; -import org.elasticsearch.cluster.metadata.MappingMetadata; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.io.IOException; -import java.util.Map; - -/** - * @Author: 31966 - * @Project: mall-product - * @Package: com.bwie.es.service.impl - * @ClassName: EsServiceImpl - * @Description: 请在此处填写具体描述 - * @Date: 2024/4/22 20:56 - */ -@Service -public class IndexServiceImpl implements IndexService { - - @Autowired - private RestHighLevelClient restHighLevelClient; - - @Override - public boolean exist(String indexName) { - if (indexName == null || indexName.isEmpty()){ - throw new ServiceException("索引名称不能为空"); - } - try { - GetIndexRequest request = new GetIndexRequest(indexName); - GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT); - // 检查响应中是否包含指定的索引 - for (String index : response.getIndices()) { - if (index.equals(indexName)){ - return true; - } - } - } catch (Exception e) { - // 处理异常,例如记录日志或返回false表示索引不存在 - e.printStackTrace(); - } - return false; - } - - @Override - public boolean index(String indexName, Map mappings) { - // 参数校验 - if (indexName == null || indexName.isEmpty()) { - throw new ServiceException("Index name cannot be null or empty"); - } - // 判断索引是否存在 - boolean indexExists = exist(indexName); - if (indexExists) { - throw new ServiceException("索引 " + indexName + " 已存在"); - } - // 创建索引并设置映射(根据mappings非空情况) - try { - Settings.Builder settingsBuilder = Settings.builder(); - XContentBuilder mappingBuilder = null; - - if (mappings != null && !mappings.isEmpty()) { - // 设置映射 - mappingBuilder = createMapping(mappings); - } - - CreateIndexRequest request = new CreateIndexRequest(indexName) - .settings(settingsBuilder); - if (mappingBuilder!=null){ - request.mapping(mappingBuilder); - } - CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); - return response.isAcknowledged(); - } catch (IOException e) { - System.err.println("创建索引时发生错误: " + e.getMessage()); - throw new ServiceException("创建索引时发生错误"); - } - } - - @Override - public boolean updataIndex(String indexName, Map mappings) { - try { - if (indexName!=null && !indexName.isEmpty()){ - if (Boolean.FALSE.equals(exist(indexName))) { - index(indexName,mappings); - return true; - }else { - deleteIndex(indexName); - index(indexName,mappings); - return true; - } - }else { - throw new ServiceException("索引名字为空,请重试!!!"); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean deleteIndex(String indexName) { - // 删除索引 - try { - restHighLevelClient.indices().delete(new DeleteIndexRequest(indexName), RequestOptions.DEFAULT); - return true; - } catch (Exception e) { - System.err.println("Error deleting index: " + e.getMessage()); - throw new ServiceException("Error deleting index"); - } - } - - @Override - public Map getMapping(String indexName) { - if (indexName == null || indexName.isEmpty()) { - throw new ServiceException("索引名称不能为空"); - } - try { - GetIndexRequest request = new GetIndexRequest(indexName); - GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT); - - // 检查响应中是否包含指定的索引 - for (String index : response.getIndices()) { - if (index.equals(indexName)) { - Map mappings = response.getMappings(); - - // 提取并返回指定索引的映射结构 - MappingMetadata mappingMetadata = mappings.get(indexName); - if (mappingMetadata != null) { - Map map = (Map) mappingMetadata.getSourceAsMap().get("properties"); - if (map==null){ - throw new ServiceException("索引映射为空"); - } - return map; - } - } - } - } catch (Exception e) { - // 处理异常,例如记录日志 - e.printStackTrace(); - } - - // 索引不存在或获取映射失败,返回null - throw new ServiceException("索引不存在,请重试"); - } - - /** - * 根据给定的映射创建XContentBuilder - */ - private XContentBuilder createMapping(Map mappings) throws IOException { - XContentBuilder builder = XContentFactory.jsonBuilder() - .startObject() - .startObject("properties"); - - for (Map.Entry entry : mappings.entrySet()) { - String fieldName = entry.getKey(); - Object fieldConfig = entry.getValue(); - - builder.startObject(fieldName); // Start field mapping - - if (fieldConfig instanceof Map) { - @SuppressWarnings("unchecked") - Map nestedMapping = (Map) fieldConfig; - - for (Map.Entry nestedEntry : nestedMapping.entrySet()) { - String nestedFieldName = nestedEntry.getKey(); - Object nestedFieldConfig = nestedEntry.getValue(); - - builder.field(nestedFieldName, nestedFieldConfig); - } - } else { - builder.field("type", fieldConfig.toString()); // Add field type - } - - builder.endObject(); // End field mapping - } - - builder.endObject() // End "properties" - .endObject(); // End root object - - return builder; - } - -} diff --git a/bawei-base/base-es/base-es-server/src/main/resources/banner.txt b/bawei-base/base-es/base-es-server/src/main/resources/banner.txt deleted file mode 100644 index 27cacb9..0000000 --- a/bawei-base/base-es/base-es-server/src/main/resources/banner.txt +++ /dev/null @@ -1,10 +0,0 @@ -Spring Boot Version: ${spring-boot.version} -Spring Application Name: ${spring.application.name} - _ __ _ _ - (_) / _|(_)| | - _ __ _ _ ___ _ _ _ ______ | |_ _ | | ___ -| '__|| | | | / _ \ | | | || ||______|| _|| || | / _ \ -| | | |_| || (_) || |_| || | | | | || || __/ -|_| \__,_| \___/ \__, ||_| |_| |_||_| \___| - __/ | - |___/ \ No newline at end of file diff --git a/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml b/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml index 36c2ac4..90c9077 100644 --- a/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml +++ b/bawei-base/base-es/base-es-server/src/main/resources/bootstrap.yml @@ -1,12 +1,12 @@ # Tomcat server: - port: 9204 + port: 9123 # Spring spring: application: # 应用名称 - name: bawei-es + name: bawei-base-es profiles: # 环境配置 active: dev @@ -14,14 +14,36 @@ spring: nacos: discovery: # 服务注册地址 - server-addr: 127.0.0.1:8848 - namespace: 12345678 + server-addr: 124.222.99.46:8848 config: # 配置中心地址 - server-addr: 127.0.0.1:8848 + server-addr: 124.222.99.46:8848 # 配置文件格式 file-extension: yml # 共享配置 shared-configs: - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} - namespace: 12345678 +springdoc: + swagger-ui: + path: /swagger-ui.html + tags-sorter: alpha + operations-sorter: alpha +api-docs: + path: v3/api-docs # 指定生成文档的路径,网关会访问这个路径来拉取文档 + group-configs: + - group: 'default' + paths-to-match: '/**' + packages-to-scan: com.keyl1me.edu.controller # 指定要扫描的包 + +knife4j: + enable: true # 开启knife4j接口文档美化 + setting: + language: zh_cn # 指定语言 +# feign 配置 +feign: + compression: + request: + enabled: true + min-request-size: 8192 + response: + enabled: true diff --git a/bawei-base/base-es/base-es-server/src/main/resources/logback.xml b/bawei-base/base-es/base-es-server/src/main/resources/logback.xml deleted file mode 100644 index 55159ec..0000000 --- a/bawei-base/base-es/base-es-server/src/main/resources/logback.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - ${log.pattern} - - - - - - ${log.path}/info.log - - - - ${log.path}/info.%d{yyyy-MM-dd}.log - - 60 - - - ${log.pattern} - - - - INFO - - ACCEPT - - DENY - - - - - ${log.path}/error.log - - - - ${log.path}/error.%d{yyyy-MM-dd}.log - - 60 - - - ${log.pattern} - - - - ERROR - - ACCEPT - - DENY - - - - - - - - - - - - - - - - - - diff --git a/bawei-base/base-es/pom.xml b/bawei-base/base-es/pom.xml index e8482d4..42ff87a 100644 --- a/bawei-base/base-es/pom.xml +++ b/bawei-base/base-es/pom.xml @@ -8,14 +8,8 @@ bawei-base 3.6.0 + base-es pom - - base-es es服务 - - - base-es-server - base-es-remote - base-es-common - + diff --git a/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/controller/MallProductInfoController.java b/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/controller/MallProductInfoController.java index e04d26e..81ae4b5 100644 --- a/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/controller/MallProductInfoController.java +++ b/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/controller/MallProductInfoController.java @@ -1,7 +1,6 @@ package com.bawei.mall.product.controller; import java.util.List; -import java.io.IOException; import javax.servlet.http.HttpServletResponse; import com.bawei.common.core.domain.R; @@ -9,7 +8,6 @@ import com.bawei.mall.product.domain.reponse.ProductDetailsResponse; import com.bawei.mall.product.domain.reponse.ProductInfoResponse; import com.bawei.mall.product.domain.request.ProductInfoRequest; import io.swagger.annotations.Api; -import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; @@ -49,7 +47,10 @@ public class MallProductInfoController extends BaseController List list = mallProductInfoService.selectMallProductInfoList(mallProductInfo); return getDataTable(list); } - + @RequestMapping("/show") + public void queryJson(){ + mallProductInfoService.queryJson(); + } @PostMapping("/syncList") public TableDataInfo syncList(@RequestBody MallProductInfo mallProductInfo) { @@ -85,6 +86,14 @@ public class MallProductInfoController extends BaseController util.exportExcel(response, list, "商品信息数据"); } + /** + * 添加es查询 + */ + @GetMapping("/esList") + public R esList(){ + return mallProductInfoService.esList(); + } + /** * 获取商品信息详细信息 */ diff --git a/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/IMallProductInfoService.java b/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/IMallProductInfoService.java index 5095c90..c3447a3 100644 --- a/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/IMallProductInfoService.java +++ b/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/IMallProductInfoService.java @@ -1,6 +1,8 @@ package com.bawei.mall.product.service; import java.util.List; + +import com.bawei.common.core.domain.R; import com.bawei.mall.product.domain.MallProductInfo; import com.bawei.mall.product.domain.reponse.ProductDetailsResponse; import com.bawei.mall.product.domain.reponse.ProductInfoResponse; @@ -70,5 +72,11 @@ public interface IMallProductInfoService */ Long selectMallProductInfoCount (MallProductInfo mallProductInfo); - void unmout(Long id, String type); + void queryJson(); + + void unmout(Long id, java.lang.String status); + + + R esList(); + } diff --git a/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/impl/MallProductInfoServiceImpl.java b/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/impl/MallProductInfoServiceImpl.java index ebdb301..5d909f8 100644 --- a/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/impl/MallProductInfoServiceImpl.java +++ b/bawei-mall/bawei-mall-product/bawei-mall-product-server/src/main/java/com/bawei/mall/product/service/impl/MallProductInfoServiceImpl.java @@ -1,15 +1,26 @@ package com.bawei.mall.product.service.impl; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.TypeReference; +import com.bawei.common.core.domain.R; import com.bawei.common.core.exception.ServiceException; import com.bawei.common.core.utils.DateUtils; -import com.bawei.common.core.utils.StringUtils; import com.bawei.common.core.utils.bean.BeanUtils; -import com.bawei.common.core.utils.thread.ThreadPool; import com.bawei.common.rabbit.domain.Message; import com.bawei.common.rabbit.enums.QueueEnum; import com.bawei.common.security.utils.SecurityUtils; +import com.bawei.es.remote.api.RemoteDocumentService; +import com.bawei.es.remote.api.RemoteIndexService; import com.bawei.mall.product.cache.ProductInfoCache; import com.bawei.mall.product.domain.MallProductRuleInfo; import com.bawei.mall.product.domain.MallProductSkuInfo; @@ -20,6 +31,7 @@ import com.bawei.mall.product.domain.reponse.ProductInfoResponse; import com.bawei.mall.product.domain.request.ProductInfoRequest; import com.bawei.mall.product.service.IMallProductRuleInfoService; import com.bawei.mall.product.service.IMallProductSkuInfoService; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -27,7 +39,6 @@ import com.bawei.mall.product.mapper.MallProductInfoMapper; import com.bawei.mall.product.domain.MallProductInfo; import com.bawei.mall.product.service.IMallProductInfoService; import org.springframework.transaction.annotation.Transactional; -import org.w3c.dom.ranges.RangeException; /** * 商品信息Service业务层处理 @@ -54,6 +65,12 @@ public class MallProductInfoServiceImpl implements IMallProductInfoService @Autowired private RabbitTemplate rabbitTemplate; + @Autowired + private RemoteDocumentService remoteDocumentService; + + @Autowired + private RemoteIndexService remoteIndexService; + /** * 查询商品信息 * @@ -120,7 +137,7 @@ public class MallProductInfoServiceImpl implements IMallProductInfoService @Transactional public int insertMallProductInfo(ProductInfoRequest productInfoRequest) { - productInfoRequest.setCreateBy(String.valueOf(SecurityUtils.getUserId())); + productInfoRequest.setCreateBy(java.lang.String.valueOf(SecurityUtils.getUserId())); productInfoRequest.setCreateTime(DateUtils.getNowDate()); int i = mallProductInfoMapper.insertMallProductInfo(productInfoRequest); if (i == 0){ @@ -200,38 +217,73 @@ public class MallProductInfoServiceImpl implements IMallProductInfoService return mallProductInfoMapper.selectMallProductInfoCount(mallProductInfo); } + @Override - public void unmout(Long id, String status) { - if(id==null && id==0){ - throw new RuntimeException("id不能为空"); - } - if (status==null || status.equals("")){ - throw new RuntimeException("商品状态不能为空"); - } - MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id); - if (mallProductInfo.getStatus().equals("0")){ - if (status.equals("1")){ + public void queryJson() { + Path pathJson = Paths.get("."); + try { + List collect = Files.walk(pathJson) + .filter(Files::isRegularFile) + .filter(path -> path.toString().endsWith(".json")) + .collect(Collectors.toList()); + //根据文件路径查找文件 + collect.forEach(path -> { + try { + String json = new String(Files.readAllBytes(path)); + JSONObject jsonObject = JSONObject.parseObject(json); + Object javaObject = JSONObject.toJavaObject(jsonObject, Object.class); + System.out.println(javaObject); + } catch (Exception e) { + e.printStackTrace(); + } + }); + }catch(Exception e){ + throw new RuntimeException(e); + } + } + + @Override + public void unmout(Long id, java.lang.String status) { + if(id==null && id==0){ + throw new RuntimeException("id不能为空"); + } + if (status==null || status.equals("")){ + throw new RuntimeException("商品状态不能为空"); + } + MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id); + if (mallProductInfo==null){ + throw new RuntimeException("商品不存在"); + } + //判断修改的状态和数据库里的状态是否冲突 + if (mallProductInfo.getStatus().equals("0") && status.equals("0")){ + throw new RuntimeException("商品已上架"); + }else if (mallProductInfo.getStatus().equals("1") && status.equals("1")){ + throw new RuntimeException("商品已下架"); + } + R shop = remoteIndexService.exist("shop"); + if (shop.isSuccess()){ + R r = remoteIndexService.deleteIndex("shop"); + if (r.isSuccess()){ + //删除该索引后,进行修改数据 mallProductInfo.setStatus(status); mallProductInfoMapper.updateMallProductInfo(mallProductInfo); + }else { - throw new RuntimeException("商品已上架"); + throw new RuntimeException("删除索引失败"); } - - }else { - if (status.equals("1")){ - throw new RuntimeException("商品已下架"); - }else { - mallProductInfo.setStatus(status); - mallProductInfoMapper.updateMallProductInfo(mallProductInfo); - } - - } - - - - - - + } } + + @Override + public R esList() { + //添加es列表查询 + if (remoteIndexService.exist("shop").isSuccess()){ + //查询es列表 + R shop = remoteDocumentService.queryList("shop", null); + return R.ok(shop.getData()); + } + return null; + } + } diff --git a/docker/indexShowJson.json b/docker/indexShowJson.json new file mode 100644 index 0000000..3ac353d --- /dev/null +++ b/docker/indexShowJson.json @@ -0,0 +1,47 @@ +{ + "mappings": { + "dynamic": "strict", + "properties": { + "mainImage": { + "type": "keyword" + }, + "spuid": { + "type": "integer" + }, + "skuId": { + "type": "integer" + }, + "mainTitle": { + "type": "text" + }, + "subTitle": { + "type": "text" + }, + "price": { + "type": "scaled_float", + "scaling_factor": 100 + }, + "productTypeValue": { + "type": "integer" + }, + "productTypeName": { + "type": "text" + }, + "productBrandValue": { + "type": "integer" + }, + "productBrandName": { + "type": "text" + }, + "productRuleValue": { + "type": "integer" + }, + "productRuleName": { + "type": "text" + }, + "productDesc": { + "type": "text" + } + } + } +} diff --git a/indexNameJson.json b/indexNameJson.json new file mode 100644 index 0000000..3ac353d --- /dev/null +++ b/indexNameJson.json @@ -0,0 +1,47 @@ +{ + "mappings": { + "dynamic": "strict", + "properties": { + "mainImage": { + "type": "keyword" + }, + "spuid": { + "type": "integer" + }, + "skuId": { + "type": "integer" + }, + "mainTitle": { + "type": "text" + }, + "subTitle": { + "type": "text" + }, + "price": { + "type": "scaled_float", + "scaling_factor": 100 + }, + "productTypeValue": { + "type": "integer" + }, + "productTypeName": { + "type": "text" + }, + "productBrandValue": { + "type": "integer" + }, + "productBrandName": { + "type": "text" + }, + "productRuleValue": { + "type": "integer" + }, + "productRuleName": { + "type": "text" + }, + "productDesc": { + "type": "text" + } + } + } +} diff --git a/sql/indexNameJson.json b/sql/indexNameJson.json new file mode 100644 index 0000000..3ac353d --- /dev/null +++ b/sql/indexNameJson.json @@ -0,0 +1,47 @@ +{ + "mappings": { + "dynamic": "strict", + "properties": { + "mainImage": { + "type": "keyword" + }, + "spuid": { + "type": "integer" + }, + "skuId": { + "type": "integer" + }, + "mainTitle": { + "type": "text" + }, + "subTitle": { + "type": "text" + }, + "price": { + "type": "scaled_float", + "scaling_factor": 100 + }, + "productTypeValue": { + "type": "integer" + }, + "productTypeName": { + "type": "text" + }, + "productBrandValue": { + "type": "integer" + }, + "productBrandName": { + "type": "text" + }, + "productRuleValue": { + "type": "integer" + }, + "productRuleName": { + "type": "text" + }, + "productDesc": { + "type": "text" + } + } + } +}