修改esbug

customer
gyc 2024-04-27 14:32:41 +08:00
parent 6d7e98a31e
commit 770d7cc049
40 changed files with 1233 additions and 1071 deletions

View File

@ -2,12 +2,13 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>base-es</artifactId>
<groupId>com.bawei</groupId>
<version>3.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bawei</groupId>
<artifactId>bawei-base</artifactId>
<version>3.6.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>base-es-common</artifactId>
@ -16,7 +17,6 @@
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 项目公共核心依赖 -->
@ -25,4 +25,5 @@
<artifactId>bawei-common-core</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -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<String,Object> objectMap;
}

View File

@ -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<String,Object> objectMap;
}

View File

@ -2,12 +2,13 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>base-es</artifactId>
<groupId>com.bawei</groupId>
<version>3.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bawei</groupId>
<artifactId>bawei-base</artifactId>
<version>3.6.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>base-es-remote</artifactId>
@ -16,13 +17,11 @@
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 文件服务公共依赖 -->
<dependency>
<groupId>com.bawei</groupId>
<artifactId>base-es-common</artifactId>
<version>3.6.0</version>
</dependency>
</dependencies>
</project>

View File

@ -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<String,Object> docMsg);
@PutMapping("/batchAddDoc/{indexName}")
public R batchAddDoc(@PathVariable("indexName") String indexName, @RequestBody Map<String,Object> docMsg);
@DeleteMapping("/bathDeleteDoc/{indexName}")
public R bathDeleteDoc(@PathVariable("indexName") String indexName, @RequestBody List<String> ids);
}

View File

@ -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<String,Object> docMsg);
@PostMapping("/deleteIndex/{indexName}")
public R deleteIndex(@PathVariable("indexName") String indexName);
@PutMapping("/updateIndex/{indexName}")
public R updateIndex(@PathVariable("indexName") String indexName,@RequestBody Map<String,Object> docMsg);
@GetMapping("/findIndex/{indexName}")
public R findIndex(@PathVariable("indexName") String indexName);
@PostMapping("/getMapping/{indexName}")
public R getMapping(@PathVariable("indexName") String indexName);
}

View File

@ -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<String,Object> conditions);
@PutMapping("/doc/{indexName}")
R batchDocument(@PathVariable(value = "indexName") String indexName, @RequestBody List<String> dataJson);
@DeleteMapping("/doc/{indexName}")
R batchDeleteDocument(@PathVariable(value = "indexName") String indexName, @RequestBody List<String> dataJson);
}

View File

@ -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<String,Object> mappings);
@PutMapping("/index/{indexName}")
public R updateIndex(@PathVariable(value = "indexName") String indexName,@RequestBody Map<String,Object> mappings);
@DeleteMapping("/index/{indexName}")
public R deleteIndex(@PathVariable(value = "indexName") String indexName);
}

View File

@ -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<EsDocRemoteService> {
@Override
public EsDocRemoteService create(Throwable cause) {
return new EsDocRemoteService() {
@Override
public R queryList(String indexName, Map<String, Object> docMsg) {
log.error("调用查询信息远程服务失败{}-{}-{}-{}",indexName,docMsg,cause.getMessage(),cause);
return R.fail();
}
@Override
public R batchAddDoc(String indexName, Map<String, Object> docMsg) {
log.error("调用批量添加信息远程服务失败{}-{}-{}",indexName,cause.getMessage(),cause);
return R.fail();
}
@Override
public R bathDeleteDoc(String indexName, List<String> ids) {
log.error("调用批量删除信息远程服务失败{}-{}-{}-{}",indexName,ids,cause.getMessage(),cause);
return R.fail();
}
};
}
}

View File

@ -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<EsIndexRemoteService> {
@Override
public EsIndexRemoteService create(Throwable cause) {
return new EsIndexRemoteService() {
@Override
public R createIndex(String indexName, Map<String, Object> 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<String, Object> docMsg) {
log.error("远程调用修改索引服务失败:{}-{}-{}{}",indexName,docMsg,cause.getMessage(),cause);
return R.fail();
}
};
}
}

View File

