• 苍穹外卖学习


    并不包含全部视频内容,大部分都按照操作文档来手搓代码,资料,代码都上传git

    〇、实际代码

    0.1 Result封装

    1. package com.sky.result;
    2. import lombok.Data;
    3. import java.io.Serializable;
    4. /**
    5. * 后端统一返回结果
    6. * @param
    7. */
    8. @Data
    9. public class Result implements Serializable {
    10. private Integer code; //编码:1成功,0和其它数字为失败
    11. private String msg; //错误信息
    12. private T data; //数据
    13. public static Result success() {
    14. Result result = new Result();
    15. result.code = 1;
    16. return result;
    17. }
    18. public static Result success(T object) {
    19. Result result = new Result();
    20. result.data = object;
    21. result.code = 1;
    22. return result;
    23. }
    24. public static Result error(String msg) {
    25. Result result = new Result();
    26. result.msg = msg;
    27. result.code = 0;
    28. return result;
    29. }
    30. }

    0.2 全局异常处理

    1. package com.sky.handler;
    2. import com.sky.exception.BaseException;
    3. import com.sky.result.Result;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.springframework.web.bind.annotation.ExceptionHandler;
    6. import org.springframework.web.bind.annotation.RestControllerAdvice;
    7. /**
    8. * 全局异常处理器,处理项目中抛出的业务异常
    9. */
    10. @RestControllerAdvice
    11. @Slf4j
    12. public class GlobalExceptionHandler {
    13. /**
    14. * 捕获业务异常
    15. * @param ex
    16. * @return
    17. */
    18. @ExceptionHandler
    19. public Result exceptionHandler(BaseException ex){
    20. log.error("异常信息:{}", ex.getMessage());
    21. return Result.error(ex.getMessage());
    22. }
    23. }

    参数BaseException,我们自定义的异常都是BaseException的子类。BaseException继承RuntimeException运行时异常

    0.3 拦截器-令牌校验

    校验令牌,令牌校验失败,就会抛出异常,如果抛出异常,就会设置响应状态码为401

    1. package com.sky.interceptor;
    2. import com.sky.constant.JwtClaimsConstant;
    3. import com.sky.properties.JwtProperties;
    4. import com.sky.utils.JwtUtil;
    5. import io.jsonwebtoken.Claims;
    6. import lombok.extern.slf4j.Slf4j;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Component;
    9. import org.springframework.web.method.HandlerMethod;
    10. import org.springframework.web.servlet.HandlerInterceptor;
    11. import javax.servlet.http.HttpServletRequest;
    12. import javax.servlet.http.HttpServletResponse;
    13. /**
    14. * jwt令牌校验的拦截器
    15. */
    16. @Component
    17. @Slf4j
    18. public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    19. @Autowired
    20. private JwtProperties jwtProperties;
    21. /**
    22. * 校验jwt
    23. *
    24. * @param request
    25. * @param response
    26. * @param handler
    27. * @return
    28. * @throws Exception
    29. */
    30. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    31. //判断当前拦截到的是Controller的方法还是其他资源
    32. if (!(handler instanceof HandlerMethod)) {
    33. //当前拦截到的不是动态方法,直接放行
    34. return true;
    35. }
    36. //1、从请求头中获取令牌
    37. String token = request.getHeader(jwtProperties.getAdminTokenName());
    38. //2、校验令牌
    39. try {
    40. log.info("jwt校验:{}", token);
    41. Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
    42. Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
    43. log.info("当前员工id:{}", empId);
    44. //3、通过,放行
    45. return true;
    46. } catch (Exception ex) {
    47. //4、不通过,响应401状态码
    48. response.setStatus(401);
    49. return false;
    50. }
    51. }
    52. }

     0.4 ThreadLocal封装

    1. package com.sky.context;
    2. public class BaseContext {
    3. public static ThreadLocal threadLocal = new ThreadLocal<>();
    4. public static void setCurrentId(Long id) {
    5. threadLocal.set(id);
    6. }
    7. public static Long getCurrentId() {
    8. return threadLocal.get();
    9. }
    10. public static void removeCurrentId() {
    11. threadLocal.remove();
    12. }
    13. }

    0.5 对象转换器

     java序列化与反序列化,将指定的类型转为指定的格式。0.6中将会用到这个对象。

    1. package com.sky.json;
    2. import com.fasterxml.jackson.databind.DeserializationFeature;
    3. import com.fasterxml.jackson.databind.ObjectMapper;
    4. import com.fasterxml.jackson.databind.module.SimpleModule;
    5. import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
    6. import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
    7. import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
    8. import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
    9. import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
    10. import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
    11. import java.time.LocalDate;
    12. import java.time.LocalDateTime;
    13. import java.time.LocalTime;
    14. import java.time.format.DateTimeFormatter;
    15. import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
    16. /**
    17. * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
    18. * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
    19. * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
    20. */
    21. public class JacksonObjectMapper extends ObjectMapper {
    22. public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    23. //public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    24. public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
    25. public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    26. public JacksonObjectMapper() {
    27. super();
    28. //收到未知属性时不报异常
    29. this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    30. //反序列化时,属性不存在的兼容处理
    31. this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    32. SimpleModule simpleModule = new SimpleModule()
    33. .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
    34. .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
    35. .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
    36. .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
    37. .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
    38. .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
    39. //注册功能模块 例如,可以添加自定义序列化器和反序列化器
    40. this.registerModule(simpleModule);
    41. }
    42. }

    0.6 SpringMVC消息 转换器

    用于统一时间的格式。 

    MappingJackson2HttpMessageConverter对象有个很相似,不要倒错包。

    在配置类WebMvcConfiguration中添加消息转换器。

    1. /**
    2. * 扩展Spring MVC框架的消息转化器
    3. * @param converters
    4. */
    5. @Override
    6. protected void extendMessageConverters(List> converters) {
    7. log.info("扩展消息转换器...");
    8. //converters中存取了全部的转换对象,有很多
    9. //创建一个消息转换器对象
    10. MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    11. 需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据
    12. converter.setObjectMapper(new JacksonObjectMapper());
    13. //将自己的消息转化器加入容器中,默认是最后的优先级,所以要设置优先级最先执行。
    14. converters.add(0,converter);
    15. }

    0.7 AOP公共字段填充

    技术点:枚举、注解、AOP、反射

    0.7.1 自定义注解 AutoFill

    1. package com.sky.annotation;
    2. import com.sky.enumeration.OperationType;
    3. import java.lang.annotation.ElementType;
    4. import java.lang.annotation.Retention;
    5. import java.lang.annotation.RetentionPolicy;
    6. import java.lang.annotation.Target;
    7. /**
    8. * 自定义注解,用于标识某个方法需要进行功能字段自动填充处理
    9. */
    10. @Target(ElementType.METHOD)
    11. @Retention(RetentionPolicy.RUNTIME)
    12. public @interface AutoFill {
    13. //数据库操作类型:UPDATE INSERT
    14. OperationType value();
    15. }

    0.7.2 定义枚举(操作的类型) 

     insert和update操作的属性不同。

    1. package com.sky.enumeration;
    2. /**
    3. * 数据库操作类型
    4. */
    5. public enum OperationType {
    6. /**
    7. * 更新操作
    8. */
    9. UPDATE,
    10. /**
    11. * 插入操作
    12. */
    13. INSERT
    14. }

    0.7.3 定义切面类

    切入点表达式+通知,进行逻辑操作。

    1. package com.sky.aspect;
    2. import com.sky.annotation.AutoFill;
    3. import com.sky.constant.AutoFillConstant;
    4. import com.sky.context.BaseContext;
    5. import com.sky.enumeration.OperationType;
    6. import lombok.extern.slf4j.Slf4j;
    7. import org.aspectj.lang.JoinPoint;
    8. import org.aspectj.lang.annotation.Aspect;
    9. import org.aspectj.lang.annotation.Before;
    10. import org.aspectj.lang.annotation.Pointcut;
    11. import org.aspectj.lang.reflect.MethodSignature;
    12. import org.springframework.stereotype.Component;
    13. import java.lang.reflect.Method;
    14. import java.time.LocalDateTime;
    15. /**
    16. * 自定义切面,实现公共字段自动填充处理逻辑
    17. */
    18. @Aspect
    19. @Component
    20. @Slf4j
    21. public class AutoFillAspect {
    22. /**
    23. * 切入点
    24. */
    25. @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    26. public void autoFillPointCut(){}
    27. /**
    28. * 前置通知,在通知中进行公共字段的赋值
    29. */
    30. @Before("autoFillPointCut()")
    31. public void autoFill(JoinPoint joinPoint){
    32. log.info("开始进行公共字段自动填充...");
    33. //获取到当前被拦截的方法上的数据库操作类型
    34. MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
    35. AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
    36. OperationType operationType = autoFill.value();//获得数据库操作类型
    37. //获取到当前被拦截的方法的参数--实体对象
    38. Object[] args = joinPoint.getArgs();
    39. if(args == null || args.length == 0){
    40. return;
    41. }
    42. Object entity = args[0];
    43. //准备赋值的数据
    44. LocalDateTime now = LocalDateTime.now();
    45. Long currentId = BaseContext.getCurrentId();
    46. //根据当前不同的操作类型,为对应的属性通过反射来赋值
    47. if(operationType == OperationType.INSERT){
    48. //为4个公共字段赋值
    49. try {
    50. Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
    51. Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
    52. Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
    53. Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
    54. //通过反射为对象属性赋值
    55. setCreateTime.invoke(entity,now);
    56. setCreateUser.invoke(entity,currentId);
    57. setUpdateTime.invoke(entity,now);
    58. setUpdateUser.invoke(entity,currentId);
    59. } catch (Exception e) {
    60. e.printStackTrace();
    61. }
    62. }else if(operationType == OperationType.UPDATE){
    63. //为2个公共字段赋值
    64. try {
    65. Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
    66. Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
    67. //通过反射为对象属性赋值
    68. setUpdateTime.invoke(entity,now);
    69. setUpdateUser.invoke(entity,currentId);
    70. } catch (Exception e) {
    71. e.printStackTrace();
    72. }
    73. }
    74. }
    75. }

     0.7.4 给方法添加注解

    给添加和修改的方法添加注解,来进行捕获。

    注解中的value属性,就是枚举类型,来标记是什么操作。

    1. package com.sky.mapper;
    2. @Mapper
    3. public interface CategoryMapper {
    4. /**
    5. * 插入数据
    6. * @param category
    7. */
    8. @Insert("insert into category(type, name, sort, status, create_time, update_time, create_user, update_user)" +
    9. " VALUES" +
    10. " (#{type}, #{name}, #{sort}, #{status}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser})")
    11. @AutoFill(value = OperationType.INSERT)
    12. void insert(Category category);
    13. /**
    14. * 根据id修改分类
    15. * @param category
    16. */
    17. @AutoFill(value = OperationType.UPDATE)
    18. void update(Category category);
    19. }

    0.8 OSS对象存储

    出现过的问题:

    上传成功了,但是回显时图片不显示。其实上传没问题。回显的地址其实也没问题。原因在于alioss权限要设置为公共读写,不要设置私有,设置私有后。上传成功后,就会在图片地址后面拼接一些英文数字字符串。这样就导致回显时,因为没有后面拼接的字符串,他就会加载不出来图片。

    1定义OSS相关配置

    application-dev.yml

    1. sky:
    2. alioss:
    3. endpoint: oss-cn-hangzhou.aliyuncs.com
    4. access-key-id: LTAI5tPeFLzsPPT8gG3LPW64
    5. access-key-secret: U6k1brOZ8gaOIXv3nXbulGTUzy6Pd7
    6. bucket-name: sky-take-out

    application.yml  

    1. sky:
    2. alioss:
    3. endpoint: ${sky.alioss.endpoint}
    4. access-key-id: ${sky.alioss.access-key-id}
    5. access-key-secret: ${sky.alioss.access-key-secret}
    6. bucket-name: ${sky.alioss.bucket-name}

    2读取OSS配置

    用于封装这四个属性,封装yml中的值。

    1. package com.sky.properties;
    2. import lombok.Data;
    3. import org.springframework.boot.context.properties.ConfigurationProperties;
    4. import org.springframework.stereotype.Component;
    5. @Component
    6. @ConfigurationProperties(prefix = "sky.alioss")
    7. @Data
    8. public class AliOssProperties {
    9. private String endpoint;
    10. private String accessKeyId;
    11. private String accessKeySecret;
    12. private String bucketName;
    13. }

    3). 生成OSS工具类对象

    创建配置类,项目启动时,创建OSSutil对象(并加入基本的四个属性值)。

    要加@Bean,要不然后面注入不进去,扫描不到。

    1. package com.sky.config;
    2. import com.sky.properties.AliOssProperties;
    3. import com.sky.utils.AliOssUtil;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    6. import org.springframework.context.annotation.Bean;
    7. import org.springframework.context.annotation.Configuration;
    8. /**
    9. * 配置类,用于创建AliOssUtil对象
    10. */
    11. @Configuration
    12. @Slf4j
    13. public class OssConfiguration {
    14. @Bean
    15. @ConditionalOnMissingBean
    16. public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
    17. log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
    18. return new AliOssUtil(aliOssProperties.getEndpoint(),
    19. aliOssProperties.getAccessKeyId(),
    20. aliOssProperties.getAccessKeySecret(),
    21. aliOssProperties.getBucketName());
    22. }
    23. }

    工具类封装

    第一个参数是byte数组,就是文件对象封装的数组。

    第二个参数,就是在服务器中存储的名字。

    1. package com.sky.utils;
    2. import com.aliyun.oss.ClientException;
    3. import com.aliyun.oss.OSS;
    4. import com.aliyun.oss.OSSClientBuilder;
    5. import com.aliyun.oss.OSSException;
    6. import lombok.AllArgsConstructor;
    7. import lombok.Data;
    8. import lombok.extern.slf4j.Slf4j;
    9. import java.io.ByteArrayInputStream;
    10. @Data
    11. @AllArgsConstructor
    12. @Slf4j
    13. public class AliOssUtil {
    14. private String endpoint;
    15. private String accessKeyId;
    16. private String accessKeySecret;
    17. private String bucketName;
    18. /**
    19. * 文件上传
    20. *
    21. * @param bytes
    22. * @param objectName
    23. * @return
    24. */
    25. public String upload(byte[] bytes, String objectName) {
    26. // 创建OSSClient实例。
    27. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    28. try {
    29. // 创建PutObject请求。
    30. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
    31. } catch (OSSException oe) {
    32. System.out.println("Caught an OSSException, which means your request made it to OSS, "
    33. + "but was rejected with an error response for some reason.");
    34. System.out.println("Error Message:" + oe.getErrorMessage());
    35. System.out.println("Error Code:" + oe.getErrorCode());
    36. System.out.println("Request ID:" + oe.getRequestId());
    37. System.out.println("Host ID:" + oe.getHostId());
    38. } catch (ClientException ce) {
    39. System.out.println("Caught an ClientException, which means the client encountered "
    40. + "a serious internal problem while trying to communicate with OSS, "
    41. + "such as not being able to access the network.");
    42. System.out.println("Error Message:" + ce.getMessage());
    43. } finally {
    44. if (ossClient != null) {
    45. ossClient.shutdown();
    46. }
    47. }
    48. //文件访问路径规则 https://BucketName.Endpoint/ObjectName
    49. StringBuilder stringBuilder = new StringBuilder("https://");
    50. stringBuilder
    51. .append(bucketName)
    52. .append(".")
    53. .append(endpoint)
    54. .append("/")
    55. .append(objectName);
    56. log.info("文件上传到:{}", stringBuilder.toString());
    57. return stringBuilder.toString();
    58. }
    59. }

     4). 定义文件上传接口

    注入工具类,完成逻辑开发

    1. package com.sky.controller.admin;
    2. import com.sky.constant.MessageConstant;
    3. import com.sky.result.Result;
    4. import com.sky.utils.AliOssUtil;
    5. import io.swagger.annotations.Api;
    6. import io.swagger.annotations.ApiOperation;
    7. import lombok.extern.slf4j.Slf4j;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.web.bind.annotation.PostMapping;
    10. import org.springframework.web.bind.annotation.RequestMapping;
    11. import org.springframework.web.bind.annotation.RestController;
    12. import org.springframework.web.multipart.MultipartFile;
    13. import java.io.IOException;
    14. import java.util.UUID;
    15. /**
    16. * 通用接口
    17. */
    18. @RestController
    19. @RequestMapping("/admin/common")
    20. @Api(tags = "通用接口")
    21. @Slf4j
    22. public class CommonController {
    23. @Autowired
    24. private AliOssUtil aliOssUtil;
    25. /**
    26. * 文件上传
    27. * @param file
    28. * @return
    29. */
    30. @PostMapping("/upload")
    31. @ApiOperation("文件上传")
    32. public Result upload(MultipartFile file){
    33. log.info("文件上传:{}",file);
    34. try {
    35. //原始文件名
    36. String originalFilename = file.getOriginalFilename();
    37. //截取原始文件名的后缀 dfdfdf.png
    38. String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
    39. //构造新文件名称
    40. String objectName = UUID.randomUUID().toString() + extension;
    41. //文件的请求路径
    42. String filePath = aliOssUtil.upload(file.getBytes(), objectName);
    43. return Result.success(filePath);
    44. } catch (IOException e) {
    45. log.error("文件上传失败:{}", e);
    46. }
    47. return Result.error(MessageConstant.UPLOAD_FAILED);
    48. }
    49. }

     

    一、nginx相关

    1.1 使用

     

    nginx.exe:启动,如果启动不成功,查看logs中的日志信息,排除一下是否是端口被占用,nginx默认是80端口。

     html:打包后的代码放在此文件夹。多个前段项目都可以放进来。

    只需要修改下配置文件。配置文件在conf文件夹中。

    配置两个service即可,分别对应两个前端项目。

    代码详情如下:

    1. #user nobody;
    2. worker_processes 1;
    3. #error_log logs/error.log;
    4. #error_log logs/error.log notice;
    5. #error_log logs/error.log info;
    6. #pid logs/nginx.pid;
    7. events {
    8. worker_connections 1024;
    9. }
    10. http {
    11. include mime.types;
    12. default_type application/octet-stream;
    13. #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    14. # '$status $body_bytes_sent "$http_referer" '
    15. # '"$http_user_agent" "$http_x_forwarded_for"';
    16. #access_log logs/access.log main;
    17. sendfile on;
    18. #tcp_nopush on;
    19. #keepalive_timeout 0;
    20. keepalive_timeout 65;
    21. #gzip on;
    22. server {
    23. listen 80;
    24. server_name localhost;
    25. #charset koi8-r;
    26. #access_log logs/host.access.log main;
    27. location / {
    28. root "D:/dev/nginx-1.14.0/html/tijian";
    29. index index.html index.htm;
    30. }
    31. #error_page 404 /404.html;
    32. # redirect server error pages to the static page /50x.html
    33. #
    34. error_page 500 502 503 504 /50x.html;
    35. location = /50x.html {
    36. root html;
    37. }
    38. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    39. #
    40. #location ~ \.php$ {
    41. # proxy_pass http://127.0.0.1;
    42. #}
    43. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    44. #
    45. #location ~ \.php$ {
    46. # root html;
    47. # fastcgi_pass 127.0.0.1:9000;
    48. # fastcgi_index index.php;
    49. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    50. # include fastcgi_params;
    51. #}
    52. # deny access to .htaccess files, if Apache's document root
    53. # concurs with nginx's one
    54. #
    55. #location ~ /\.ht {
    56. # deny all;
    57. #}
    58. }
    59. server {
    60. listen 81;
    61. server_name localhost;
    62. #charset koi8-r;
    63. #access_log logs/host.access.log main;
    64. location / {
    65. root "D:/dev/nginx-1.14.0/html/tijiancms";
    66. index index.html index.htm;
    67. }
    68. #error_page 404 /404.html;
    69. # redirect server error pages to the static page /50x.html
    70. #
    71. error_page 500 502 503 504 /50x.html;
    72. location = /50x.html {
    73. root html;
    74. }
    75. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    76. #
    77. #location ~ \.php$ {
    78. # proxy_pass http://127.0.0.1;
    79. #}
    80. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    81. #
    82. #location ~ \.php$ {
    83. # root html;
    84. # fastcgi_pass 127.0.0.1:9000;
    85. # fastcgi_index index.php;
    86. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    87. # include fastcgi_params;
    88. #}
    89. # deny access to .htaccess files, if Apache's document root
    90. # concurs with nginx's one
    91. #
    92. #location ~ /\.ht {
    93. # deny all;
    94. #}
    95. }
    96. # another virtual host using mix of IP-, name-, and port-based configuration
    97. #
    98. #server {
    99. # listen 8000;
    100. # listen somename:8080;
    101. # server_name somename alias another.alias;
    102. # location / {
    103. # root html;
    104. # index index.html index.htm;
    105. # }
    106. #}
    107. # HTTPS server
    108. #
    109. #server {
    110. # listen 443 ssl;
    111. # server_name localhost;
    112. # ssl_certificate cert.pem;
    113. # ssl_certificate_key cert.key;
    114. # ssl_session_cache shared:SSL:1m;
    115. # ssl_session_timeout 5m;
    116. # ssl_ciphers HIGH:!aNULL:!MD5;
    117. # ssl_prefer_server_ciphers on;
    118. # location / {
    119. # root html;
    120. # index index.html index.htm;
    121. # }
    122. #}
    123. }

    1.2 反向代理和负载均衡

    1.2.1 介绍

    前端访问的地址和后端接口真实的地址不一致。


    nginx 反向代理的好处:

    • 提高访问速度

      因为nginx本身可以进行缓存,如果访问的同一接口,并且做了数据缓存,nginx就直接可把数据返回,不需要真正地访问服务端,从而提高访问速度。

    • 进行负载均衡

      所谓负载均衡,就是把大量的请求按照我们指定的方式均衡的分配给集群中的每台服务器。

    • 保证后端服务安全

      因为一般后台服务地址不会暴露,所以使用浏览器不能直接访问,可以把nginx作为请求访问的入口,请求到达nginx后转发到具体的服务中,从而保证后端服务的安全

     1.2.2配置

    都是在nginx.conf中进行配置。

    1.2.2.1 反向代理
    1. server{
    2. listen 80;
    3. server_name localhost;
    4. location /api/{
    5. proxy_pass http://localhost:8080/admin/; #反向代理
    6. }
    7. }

    proxy_pass:该指令是用来设置代理服务器的地址,可以是主机名称,IP地址加端口号等形式。

    如上代码的含义是:监听80端口号, 然后当我们访问 http://localhost:80/api/../..这样的接口的时候,它会通过 location /api/ {} 这样的反向代理到 http://localhost:8080/admin/上来。

     图解:

    红色区域进行替换。 

    1.2.2.2 负载均衡

    负载均衡底层,就是使用的反向代理。

     webservers就是一个ip端口组。

    1. upstream webservers{
    2. server 192.168.100.128:8080;
    3. server 192.168.100.129:8080;
    4. }
    5. server{
    6. listen 80;
    7. server_name localhost;
    8. location /api/{
    9. proxy_pass http://webservers/admin;#负载均衡
    10. }
    11. }

    upstream:如果代理服务器是一组服务器的话,我们可以使用upstream指令配置后端服务器组。

    如上代码的含义是:监听80端口号, 然后当我们访问 http://localhost:80/api/../..这样的接口的时候,它会通过 location /api/ {} 这样的反向代理到 http://webservers/admin,根据webservers名称找到一组服务器,根据设置的负载均衡策略(默认是轮询)转发到具体的服务器。

    注:upstream后面的名称可自定义,但要上下保持一致。  

    nginx 负载均衡策略:

    名称说明
    轮询默认方式
    weight权重方式,默认为1,权重越高,被分配的客户端请求就越多
    ip_hash依据ip分配方式,这样每个访客可以固定访问一个后端服务
    least_conn依据最少连接方式,把请求优先分配给连接数少的后端服务
    url_hash依据url分配方式,这样相同的url会被分配到同一个后端服务
    fair依据响应时间方式,响应时间短的服务将会被优先分配

    具体配置方式:

    1. upstream webservers{
    2. server 192.168.100.128:8080 weight=90;
    3. server 192.168.100.129:8080 weight=10;
    4. }
    1. upstream webservers{
    2. ip_hash;
    3. server 192.168.100.128:8080;
    4. server 192.168.100.129:8080;
    5. }

    其他的类似。 

     二、代码相关

    2.1 build

    创建一个VO对象,此处使用的是builder构造器。当然去new对象也可以。但是使用builder(),在实体中要加入@Builder注解

     2.2 属性配置封装

    使用场景:

    拿到属性类中的实际值。jwtProperties 是上方依赖注入的。


    这是一个属性类。真正的结果,在yml配置文件中。 

    数据封装在配置文件中。 

     2.3 登录md5密码加密

     思路:

    用户输入账号密码,传输到后端。后端根据用户名查询,返回整条user数据(判断用户是否存在)。在使用传输过来的密码,将此密码进行md5加密与查询出来的数据比对。(用户存在,判断密码是否正确)

    1. public Employee login(EmployeeLoginDTO employeeLoginDTO) {
    2. String username = employeeLoginDTO.getUsername();
    3. String password = employeeLoginDTO.getPassword();
    4. //1、根据用户名查询数据库中的数据
    5. Employee employee = employeeMapper.getByUsername(username);
    6. //2、处理各种异常情况(用户名不存在、密码不对、账号被锁定)
    7. if (employee == null) {
    8. //账号不存在
    9. throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
    10. }
    11. //密码比对
    12. //需要进行md5加密,然后再进行比对
    13. password = DigestUtils.md5DigestAsHex(password.getBytes());
    14. if (!password.equals(employee.getPassword())) {
    15. //密码错误
    16. throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
    17. }
    18. if (employee.getStatus() == StatusConstant.DISABLE) {
    19. //账号被锁定
    20. throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
    21. }
    22. //3、返回实体对象
    23. return employee;
    24. }

    DigestUtils是spring提供的md5加密。 

    2.4 异常处理(全局异常处理器)

    代码中尽量避免字符串的出现,所以都维护在常量类中。 

     操作步骤

    1.将抛出的异常的类名复制出来,方便在全局异常处理器中进行捕获。

    SQLIntegrityConstraintViolationException

    2. 重写exceptionHandler方法,别忘了加上@ExceptionHandler注解。

    3.代码实现捕获指定异常。

    代码:

    第二个方法是。

    1. package com.sky.handler;
    2. import com.sky.constant.MessageConstant;
    3. import com.sky.exception.BaseException;
    4. import com.sky.result.Result;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.springframework.web.bind.annotation.ExceptionHandler;
    7. import org.springframework.web.bind.annotation.RestControllerAdvice;
    8. import java.sql.SQLIntegrityConstraintViolationException;
    9. /**
    10. * 全局异常处理器,处理项目中抛出的业务异常
    11. */
    12. @RestControllerAdvice
    13. @Slf4j
    14. public class GlobalExceptionHandler {
    15. /**
    16. * 捕获业务异常
    17. *
    18. * @param ex
    19. * @return
    20. */
    21. @ExceptionHandler
    22. public Result exceptionHandler(BaseException ex) {
    23. log.error("异常信息:{}", ex.getMessage());
    24. return Result.error(ex.getMessage());
    25. }
    26. /**
    27. * 捕获用户名重复异常(添加用户操作)
    28. * @param ex
    29. * @return
    30. */
    31. @ExceptionHandler
    32. public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
    33. // Duplicate entry 'zhangsan' for key 'employee.idx_username'
    34. log.error("异常信息:{}", ex.getMessage());
    35. //提示前端 用户名已经存在,并且将用户名取出来
    36. String message = ex.getMessage();
    37. if (message.contains("Duplicate entry")) {
    38. //空格进行分隔,取出第三个字符串,就是用户名
    39. String[] strArray = message.split(" ");
    40. String msg = strArray[2] + MessageConstant.YI_CUN_ZAI;//拼接已存在
    41. return Result.error(msg);
    42. }
    43. //如果不是,返回未知错误。
    44. return Result.error(MessageConstant.UNKNOWN_ERROR);
    45. }
    46. }

    2.5 ThreadLocal的使用

    1.存入

    //将当前员工id存入BaseContext中。BaseContext是对ThreadLocal的封装
    BaseContext.setCurrentId(empId);

    1. package com.sky.interceptor;
    2. import com.sky.constant.JwtClaimsConstant;
    3. import com.sky.context.BaseContext;
    4. import com.sky.properties.JwtProperties;
    5. import com.sky.utils.JwtUtil;
    6. import io.jsonwebtoken.Claims;
    7. import lombok.extern.slf4j.Slf4j;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.stereotype.Component;
    10. import org.springframework.web.method.HandlerMethod;
    11. import org.springframework.web.servlet.HandlerInterceptor;
    12. import javax.servlet.http.HttpServletRequest;
    13. import javax.servlet.http.HttpServletResponse;
    14. /**
    15. * jwt令牌校验的拦截器
    16. */
    17. @Component
    18. @Slf4j
    19. public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    20. @Autowired
    21. private JwtProperties jwtProperties;
    22. /**
    23. * 校验jwt
    24. *
    25. * @param request
    26. * @param response
    27. * @param handler
    28. * @return
    29. * @throws Exception
    30. */
    31. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    32. //判断当前拦截到的是Controller的方法还是其他资源
    33. if (!(handler instanceof HandlerMethod)) {
    34. //当前拦截到的不是动态方法,直接放行
    35. return true;
    36. }
    37. //1、从请求头中获取令牌
    38. String token = request.getHeader(jwtProperties.getAdminTokenName());
    39. //2、校验令牌
    40. try {
    41. log.info("jwt校验:{}", token);
    42. Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
    43. Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
    44. log.info("当前员工id:{}", empId);
    45. //将当前员工id存入BaseContext中。BaseContext是对ThreadLocal的封装
    46. BaseContext.setCurrentId(empId);
    47. //3、通过,放行
    48. return true;
    49. } catch (Exception ex) {
    50. //4、不通过,响应401状态码
    51. response.setStatus(401);
    52. return false;
    53. }
    54. }
    55. }

     2.取出

    serviceImpl中,取出   BaseContext.getCurrentId()

    1. @Override
    2. public void insertEmp(EmployeeDTO employeeDTO) {
    3. Employee employee = Employee.builder()
    4. .createTime(LocalDateTime.now())
    5. .updateTime(LocalDateTime.now())
    6. //设置默认密码123456,并进行加密
    7. .password(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()))
    8. //设置状态,默认为1
    9. .status(StatusConstant.ENABLE)
    10. //从BaseContext中获取存储的信息
    11. .createUser(BaseContext.getCurrentId())
    12. .updateUser(BaseContext.getCurrentId())
    13. .build();
    14. BeanUtils.copyProperties(employeeDTO, employee);
    15. employeeMapper.insertEmp(employee);
    16. }

     2.6 日期的格式

     解决方式:

    1). 方式一

    在属性上加上注解,对日期进行格式化

    但这种方式,需要在每个时间属性上都要加上该注解,使用较麻烦,不能全局处理。  

    2). 方式二(推荐 )

    在WebMvcConfiguration中扩展SpringMVC的消息转换器,统一对日期类型进行格式处理

    1. /**
    2. * 扩展Spring MVC框架的消息转化器
    3. * @param converters
    4. */
    5. protected void extendMessageConverters(List> converters) {
    6. log.info("扩展消息转换器...");
    7. //创建一个消息转换器对象
    8. MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    9. //需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据
    10. converter.setObjectMapper(new JacksonObjectMapper());
    11. //将自己的消息转化器加入容器中
    12. converters.add(0,converter);
    13. }

     对象转换器就是0.5

    三、常识规范理解

    3.1 dto、vo、pojo、Result

    vo中v联想view,所示是返回给前端想要的属性。

    dto是前端给后端传输的属性。

    pojo是和数据库相对应的实体。

    result规定,前后端传输都会封装为Result对象。

    result其中包含:

    1. {
    2. "code": 0,
    3. "data": {},
    4. "msg": "string"
    5. }

     3.2 log

    添加@Slf4j注解后,就可以使用log.info()了。最原始的方法就是 new。

    3.3 唯一约束异常

    java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'zhangsan' for key 'employee.idx_username'

    这个已经提示了idx_username是索引名称。Duplicate 重复。

     解决办法:查看2.4

    3.4 ThreadLocal存储

    介绍:

    ThreadLocal 并不是一个Thread,而是Thread的局部变量ThreadLocal为每个线程提供单独一份存储空间,具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外则不能访问。

    常用方法:

    • public void set(T value) 设置当前线程的线程局部变量的值

    • public T get() 返回当前线程所对应的线程局部变量的值

    • public void remove() 移除当前线程的线程局部变量

    一次请求,tomcat就会给我们分配一个线程。这一个请求中线程共享数据。

    例如:在拦截器中输出,controller中输出,controller调用service再调用mapper,service输出,mapper输出 的 线程id都是一致的。

     

     我们应该在拦截器的位置将数据(例如:当前人id)存储到ThreaLocal中,方便后续直接拿取。

    封装详情见:0.4

    使用详情见:2.5

    3.5 请求参数相关

     3.5.1 query

    常见与get请求,query就是路径后面拼接。

    3.5.2 body(json) 

    常见于post请求,参数都放在请求体中

    3.5.3 header

    请求头参数,token。在请求是携带在请求头中。

    3.6 @JsonFormat

    次注解用于格式化日期

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

    3.7 Mybatis别名

    1. mybatis:
    2. #mapper配置文件
    3. mapper-locations: classpath:mapper/*.xml
    4. type-aliases-package: com.sky.entity

     

    参数类型,就可以直接写别名 

    3.8 数据类型

    `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',

    private Long id;  实体中用Long来对应。

    3.9 路径参数+query参数 

    因为是post请求,所以参数要放在body中。

    路径参数与http字符串参数 。

    接口中id是Long类型,所以接口文档中用interger,不能用string,也不能用Integer(id会为null)。 

    3.10 相关注解

    @PathVariable 路径参数

    @RequestBody 前端传输json格式

    3.11 yml配置属性

     

    四、配置相关

    4.1 mybatis

    4.1.1 驼峰命名

    1. mybatis:
    2. configuration:
    3. #开启驼峰命名
    4. map-underscore-to-camel-case: true

    五、状态码

    5.1 401

    401状态码HTTP协议中的一个状态码,表示“未授权”(Unauthorized)

    解决:查看请求是否进入到controller中,如果没进入,就要考虑拦截器。

    可以查看token是否校验通过。

    六、工具的使用

    6.1 apifox 

    6.1.1 全局参数

     右上角可以设置环境,也可以设置全局参数,例如token。

    七、优雅代码 

    7.1 builder 

    实体上要添加@Builder注解

    1. Employee employee = Employee.builder()
    2. .createTime(LocalDateTime.now())
    3. .updateTime(LocalDateTime.now())
    4. //设置默认密码123456,并进行加密
    5. .password(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()))
    6. //设置状态,默认为1
    7. .status(StatusConstant.ENABLE)
    8. //从BaseContext中获取存储的信息
    9. .createUser(BaseContext.getCurrentId())
    10. .updateUser(BaseContext.getCurrentId())
    11. .build();

     7.2 option判空

  • 相关阅读:
    react native debugger
    使用浏览功能
    【苍穹外卖 | 项目日记】第六天
    Ubtunu排查磁盘空间是否已满—并清理的方式
    C++-Cmake指令:add_executable
    FFmpeg入门详解之116:rtsp live555摄像头直播
    【UE5 虚幻引擎】新建C++类:类的类型 命名 类的目标模块
    【智能家居项目】FreeRTOS版本——多任务系统中使用DHT11 | 获取SNTP服务器时间 | 重新设计功能框架
    第08章 索引的创建与设计原则【2.索引及调优篇】【MySQL高级】
    spring mvc:请求执行流程(一)之获取Handler
  • 原文地址:https://blog.csdn.net/qq_69325307/article/details/138002406