Dubbo 统一参数验证

需求:

  • 方法注解实现参数验证
  • 消息文件存储消息字符串

实现:

  • 注解定义
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ValidBody {
    String desc() default "aop annotation for body validation";
}
  • 切面Aspect
@Aspect
public class BodyValidationAspect {

    private static final int DEFAULT_MAX_RETRIES = 2;

    private int maxRetries = DEFAULT_MAX_RETRIES;
    private int order = 2;

    public void setMaxRetries(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    @Autowired
    private ValidatorFactory validatorFactory;

    @Before("pointcut()")
    public void before(JoinPoint point) throws Exception {
        Object[] args = point.getArgs();
        BaseReqBody param = getBaseReqBodyFromArgs(args);
        if(param == null)
            return ;
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<BaseReqBody>> requestViolations =  validator.validate(param);
        boolean requestHasViolations = !requestViolations.isEmpty();
        if(requestHasViolations){
            ConstraintViolation<BaseReqBody> requestViolation = requestViolations.iterator().next();
            throw new ReqException(PARAM_INVALID, processForParaName(requestViolation.getMessage(),requestViolation));
        }
    }

    private String processForParaName(String oriMessage,ConstraintViolation<BaseReqBody> requestViolation){
        if(oriMessage.contains("paramName")){
            return oriMessage.replaceAll("paraName",requestViolation.getPropertyPath().iterator().next().getName());
        }
        return oriMessage;
    }

    public BaseReqBody getBaseReqBodyFromArgs(Object[] args){
        for(Object arg : args){
            if(arg.getClass().getSuperclass().equals(BaseReqBody.class)||arg instanceof BaseReqBody)
                return (BaseReqBody)arg;
        }
        return null;
    }

    @Pointcut("@annotation(com.xxxx.xx.xx.annotation.ValidBody)")
    public void pointcut(){}
}

使用

@Override
@ValidBody
public TerminalScanOrderCreateRespBody addMerchantOrder(TerminalScanOrderCreateReqBody body) throws Exception {
        return null;
}
public class TerminalScanOrderCreateReqBody extends BaseReqBody {

    @JSONField(name = "ts_no")
    @JsonProperty("ts_no")
    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 32,message = "${Size}")
    private String tsNo;//ts_no

    @JSONField(name = "ts_time", format = "yyyy-MM-dd HH:mm:ss")
    @JsonProperty("ts_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date tsTime;//ts_time

    @JSONField(name = "order_fee")
    @JsonProperty("order_fee")
    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 12,message = "${Size}")
    @Money
    private String orderFee;//order_fee

    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 12,message = "${Size}")
    @Money
    private String fee;//fee

    @JSONField(name = "coin_type")
    @JsonProperty("coin_type")
    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 16,message = "${Size}")
    private String coinType;//coin_type

    @JSONField(name = "coupon_code")
    @JsonProperty("coupon_code")
    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 32,message = "${Size}")
    private String couponCode;//coupon_code

    @JSONField(name = "mch_code")
    @JsonProperty("mch_code")
    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 32,message = "${Size}")
    private String shopCode;//mch_code

    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 32,message = "${Size}")
    private String sn;

    @JSONField(name = "operator_id")
    @JsonProperty("operator_id")
    @NotEmpty(message = "${NotEmpty}")
    @Size(max = 32,message = "${Size}")
    private String operatorId;//operator_id

    public TerminalScanOrderCreateReqBody() {
    }

    //getter setter
}

  • 消息模板EL 表达式不生效
    • 原因
       <property name="useCodeAsDefaultMessage" value="true" />
      

CommonMessage.properties

NotEmpty = param paramName can not be empty
Size = {validatedValue} is too long for paramName
Money = {validatedValue} wrong format for paramName
    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>i18n/messages/BaseRespMesage</value>
                <value>i18n/messages/BizMessage</value>
                <value>i18n/messages/CommonMessage</value>
            </list>
        </property>
        <property name="fileEncodings">
            <value>utf-8</value>
        </property>
        <property name="useCodeAsDefaultMessage" value="false" />
        <property name="cacheSeconds" value="120"></property>
    </bean>

转载于:https://my.oschina.net/u/732556/blog/1529192

本课程是一门具有很强实践性质的“项目实战”课程,即“企业中台系统实战”,其中主要包含三大块核心内容,如下图所示(右键可以在新标签页中打开图片放大查看): 即主要包含以下三大块内容: ① 企业内部应用系统菜单资源和操作权限的统一管理; ② 分布式应用系统通信时的统一授权,即基于AccessToken的授权与认证; ③ 分布式服务/系统通信时的两大方式(基于dubbo rpc协议和基于http协议的restful api实战)。   值得一提的是,这套中台系统由于讲解了如何统一管理企业内部各大应用系统的“菜单资源列表”、“操作权限”,故而本门课程的“代码实战”是建立在之前debug录制的“企业权限管理平台”这套课程的基础之上的,故而在这里debug建议没有项目开发基础的小伙伴可以先去学习我的那套“企业权限管理平台”的实战课程,之后再来学习我的这套中台系统的实战才不会很吃力(课程链接:)   本课程的课程大纲如下图所示(右键可以在新标签页中打开图片放大查看):   除此之外,这套“中台系统”由于统一管理了企业内部各大应用系统的“菜单资源和操作权限”以及“应用系统之间通信时的统一授权”,故而难免需要涉及到“中台系统”与“中台子系统”、“中台子系统”与“中台子系统”之间的通信(即分布式服务之间的通信),在这里我们是采用“dubbo + zookeeper”的方式加以落地实现的,详情如下图所示(右键可以在新标签页中打开图片放大查看):   而众所周知,作为一款知名以及相当流行的分布式服务调度中间件,dubbo现如今已经晋升为Apache顶级的开源项目,未来也仍将成为“分布式系统”开发实战的一大利器,如下图所示为dubbo底层核心系统架构图(右键可以在新标签页中打开图片放大查看): 而在这门“中台系统实战”的课程中,我们也将始终贯彻、落地dubbo的这一核心系统架构图,即如何将中台系统开发的服务注册/发布到注册中心zookeeper,中台子系统如何订阅/消费/调度中台系统发布在zookeeper的接口服务,中台子系统在走http协议调度通信时dubbo如何进行拦截、基于token认证接口的调用者等等,这些内容我们在课程中将一一得到代码层面的实战落地!   下图为本课程中涉及到的分布式系统/服务之间 采用“http协议restfulapi”方式通信时的Token授权、认证的流程图(右键可以在新标签页中打开图片放大查看): 而不夸张地说,基于AccessToken的授权、认证方式在现如今微服务、分布式时代系统与系统在通信期间最为常用的“授权方式”了,可想而知,掌握其中的流程思想是多么的重要!   以下为本门课程的部分截图(右键可以在新标签页中打开图片放大查看):     核心技术列表: 值得一提的是,由于本门课程是一门真正介绍“中台思想”以及将“中台思想”和“分布式系统开发实战”相结合落地的课程,故而在学完本门课程之后,可以掌握到的核心技术自然是相当多的。主要由SpringBoot2.0、SpringMVC、Mybatis、Dubbo、ZooKeeper、Redis、OkHttp3、Guava-Retrying重试机制、JWT(Json Web Token)、Shiro、分布式集群session共享、Lombok、StreamAPI、Dubbo-Filter以及ServiceBean等等。如下图所示(右键可以在新标签页中打开图片放大查看):
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值