@ -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<RemoteDocumentService>
{
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<String, Object> conditions) {
return R.fail();
}
@Override
public R batchDocument(String indexName, List<String> dataJson) {
return R.fail();
}
@Override
public R batchDeleteDocument(String indexName, List<String> dataJson) {
return R.fail();
}
};
}
}

View File

@ -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<RemoteIndexService>
{
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<String, Object> mappings) {
return R.fail();
}
@Override
public R updateIndex(String indexName, Map<String, Object> mappings) {
return R.fail();
}
@Override
public R deleteIndex(String indexName) {
return R.fail();
}
};
}
}

View File

@ -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

View File

@ -2,12 +2,13 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>base-es</artifactId>
<groupId>com.bawei</groupId>
<version>3.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bawei</groupId>
<artifactId>bawei-base</artifactId>
<version>3.6.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>base-es-server</artifactId>
@ -16,9 +17,12 @@
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
<!-- SpringCloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
@ -51,7 +55,23 @@
<dependency>
<groupId>com.bawei</groupId>
<artifactId>bawei-common-security</artifactId>
<artifactId>bawei-common-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.7.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
@ -59,7 +79,7 @@
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
<!-- BaWei Common DataScope -->
<!-- es-common -->
<dependency>
<groupId>com.bawei</groupId>
<artifactId>base-es-common</artifactId>

View File

@ -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);
}
}

View File

@ -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))
);
}
}

View File

@ -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;
}
}

View File

@ -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<String,Object> conditions){
return documentService.queryList(indexName,conditions);
}
@PutMapping("/{indexName}")
@ApiOperation(value = "批量操作数据")
public R batchDocument(@PathVariable String indexName, @RequestBody Map<String,Object> dataJson){
documentService.batchOperation(indexName,dataJson);
return R.ok(null, "批量操作成功");
}
@DeleteMapping("/{indexName}")
@ApiOperation(value = "批量删除")
public R batchDeleteDocument(@PathVariable String indexName, @RequestBody List<String> dataJson){
documentService.batchDeletion(indexName,dataJson);
return R.ok(null, "批量删除成功");
}
}

View File

@ -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<String,Object> docMsg){
return R.ok(esDocService.queryList(indexName,docMsg),"数据查询成功");
}
@PutMapping("/batchAddDoc/{indexName}")
public R batchAddDoc(@PathVariable String indexName, @RequestBody Map<String,Object> docMsg){
esDocService.batchAddDoc(indexName,docMsg);
return R.ok(null,"批量操作文档数据成功");
}
@DeleteMapping("/bathDeleteDoc/{indexName}")
public R bathDeleteDoc(@PathVariable String indexName, @RequestBody List<String> ids){
esDocService.bathDeleteDoc(indexName,ids);
return R.ok(null,"批量删除文档数据成功");
}
}

View File

@ -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<String,Object> 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<String,Object> 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),"索引映射存在");
}
}

View File

@ -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<String,Object> mappings){
return R.ok(indexService.index(indexName,mappings),"es索引添加成功");
}
@PutMapping("/{indexName}")
@ApiOperation(value = "修改索引")
public R updateIndex(@PathVariable String indexName,@RequestBody Map<String,Object> 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索引删除成功");
}
}

View File

@ -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("演示模式,不允许操作");
}
}

View File

@ -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<String, Object> conditions);
void batchOperation(String indexName, Map<String,Object> dataJson);
void batchDeletion(String indexName, List<String> dataJson);
}

View File

@ -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<String, Object> docMsg);
void bathDeleteDoc(String indexName, List<String> ids);
R queryList(String indexName, Map<String, Object> docMsg);
}

View File

@ -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<String,Object> docMsg);
boolean deleteIndex(String indexName);
Map<String, Object> getMapping(String indexName);
boolean updateIndex(String indexName, Map<String, Object> docMsg);
}

View File

@ -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<String, Object> mappings);
boolean updataIndex(String indexName, Map<String, Object> mappings);
boolean deleteIndex(String indexName);
Map<String, Object> getMapping(String indexName);
}

View File

