Spring Cloud微服务实战 打造企业级优惠券系统 5-4 阶段说明[微服务通用模块说明]

0    课程地址

https://coding.imooc.com/lesson/380.html#mid=28604

1    浓缩精华
2    个人关注
3    课程内容

一个大的业务系统拆分为多个小的功能微服务,必然会存在着一些代码在多个微服务中都会用到。这类代码我们称之为通用代码或者基础代码,通常,我们会把它们定义在一个(或者多个) xxx-common 包中(jar),
让其他的微服务去依赖它。

设计思想与实现的功能

设计思想

  • 通用的代码、配置不应该散落在各个业务模块中,不利于维护与更新
  • 一个大的系统,响应对象需要统一外层格式
  • 各种业务设计与实现,可能会抛出各种各样的异常,异常信息的收集也应该做到统一

实现难点与不易理解的知识点说明

统一异常需要注意对两个注解的理解

/**
 * <h1>全局异常处理</h1>
 * RestControllerAdvice: 组合注解, ControllerAdvice + ResponseBody, 是对 RestController 的功能增强
 * Created by Qinyi.
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * <h2>对 CouponException 进行统一处理</h2>
     * ExceptionHandler: 可以对指定的异常进行拦截
     * */
    @ExceptionHandler(value = CouponException.class)
    public CommonResponse<String> handlerAdException(HttpServletRequest req,
                                                     CouponException ex) {
        // 统一异常接口的响应
        // 优化: 定义不同类型的异常枚举(异常码和异常信息)
        CommonResponse<String> response = new CommonResponse<>(-1,
                "business error");
        response.setData(ex.getMessage());
        return response;
    }
}

统一响应需要注意对特殊情况(不需要统一响应的接口)的考虑

/**
 * <h1>忽略统一响应注解定义</h1>
 * 可以应用到类上,也可以应用到方法上
 * Created by Qinyi.
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreResponseAdvice {
}

/**
* <h2>判断是否需要对响应进行处理</h2>
* @return false: 不需要处理; true: 需要处理
* */
@Override
@SuppressWarnings("all")
public boolean supports(MethodParameter methodParameter,
                        Class<? extends HttpMessageConverter<?>> aClass) {

    // 如果当前方法所在的类标识了 IgnoreResponseAdvice 注解, 则不需要处理
    if (methodParameter.getDeclaringClass().isAnnotationPresent(
            IgnoreResponseAdvice.class
    )) {
        return false;
    }

    // 如果当前方法标识了 IgnoreResponseAdvice 注解, 则不需要处理
    if (methodParameter.getMethod().isAnnotationPresent(
            IgnoreResponseAdvice.class
    )) {
        return false;
    }

    // 对响应进行处理, 执行 beforeBodyWrite 方法
    return true;
}
4    代码演练 





诸葛
原文地址:https://www.cnblogs.com/1446358788-qq/p/14296123.html