当前位置: 首页 > article >正文

苍穹外卖中的模块总结

本文总结苍穹外卖项目中可复用的通用设计

sky-common

在这里插入图片描述
constant存放常量类,包括消息常量,状态常量
context是上下文对象,封装了threadlocal

package com.sky.context;

public class BaseContext {

    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    public static void setCurrentId(Long id) {
        threadLocal.set(id);
    }

    public static Long getCurrentId() {
        return threadLocal.get();
    }

    public static void removeCurrentId() {
        threadLocal.remove();
    }

}

enumeration存放枚举类
exception存放自定义异常类,用于抛出自定义异常

/**
 * 业务异常
 */
public class BaseException extends RuntimeException {

    public BaseException() {}
    public BaseException(String msg) {
        super(msg);
    }

}
/**
 * 账号被锁定异常
 */
public class AccountLockedException extends BaseException {

    public AccountLockedException() {
    }

    public AccountLockedException(String msg) {
        super(msg);
    }

}

properties用于配置工具类的属性,@ConfigurationProperties(prefix = “sky.alioss”)读取application.yml中以sky.alioss为前缀的具体值

@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}

utils封装具体的工具类
result封装返回给前端的响应类
json封装对象映射器(基于jackson将Java对象转为json,或者将json转为Java对象),定制 JSON 与 Java 对象之间的序列化(对象转JSON)和反序列化(JSON转对象)规则

sky-pojo

在这里插入图片描述

entity封装实体类,dto封装前端向后端传递数据的对象,通常是entity中某个类的部分数据,vo封装后端向前端返回数据的对象,按照前端需要的数据格式进行设计

sky-server

在这里插入图片描述
annotationaspect负责springboot的aop切面编程
config用于注册Bean

WebMvcConfiguration

/**
 * 配置类,注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
    @Autowired
    private JwtTokenUserInterceptor jwtTokenUserInterceptor;

    /**
     * 注册自定义拦截器
     *
     * @param registry
     */
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");
        registry.addInterceptor(jwtTokenAdminInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/employee/login");
        registry.addInterceptor(jwtTokenUserInterceptor)
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/user/login")
                .excludePathPatterns("/user/shop/status");
    }

    /**
     * 通过knife4j生成接口文档
     * @return
     */
    @Bean
    public Docket docket1() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .groupName("管理端接口")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller.admin"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    @Bean
    public Docket docket2() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .groupName("用户端接口")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller.user"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    /**
     * 设置静态资源映射
     * @param registry
     */
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 扩展spring mvc 的消息转换器
     * @param converters
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器");
        //创建一个消息转换器对象
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //为消息转换器设置一个对象转换器,对象转换器可将java对象序列化
        converter.setObjectMapper(new JacksonObjectMapper());
        //将消息转换器添加到converters
        converters.add(0,converter);


    }

}

z

public class OssConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties) {
        log.info("开始创建阿里云上传文件工具类对象",aliOssProperties);
        return new AliOssUtil(aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName()
        );
    }
}

这里用到前面common中提到的AliOssProperties来创建AliOssUtil类
handle用于定义全局异常处理器,处理各个地方抛出的异常

/**
 * 全局异常处理器,处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息:{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String msg=ex.getMessage();
        if(msg.contains("Duplicate entry")){
            String[] msgs=msg.split(" ");
            String username=msgs[2];
            return Result.error(username+MessageConstant.ALREADY_EXISTS);
        }else{
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

}

@RestControllerAdvice:表示这是一个全局异常处理类,会拦截所有 @RestController 或 @Controller 抛出的异常,并将处理结果以 JSON 格式返回给前端。
@ExceptionHandler :是 Spring 框架中用于集中处理异常的核心注解,它的核心作用是捕获并处理控制器(Controller)中抛出的特定异常,返回统一的错误响应。
interceptor用于定义拦截器
task定义定时任务类,与websocket配合使用


http://www.kler.cn/a/559834.html

相关文章:

  • 【前端】react大全一本通
  • 【JavaEE】-- 多线程(初阶)2
  • 侯捷 C++ 课程学习笔记:四个层面基本用法
  • PLC通讯
  • SPRING10_SPRING的生命周期流程图
  • Qt/C++项目积累:3.日志管理系统 - 3.1 项目介绍
  • 基于python的旅客游记和轨迹分析可视化系统设计(新)
  • 基于Python异常信息丰富度约束下CNN压缩系统设计与实现
  • 【个人开源】——从零开始在高通手机上部署sd(二)
  • 纷析云开源版- Vue2-增加字典存储到localStorage
  • 【Python爬虫(60)】解锁社交媒体数据宝藏:Python爬虫实战攻略
  • buuctf-[极客大挑战 2019]LoveSQL
  • 调试无痛入手
  • 蓝桥杯试题:小明的彩灯(差分 前缀和)
  • Linux系统移植之Uboot启动流程
  • “国补”带火手机换新,出售旧手机应如何保护个人信息安全
  • 鸿蒙学习-
  • Http升级为Https - 开发/测试服环境
  • 基于物联网的家庭版防疫面罩设计与实现(论文+源码)
  • μEMU部署测试(论文复现)