@ -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<String, Object> 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<String, Object> 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<String, Object> dataJson) {
BulkRequest bulkRequest = new BulkRequest();
// 根据dataJson中的key进行批量操作
for (Map.Entry<String, Object> entry : dataJson.entrySet()) {
String id = entry.getKey();
Map<String, Object> document = (Map<String, Object>) 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<String> 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<String, Object> conditions, SearchSourceBuilder sourceBuilder) {
// 从条件中获取分页信息
Map<String, Object> pagination = (Map<String, Object>) 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<String, Object> 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<String, Object> conditions, SearchSourceBuilder sourceBuilder) {
Map<String, Object> highlightParams = (Map<String, Object>) conditions.get("highlight");
if (highlightParams != null) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
List<String> fieldNames = (List<String>) highlightParams.getOrDefault("fields", Collections.emptyList());
String preTag = (String) highlightParams.getOrDefault("preTag", "<em>");
String postTag = (String) highlightParams.getOrDefault("postTag", "</em>");
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<String, Object> objectMap = new LinkedHashMap<>();
for (SearchHit hit : searchResponse.getHits().getHits()) {
String sourceAsString = hit.getSourceAsString();
HashMap<String, Object> 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<String, HighlightField> highlightFields, Map<String, Object> parsedObject) {
if (!highlightFields.isEmpty()) {
for (Map.Entry<String, HighlightField> 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<String, Object> conditions) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if (conditions != null && !conditions.isEmpty()) {
for (Map.Entry<String, Object> entry : conditions.entrySet()) {
String field = entry.getKey();
Object value = entry.getValue();
// 处理范围查询条件
if (value instanceof Map && ((Map<?, ?>) value).containsKey("range")) {
Map<String, Object> rangeParams = (Map<String, Object>) 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;
}
}

View File

@ -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<String, Object> docMsg) {
BulkRequest bulkRequest = new BulkRequest();
for (Map.Entry<String, Object> entry : docMsg.entrySet()){
String id = entry.getKey();
Map<String, Object> value = (Map<String, Object>) 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<String> 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<String, Object> 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<String, Object> stringObjectLinkedHashMap = new LinkedHashMap<>();
for (SearchHit hit : searchResponse.getHits().getHits()) {
String sourceAsString = hit.getSourceAsString();
HashMap<String,Object> 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<String, HighlightField> highlightFields, Map<String, Object> parsedObject) {
if (!highlightFields.isEmpty()) {
for (Map.Entry<String, HighlightField> 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<String, Object> 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<String, Object> docMsg, SearchSourceBuilder sourceBuilder) {
// 获取高亮参数
Map<String,Object> highlight = (Map<String, Object>) docMsg.get("highlight");
// 判断是否需要高亮
if(highlight != null){
// 创建高亮构建器
HighlightBuilder highlightBuilder = new HighlightBuilder();
// 获取高亮字段
List<String> fields = (List<String>) highlight.getOrDefault("fields", Collections.emptyList());
// 获取高亮前缀
String preTag = (String) highlight.getOrDefault("preTag", "<em>");
// 获取高亮后缀
String postTag = (String) highlight.getOrDefault("postTag", "</em>");
// 循环设置高亮字段
for (String field : fields) {
highlightBuilder.field(field);
}
// 设置高亮包裹
highlightBuilder.preTags(preTag).postTags(postTag);
// 设置高亮
sourceBuilder.highlighter(highlightBuilder);
}
}
private void setSortParameters(Map<String, Object> 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<String, Object> docMsg, SearchSourceBuilder sourceBuilder) {
// 从条件中获取分页信息
Map<String,Object> pagination = (Map<String, Object>) 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<String, Object> docMsg) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if(docMsg != null && !docMsg.isEmpty()){
for (Map.Entry<String, Object> entry : docMsg.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if(value instanceof Map && ((Map<?, ?>) value).containsKey("range")){
Map<String, Object> rangeParms = (Map<String, Object>) 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("索引名称为空,请重试");
}
}
}

View File

@ -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<String,Object> 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<String,Object> docMsg) throws IOException {
// 初始化XContentBuilder对象开始构建JSON对象
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.startObject("properties");
// 遍历docMsg为每个字段构建映射
for (Map.Entry<String, Object> entry : docMsg.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
xContentBuilder.startObject(key);
if(value instanceof Map){
// 如果字段值是Map类型则递归处理
Map<String,Object> stringObjectMap = (Map<String, Object>) value;
// 遍历内部映射,添加到当前字段
for (Map.Entry<String, Object> 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<String, Object> 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<String, MappingMetadata> mappings = getIndexResponse.getMappings();
MappingMetadata mappingMetadata = mappings.get(indexName);
// 判断映射是否为空
if(mappingMetadata != null){
// 获取映射
Map<String,Object> properties = (Map<String, Object>) 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<String, Object> 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);
}
}
}

View File

@ -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<String, Object> 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<String, Object> 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<String, Object> 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<String, MappingMetadata> mappings = response.getMappings();
// 提取并返回指定索引的映射结构
MappingMetadata mappingMetadata = mappings.get(indexName);
if (mappingMetadata != null) {
Map<String,Object> map = (Map<String, Object>) 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<String, Object> mappings) throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("properties");
for (Map.Entry<String, Object> entry : mappings.entrySet()) {
String fieldName = entry.getKey();
Object fieldConfig = entry.getValue();
builder.startObject(fieldName); // Start field mapping
if (fieldConfig instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> nestedMapping = (Map<String, Object>) fieldConfig;
for (Map.Entry<String, Object> 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;
}
}

View File

@ -1,10 +0,0 @@
Spring Boot Version: ${spring-boot.version}
Spring Application Name: ${spring.application.name}
_ __ _ _
(_) / _|(_)| |
_ __ _ _ ___ _ _ _ ______ | |_ _ | | ___
| '__|| | | | / _ \ | | | || ||______|| _|| || | / _ \
| | | |_| || (_) || |_| || | | | | || || __/
|_| \__,_| \___/ \__, ||_| |_| |_||_| \___|
__/ |
|___/

View File

@ -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

View File

@ -1,74 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 日志存放路径 -->
<property name="log.path" value="logs/bawei-file" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.bawei" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
</root>
</configuration>

View File

@ -8,14 +8,8 @@
<artifactId>bawei-base</artifactId>
<version>3.6.0</version>
</parent>
<artifactId>base-es</artifactId>
<packaging>pom</packaging>
<description>
base-es es服务
</description>
<modules>
<module>base-es-server</module>
<module>base-es-remote</module>
<module>base-es-common</module>
</modules>
</project>

View File

@ -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<MallProductInfo> 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();
}
/**
*
*/

View File

@ -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();
}

View File

@ -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,8 +217,33 @@ public class MallProductInfoServiceImpl implements IMallProductInfoService
return mallProductInfoMapper.selectMallProductInfoCount(mallProductInfo);
}
@Override
public void unmout(Long id, String status) {
public void queryJson() {
Path pathJson = Paths.get(".");
try {
List<Path> 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不能为空");
}
@ -209,29 +251,39 @@ public class MallProductInfoServiceImpl implements IMallProductInfoService
throw new RuntimeException("商品状态不能为空");
}
MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
if (mallProductInfo.getStatus().equals("0")){
if (status.equals("1")){
mallProductInfo.setStatus(status);
mallProductInfoMapper.updateMallProductInfo(mallProductInfo);
}else {
if (mallProductInfo==null){
throw new RuntimeException("商品不存在");
}
//判断修改的状态和数据库里的状态是否冲突
if (mallProductInfo.getStatus().equals("0") && status.equals("0")){
throw new RuntimeException("商品已上架");
}
}else {
if (status.equals("1")){
}else if (mallProductInfo.getStatus().equals("1") && status.equals("1")){
throw new RuntimeException("商品已下架");
}else {
}
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("删除索引失败");
}
}
}
@Override
public R esList() {
//添加es列表查询
if (remoteIndexService.exist("shop").isSuccess()){
//查询es列表
R shop = remoteDocumentService.queryList("shop", null);
return R.ok(shop.getData());
}
return null;
}
}

View File

@ -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"
}
}
}
}

47
indexNameJson.json 100644
View File

@ -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"
}
}
}
}

View File

@ -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"
}
}
}
}