苍穹外卖中的模块总结

news/2025/2/24 20:28:48

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

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.niftyadmin.cn/n/5864793.html

相关文章

毕业项目推荐:基于yolov8/yolov5/yolo11的番茄成熟度检测识别系统(python+卷积神经网络)

文章目录 概要一、整体资源介绍技术要点功能展示&#xff1a;功能1 支持单张图片识别功能2 支持遍历文件夹识别功能3 支持识别视频文件功能4 支持摄像头识别功能5 支持结果文件导出&#xff08;xls格式&#xff09;功能6 支持切换检测到的目标查看 二、数据集三、算法介绍1. YO…

k8s部署针对外部服务器的prometheus服务

在Kubernetes(K8s)集群中部署Prometheus以监控外部服务器&#xff0c;涉及到几个关键步骤&#xff1a;配置Prometheus以抓取远程目标、设置服务发现机制、以及确保网络可达性。下面是一个详细指南&#xff0c;指导您如何在Kubernetes中部署并配置Prometheus&#xff0c;以便有效…

Python的子线程与主线程之间的通信并通知主线程更新UI

新建PLC类 PLC.py import json import time from threading import Threadfrom HslCommunication import SiemensS7Net, SiemensPLCS from PySide6.QtCore import QThread, Signal, QObjectfrom tdm.MsgType import MSG_TYPE_LOG, MSG_TYPE_MSGBOX# 自定义信号类&#xff0c;用…

ElasticSearch查询指南:从青铜到王者的骚操作

ElasticSearch查询指南&#xff1a;从青铜到王者的骚操作 本文来源于笔者的CSDN原创&#xff0c;由于掘金>已经去掉了转载功能&#xff0c;所以只好重新上传&#xff0c;以下图片依然保持最初发布的水印&#xff08;如CSDN水印&#xff09;。&#xff08;以后属于本人原创均…

vue-fastapi-admin 部署心得

vue-fastapi-admin 部署心得 这两天需要搭建一个后台管理系统&#xff0c;找来找去 vue-fastapi-admin 这个开源后台管理框架刚好和我的技术栈所契合。于是就浅浅的研究了一下。 主要是记录如何基于原项目提供的Dockerfile进行调整&#xff0c;那项目文件放在容器外部&#xf…

基于Spring Boot的公司资产网站设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

从零实现机器人自主避障

1. 编译工具安装 sudo apt update sudo apt install python3-catkin-pkg python3-rosdep python3-rosinstall-generator python3-wstool python3-rosinstall build-essential sudo rosdep init rosdep update2. 构建节点 mkdir -p ~/ros2_ws/src cd ~/ros2_ws ros2 pkg creat…

mysql之B+ 树索引 (InnoDB 存储引擎)机制

b树索引机制 B 树索引 (InnoDB 存储引擎)机制**引言&#xff1a;****1. 数据页结构与查找**2. 索引的引入**3. InnoDB 的 B 树索引****4. InnoDB B 树索引的注意事项****5. MyISAM 的索引方案 (选读&#xff0c;与 InnoDB 做对比)****6. MySQL 中创建和删除索引的语句** **B 树…