Commit 3ab6e756 authored by shengnan hu's avatar shengnan hu
Browse files

init

parents
Pipeline #294 passed with stage
in 2 minutes and 13 seconds
<?xml version="1.0" encoding="UTF-8"?>
<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>mall4cloud-common</artifactId>
<groupId>com.mall4j.cloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mall4cloud-common-core</artifactId>
<description>mall4cloud 公共模块核心(公共中的公共代码)</description>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<!--接口文档-->
<dependency>
<groupId>cn.throwx</groupId>
<artifactId>canal-glue-core</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${pom.basedir}/lib/canal-glue-core.jar</systemPath>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson2.version}</version>
</dependency>
</dependencies>
</project>
package com.mall4j.cloud.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author FrozenWatermelon
* @date 2020/9/21
*/
@EnableAspectJAutoProxy(exposeProxy = true)
@Configuration
public class AopConfig {
}
package com.mall4j.cloud.common.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author FrozenWatermelon
* @date 2020/7/11
*/
@Configuration
public class RestTemplateConfig {
@Bean
@ConditionalOnMissingBean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.mall4j.cloud.common.constant;
import com.mall4j.cloud.common.feign.FeignInsideAuthConfig;
/**
* @author FrozenWatermelon
* @date 2020/12/8
*/
public interface Auth {
String CHECK_TOKEN_URI = FeignInsideAuthConfig.FEIGN_INSIDE_URL_PREFIX + "/token/checkToken";
String CHECK_RBAC_URI = FeignInsideAuthConfig.FEIGN_INSIDE_URL_PREFIX + "/insider/permission/checkPermission";
}
package com.mall4j.cloud.common.constant;
/**
* 常量
* @author FrozenWatermelon
*/
public class Constant {
/** 超级管理员ID */
public static final int SUPER_ADMIN_ID = 1;
/**
* 自营店id
*/
public static final long MAIN_SHOP = 1L;
/**
* 如果把平台的数据也保存在店铺里面,如分类,热搜之类的,保存的店铺id
*/
public static final long PLATFORM_SHOP_ID = 0L;
/**
* 商城缺失sku属性时的字符描述
*/
public static final String SKU_PREFIX = "规格:";
public static final String DEFAULT_SKU = "规格";
/** 系统菜单最大id */
public static final int SYS_MENU_MAX_ID = 30;
/**
* 查询订单成功状态
*/
public static final String SUCCESS = "SUCCESS";
/**
* 一级分类id
*/
public static final Long CATEGORY_ID = 0L;
/**
* 分类间隔
*/
public static final String CATEGORY_INTERVAL = "-";
/**
* 店铺收藏返回的商品数量
*/
public static final Integer SPU_SIZE_FIVE = 5;
/**
* 订单如果未支付,30分钟后取消
*/
public static final int ORDER_CANCEL_TIME = 30;
/**
* 如果因为网络原因,导致无法清楚订单是否已经下单成功,那么处理的时间应该要比订单取消时间晚一点
*/
public static final int ORDER_CANCEL_WAIT_TIME = 10 + ORDER_CANCEL_TIME;
/**
* 默认金额
*/
public static final Long DEFAULT_AMOUNT = 0L;
/**
* 字符串最大长度限制
*/
public static final Integer MAX_FIELD_LIMIT = 500;
/**
* 句号(英文符号)
*/
public static final String PERIOD = ".";
/**
* 下划线
*/
public static final String UNDERLINE = "_";
/**
* 逗号
*/
public static final String COMMA = ",";
}
package com.mall4j.cloud.common.constant;
/**
* 等级
* @author yxf
* @date 2020/11/20
*/
public enum StatusEnum {
/**
* 删除 (逻辑删除)
*/
DELETE(-1),
/**
* 禁用/过期/下架
*/
DISABLE(0),
/**
* 启用/未过期/上架
*/
ENABLE(1),
/**
* 违规下架
*/
OFFLINE(2),
/**
* 等待审核
*/
WAIT_AUDIT(3)
;
private final Integer value;
public Integer value() {
return value;
}
StatusEnum(Integer value) {
this.value = value;
}
public static Boolean offlineStatus (Integer value) {
StatusEnum[] enums = values();
for (StatusEnum statusEnum : enums) {
if (statusEnum.value().equals(value)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
}
package com.mall4j.cloud.common.constant;
/**
* @author lhd
* @date 2020/12/30
*/
public enum UserAdminType {
/**
* 管理员
*/
ADMIN(1),
/**
* 用户
*/
USER(0),
;
private Integer value;
public Integer value() {
return value;
}
public Integer getValue() {
return value;
}
UserAdminType(Integer value) {
this.value = value;
}
public static UserAdminType instance(Integer value) {
UserAdminType[] enums = values();
for (UserAdminType statusEnum : enums) {
if (statusEnum.getValue().equals(value)) {
return statusEnum;
}
}
return null;
}
}
package com.mall4j.cloud.common.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Date;
/**
* 阿里java开发手册: 【强制】表必备三字段:id, create_time, update_time。 说明:其中 id 必为主键,类型为 bigint
* unsigned、单表时自增、步长为 1。create_time, update_time 的类型均为 datetime
* 类型,前者现在时表示主动式创建,后者过去分词表示被动式更新。
*
* @author FrozenWatermelon
*/
public class BaseDTO {
/**
* 创建时间
*/
@Schema(description = "创建时间" )
protected Date createTime;
/**
* 更新时间
*/
@Schema(description = "更新时间" )
protected Date updateTime;
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "BaseDTO{" + "createTime=" + createTime + ", updateTime=" + updateTime + '}';
}
}
package com.mall4j.cloud.common.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* @author FrozenWatermelon
*/
public class OrderSearchDTO {
/**
* 用户id
*/
private Long userId;
/**
* 店铺id
*/
private Long shopId;
@Schema(description = "订单状态" )
private Integer status;
@Schema(description = "是否已经支付,1:已经支付过,0:没有支付过" )
private Integer isPayed;
/**
* 订购流水号
*/
@Schema(description = "订单号" )
private Long orderId;
@Schema(description = "下单的时间范围:开始时间" )
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime;
@Schema(description = "下单的时间范围:结束时间" )
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
@Schema(description = "店铺名称" )
private String shopName;
@Schema(description = "商品名称" )
private String spuName;
@Schema(description = "收货人姓名" )
private String consignee;
@Schema(description = "收货人手机号" )
private String mobile;
@Schema(description = "物流类型 3:无需快递" )
private Integer deliveryType;
@Schema(description = "开始页" )
private Integer pageNum;
@Schema(description = "每页大小" )
private Integer pageSize;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getIsPayed() {
return isPayed;
}
public void setIsPayed(Integer isPayed) {
this.isPayed = isPayed;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String getSpuName() {
return spuName;
}
public void setSpuName(String spuName) {
this.spuName = spuName;
}
public String getConsignee() {
return consignee;
}
public void setConsignee(String consignee) {
this.consignee = consignee;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Integer getDeliveryType() {
return deliveryType;
}
public void setDeliveryType(Integer deliveryType) {
this.deliveryType = deliveryType;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
@Override
public String toString() {
return "OrderSearchDTO{" +
"userId=" + userId +
", shopId=" + shopId +
", status=" + status +
", isPayed=" + isPayed +
", orderId=" + orderId +
", startTime=" + startTime +
", endTime=" + endTime +
", shopName='" + shopName + '\'' +
", spuName='" + spuName + '\'' +
", consignee='" + consignee + '\'' +
", mobile='" + mobile + '\'' +
", deliveryType=" + deliveryType +
", pageNum=" + pageNum +
", pageSize=" + pageSize +
'}';
}
}
package com.mall4j.cloud.common.exception;
import com.mall4j.cloud.common.response.ResponseEnum;
/**
* @author FrozenWatermelon
* @date 2020/7/11
*/
public class Mall4cloudException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Object object;
private ResponseEnum responseEnum;
public Mall4cloudException(String msg) {
super(msg);
}
public Mall4cloudException(String msg, Object object) {
super(msg);
this.object = object;
}
public Mall4cloudException(String msg, Throwable cause) {
super(msg, cause);
}
public Mall4cloudException(ResponseEnum responseEnum) {
super(responseEnum.getMsg());
this.responseEnum = responseEnum;
}
public Mall4cloudException(ResponseEnum responseEnum, Object object) {
super(responseEnum.getMsg());
this.responseEnum = responseEnum;
this.object = object;
}
public Object getObject() {
return object;
}
public ResponseEnum getResponseEnum() {
return responseEnum;
}
}
package com.mall4j.cloud.common.feign;
import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;
/**
* @author FrozenWatermelon
* @date 2020/11/27
*/
@Component
@ConditionalOnClass({RequestInterceptor.class})
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
private static final Logger logger = LoggerFactory.getLogger(FeignBasicAuthRequestInterceptor.class);
@Autowired
private FeignInsideAuthConfig feignInsideAuthConfig;
@Override
public void apply(RequestTemplate template) {
// feign的内部请求,往请求头放入key 和 secret进行校验
template.header(feignInsideAuthConfig.getKey(), feignInsideAuthConfig.getSecret());
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
if (attributes == null) {
return;
}
HttpServletRequest request = attributes.getRequest();
String authorization = request.getHeader("Authorization");
if (StrUtil.isNotBlank(authorization)) {
template.header("Authorization", authorization);
}
}
}
package com.mall4j.cloud.common.feign;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author FrozenWatermelon
* @date 2020/12/11
*/
@Configuration
public class FeignHttpClientConfig {
@Bean(destroyMethod = "close")
public CloseableHttpClient httpClient() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(400);
connectionManager.setDefaultMaxPerRoute(100);
RequestConfig requestConfig = RequestConfig.custom()
//从连接池获取连接等待超时时间
.setConnectionRequestTimeout(2000)
//请求超时时间
.setConnectTimeout(2000)
//等待服务响应超时时间
.setSocketTimeout(15000)
.build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.evictExpiredConnections();
return httpClientBuilder.build();
}
}
package com.mall4j.cloud.common.feign;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @author FrozenWatermelon
* @date 2020/9/10
*/
@RefreshScope
@Configuration
@ConfigurationProperties("feign.inside")
public class FeignInsideAuthConfig {
/**
* feign请求前缀
*/
public static final String FEIGN_INSIDE_URL_PREFIX = "/feign";
@Value("${feign.inside.key}")
private String key;
@Value("${feign.inside.secret}")
private String secret;
@Value("#{'${feign.inside.ips:}'.split(',')}")
private List<String> ips;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public List<String> getIps() {
return ips;
}
public void setIps(List<String> ips) {
this.ips = ips;
}
@Override
public String toString() {
return "FeignInsideAuthConfig{" +
"key='" + key + '\'' +
", secret='" + secret + '\'' +
", ips=" + ips +
'}';
}
}
package com.mall4j.cloud.common.handler;
import cn.hutool.core.util.StrUtil;
import com.mall4j.cloud.common.exception.Mall4cloudException;
import com.mall4j.cloud.common.response.ResponseEnum;
import com.mall4j.cloud.common.response.ServerResponseEntity;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义错误处理器,除了授权只要请求服务器成功,就返回200,错误根据错误码前端进行处理
*
* @author FrozenWatermelon
* @date 2020/7/11
*/
@RestController
@RestControllerAdvice
public class DefaultExceptionHandlerConfig {
private static final Logger logger = LoggerFactory.getLogger(DefaultExceptionHandlerConfig.class);
@ExceptionHandler({ MethodArgumentNotValidException.class, BindException.class })
public ResponseEntity<ServerResponseEntity<List<String>>> methodArgumentNotValidExceptionHandler(Exception e) {
logger.error("methodArgumentNotValidExceptionHandler", e);
List<FieldError> fieldErrors = null;
if (e instanceof MethodArgumentNotValidException) {
fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
}
if (e instanceof BindException) {
fieldErrors = ((BindException) e).getBindingResult().getFieldErrors();
}
if (fieldErrors == null) {
return ResponseEntity.status(HttpStatus.OK)
.body(ServerResponseEntity.fail(ResponseEnum.METHOD_ARGUMENT_NOT_VALID));
}
List<String> defaultMessages = new ArrayList<>(fieldErrors.size());
for (FieldError fieldError : fieldErrors) {
defaultMessages.add(fieldError.getField() + ":" + fieldError.getDefaultMessage());
}
return ResponseEntity.status(HttpStatus.OK)
.body(ServerResponseEntity.fail(ResponseEnum.METHOD_ARGUMENT_NOT_VALID, defaultMessages));
}
@ExceptionHandler({ HttpMessageNotReadableException.class })
public ResponseEntity<ServerResponseEntity<List<FieldError>>> methodArgumentNotValidExceptionHandler(
HttpMessageNotReadableException e) {
logger.error("methodArgumentNotValidExceptionHandler", e);
return ResponseEntity.status(HttpStatus.OK)
.body(ServerResponseEntity.fail(ResponseEnum.HTTP_MESSAGE_NOT_READABLE));
}
@ExceptionHandler(Mall4cloudException.class)
public ResponseEntity<ServerResponseEntity<Object>> mall4cloudExceptionHandler(Mall4cloudException e) {
logger.error("mall4cloudExceptionHandler", e);
ResponseEnum responseEnum = e.getResponseEnum();
// 失败返回失败消息 + 状态码
if (responseEnum != null) {
return ResponseEntity.status(HttpStatus.OK).body(ServerResponseEntity.fail(responseEnum, e.getObject()));
}
// 失败返回消息 状态码固定为直接显示消息的状态码
return ResponseEntity.status(HttpStatus.OK).body(ServerResponseEntity.showFailMsg(e.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ServerResponseEntity<Object>> exceptionHandler(Exception e) throws TransactionException {
logger.error("exceptionHandler", e);
logger.info("RootContext.getXID(): " + RootContext.getXID());
if (StrUtil.isNotBlank(RootContext.getXID())) {
GlobalTransactionContext.reload(RootContext.getXID()).rollback();
}
return ResponseEntity.status(HttpStatus.OK).body(ServerResponseEntity.fail(ResponseEnum.EXCEPTION));
}
}
package com.mall4j.cloud.common.handler;
import cn.hutool.core.util.CharsetUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall4j.cloud.common.exception.Mall4cloudException;
import com.mall4j.cloud.common.response.ServerResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author FrozenWatermelon
* @date 2020/7/16
*/
@Component
public class HttpHandler {
private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);
@Autowired
private ObjectMapper objectMapper;
public <T> void printServerResponseToWeb(ServerResponseEntity<T> serverResponseEntity) {
if (serverResponseEntity == null) {
logger.info("print obj is null");
return;
}
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
if (requestAttributes == null) {
logger.error("requestAttributes is null, can not print to web");
return;
}
HttpServletResponse response = requestAttributes.getResponse();
if (response == null) {
logger.error("httpServletResponse is null, can not print to web");
return;
}
logger.error("response error: " + serverResponseEntity.getMsg());
response.setCharacterEncoding(CharsetUtil.UTF_8);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
PrintWriter printWriter = null;
try {
printWriter = response.getWriter();
printWriter.write(objectMapper.writeValueAsString(serverResponseEntity));
}
catch (IOException e) {
throw new Mall4cloudException("io 异常", e);
}
}
}
package com.mall4j.cloud.common.model;
import java.io.Serializable;
import java.util.Date;
/**
* 阿里java开发手册: 【强制】表必备三字段:id, create_time, update_time。 说明:其中 id 必为主键,类型为 bigint
* unsigned、单表时自增、步长为 1。create_time, update_time 的类型均为 datetime
* 类型,前者现在时表示主动式创建,后者过去分词表示被动式更新。
*
* @author FrozenWatermelon
*/
public class BaseModel implements Serializable {
/**
* 创建时间
*/
protected Date createTime;
/**
* 更新时间
*/
protected Date updateTime;
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "BaseModel{" + "createTime=" + createTime + ", updateTime=" + updateTime + '}';
}
}
package com.mall4j.cloud.common.response;
/**
* @author FrozenWatermelon
* @date 2020/7/9
*/
public enum ResponseEnum {
/**
* ok
*/
OK("00000", "ok"),
/**
* 用于直接显示提示用户的错误,内容由输入内容决定
*/
SHOW_FAIL("A00001", ""),
/**
* 方法参数没有校验,内容由输入内容决定
*/
METHOD_ARGUMENT_NOT_VALID("A00002", ""),
/**
* 无法读取获取请求参数
*/
HTTP_MESSAGE_NOT_READABLE("A00003", "请求参数格式有误"),
/**
* 未授权
*/
UNAUTHORIZED("A00004", "Unauthorized"),
/**
* 服务器出了点小差
*/
EXCEPTION("A00005", "服务器出了点小差"),
/**
* 数据异常
*/
DATA_ERROR("A00007", "数据异常,请刷新后重新操作"),
/**
* 一些需要登录的接口,而实际上因为前端无法知道token是否已过期,导致token已失效时,
* 应该返回一个状态码,告诉前端token已经失效了,及时清理
*/
CLEAN_TOKEN("A00008", "clean token"),
/**
* 刷新token已过期
*/
REFRESH_TOKEN_EXIST("A00009", "refresh token exist"),
/**
* 数据不完整
*/
DATA_INCOMPLETE("A00010", "数据不完整"),
/**
* 01开头代表商品
*/
SPU_NOT_EXIST("A01000", "spu not exist"),
/**
* 02开头代表购物车
*/
SHOP_CART_NOT_EXIST("A02000", "shop cart not exist"),
/**
* 03开头代表订单
*/
ORDER_NOT_EXIST("A03000", "order not exist"),
/**
* 请勿重复提交订单,
* 1.当前端遇到该异常时,说明前端防多次点击没做好
* 2.提示用户 订单已发生改变,请勿重复下单
*/
REPEAT_ORDER("A03002", "please don't repeat order"),
/**
* 订单已过期,当前端看到该状态码的时候,提示订单信息已过期,请重新确认后提交,此时用户点击确定,前端刷新页面。
*/
ORDER_EXPIRED("A03003", "order expired"),
/**
* 订单已支付,无法取消订单
*/
ORDER_PAYED("A03007", "order payed"),
/**
* 订单未发货,无法确认收货
*/
ORDER_NO_DELIVERY("A03008", "order no delivery"),
/**
* 库存不足,body会具体返回那个skuid的库存不足
*/
NOT_STOCK("A03010", "not stock"),
/**
* 订单未完成或未关闭,无法删除订单
*/
ORDER_NOT_FINISH_OR_CLOSE("A03011", "order not finish or close"),
/**
* 订单未支付
*/
ORDER_NOT_PAYED("A03012", "order not payed"),
/**
* 订单已失败
*/
ORDER_HAS_FAILED("A03013", "order has failed"),
/**
* 没有查询权限
*/
REFUND_NOT_PERMISSION("A03024", "refund not permission"),
/**
* 撤销失败 当前状态不允许此操作
*/
REFUND_STATUS_CHECK("A03034", "refund status check"),
/**
* 04 开头代表注册登录之类的异常状态
* 社交账号未绑定,当前端看到该异常时,应该在合适的时间(比如在购买的时候跳)根据社交账号的类型,跳转到绑定系统账号的页面
*/
SOCIAL_ACCOUNT_NOT_BIND("A04001", "social account not bind"),
/**
* 有些时候第三方系统授权之后,会有个临时的key,比如小程序的session_key
* 这个异常代表session_key过期,前端遇到这个问题的时候,应该再次调用社交登录的接口,刷新session_key
*/
BIZ_TEMP_SESSION_KEY_EXPIRE("A04002", "biz temp session key expire"),
/**
* 账号未注册,前端看到这个状态码,弹出选择框,提示用户账号未注册,是否进入注册页面,用户选择是,进入注册页面
*/
ACCOUNT_NOT_REGISTER("A04003", "account not register");
private final String code;
private final String msg;
public String value() {
return code;
}
public String getMsg() {
return msg;
}
ResponseEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public String toString() {
return "ResponseEnum{" + "code='" + code + '\'' + ", msg='" + msg + '\'' + "} " + super.toString();
}
}
package com.mall4j.cloud.common.response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.Objects;
/**
* 统一的返回数据
*
* @author FrozenWatermelon
* @date 2020/7/3
*/
public class ServerResponseEntity<T> implements Serializable {
private static final Logger log = LoggerFactory.getLogger(ServerResponseEntity.class);
/**
* 状态码
*/
private String code;
/**
* 信息
*/
private String msg;
/**
* 数据
*/
private T data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean isSuccess() {
return Objects.equals(ResponseEnum.OK.value(), this.code);
}
@Override
public String toString() {
return "ServerResponseEntity{" + "code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}';
}
public static <T> ServerResponseEntity<T> success(T data) {
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setData(data);
serverResponseEntity.setCode(ResponseEnum.OK.value());
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> success() {
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setCode(ResponseEnum.OK.value());
serverResponseEntity.setMsg(ResponseEnum.OK.getMsg());
return serverResponseEntity;
}
/**
* 前端显示失败消息
* @param msg 失败消息
* @return
*/
public static <T> ServerResponseEntity<T> showFailMsg(String msg) {
log.error(msg);
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(msg);
serverResponseEntity.setCode(ResponseEnum.SHOW_FAIL.value());
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> fail(ResponseEnum responseEnum) {
log.error(responseEnum.toString());
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(responseEnum.getMsg());
serverResponseEntity.setCode(responseEnum.value());
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> fail(ResponseEnum responseEnum, T data) {
log.error(responseEnum.toString());
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(responseEnum.getMsg());
serverResponseEntity.setCode(responseEnum.value());
serverResponseEntity.setData(data);
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> transform(ServerResponseEntity<?> oldServerResponseEntity) {
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(oldServerResponseEntity.getMsg());
serverResponseEntity.setCode(oldServerResponseEntity.getCode());
log.error(serverResponseEntity.toString());
return serverResponseEntity;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment