项目初始化
版本管理
https://spring.io/projects/spring-cloud
。https://spring.io/projects/spring-kafka
。?,?:Exception thrown when sending a message with key='null' and payload='byte[205]' to topic notify org.apache.kafka.common.errors.UnsupportedVersionException: Attempting to use idempotence with a broker which does not support the required message format (v2). The broker must be version *0.11* or later.
https://maven.apache.org/index.html
。Apache Maven is a software project management and comprehension tool
废话不多说,直接看脚手架
@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
public ResponseResult<String> handleValidException(MethodArgumentNotValidException ex, HttpServletResponse httpServletResponse) {
log.error("[GlobalExceptionHandler][handleValidException] 参数校验exception", ex);
return wrapperBindingResult(ex.getBindingResult(), httpServletResponse);
}
private ResponseResult<String> wrapperBindingResult(BindingResult bindingResult, HttpServletResponse httpServletResponse) {
StringBuilder errorMsg = new StringBuilder();
for (ObjectError error : bindingResult.getAllErrors()) {
if (error instanceof FieldError) {
errorMsg.append(((FieldError) error).getField()).append(": ");
}
errorMsg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
}
httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());
return ResponseResult.failed(ResultCode.FAILED.getCode(),null);
}
@Aspect
@Slf4j
@Component
public class WebLogAspect {
@Pointcut("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
public void cutController() {
}
@Before("cutController()")
public void doBefore(JoinPoint point) {
//获取拦截方法的参数
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String url = request.getRequestURL().toString();
List<Object> list = Lists.newArrayList();
for (Object object : point.getArgs()) {
if (object instanceof MultipartFile || object instanceof HttpServletRequest || object instanceof HttpServletResponse || object instanceof BindingResult) {
continue;
}
list.add(object);
}
log.info("请求 uri:[{}],params:[{}]", url, StringUtils.join(list, ","));
}
/**
* 返回通知:
* 1. 在目标方法正常结束之后执行
* 1. 在返回通知中补充请求日志信息,如返回时间,方法耗时,返回值,并且保存日志信息
*
* @param response
* @throws Throwable
*/
@AfterReturning(returning = "response", pointcut = "cutController()")
public void doAfterReturning(Object response) {
if (response != null) {
log.info("请求返回result:[{}]", JSONUtil.toJsonStr(response));
}
}
}
@Configuration
public class GlobalCorsConfig {
/**
* 允许跨域调用的过滤器
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
//允许所有域名进行跨域调用
config.setAllowedOrigins(Lists.newArrayList("*"));
//允许跨越发送cookie
config.setAllowCredentials(true);
//放行全部原始头信息
config.addAllowedHeader("*");
//允许所有请求方法跨域调用
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo()).enable(true)
.select()
//apis: 添加swagger接口提取范围
.apis(RequestHandlerSelectors.basePackage("com.vines.controller"))
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("项目描述")
.description("基础服务项目描述")
.contact(new Contact("作者", "作者URL", "作者Email"))
.version("1.0")
.build();
}
}
@Data
public class ResponseResult<T> {
private int code;
private String message;
private T data;
public static <T> ResponseResult<T> success(T data){
ResponseResult<T> responseResult=new ResponseResult<>();
responseResult.setCode(ResultCode.SUCCESS.getCode());
responseResult.setMessage(ResultCode.SUCCESS.getMessage());
responseResult.setData(data);
return responseResult;
}
public static <T> ResponseResult<T> success(){
ResponseResult<T> responseResult=new ResponseResult<>();
responseResult.setCode(ResultCode.SUCCESS.getCode());
responseResult.setMessage(ResultCode.SUCCESS.getMessage());
return responseResult;
}
public static <T> ResponseResult failed(int code,String message){
ResponseResult<T> responseResult=new ResponseResult<>();
responseResult.setCode(code);
responseResult.setMessage(message);
return responseResult;
}
public static boolean isSucceed(ResponseResult responseResult){
return responseResult.getCode()==ResultCode.SUCCESS.getCode();
}
}
常用工具
https://github.com/kstyrc/embedded-redis
。https://github.com/mariadb
。<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
https://hutool.cn/
。https://baomidou.com/
。https://mapstruct.org/
。https://github.com/redisson/redisson
。总结
项目包含2个版本:
基于springboot的单体版本
基于spring cloud aliabab的微服务版本
从文档到视频、接口调试、学习看板等方面,让项目学习更加容易,内容更加沉淀。全套视频教程约44小时,共260期,讲解非常详细细腻。下面详细为大家介绍:
架构与业务
使用主流的技术架构,真正手把手教你从0到1如何搭建项目手脚架、项目架构分析、建表逻辑、业务分析、实现等。
单体版本:springboot 2.7、mybatis plus、rabbitmq、elasticsearch、redis
微服务版本:spring cloud alibaba 2021.0.5.0,nacos、seata、openFeign、sentinel
更多详情请查看: