Dubbo RPC接口的参数校验过程
作者:雪落南城
文章介绍了在服务A调用服务B时,如何通过添加validation="true"实现参数校验,包括在pom文件、配置文件或注解@Reference中设置,并说明服务B的接口DTO可嵌套校验,需使用@Valid和@Validated
Dubbo RPC接口的参数校验
服务A调用服务B时,调用时即对服务B的接口参数进行校验 ,无需进入到服务B
重点就是添加 validation = "true"
1、pom文件
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>2、dubbo xml配置
或者Config类修改 或者@Reference时添加
在客户端验证参数
<dubbo:reference id="validationService" interface="com.alibaba.dubbo.examples.validation.api.ValidationService" validation="true" />
在服务器端验证参数
<dubbo:service interface="com.alibaba.dubbo.examples.validation.api.ValidationService" validation="true" />
config类
@Bean
public ReferenceBean<PLRepaymentPlanService> repaymentPlanServiceReferenceBean(){
ReferenceBean<PLRepaymentPlanService> referenceBean = new ReferenceBean<>();
referenceBean.setInterface(PLRepaymentPlanService.class);
referenceBean.setCheck(false);
referenceBean.setValidation("true");
return referenceBean;
}@Reference
@Reference(validation = "true") TestService testService;
3、服务B的接口
Integer createRepaymentPlan(@Valid RepaymentPlanRequestDTO dto,@NotNull Integer age) throws PostLoanException;
DTO 内容
@Data
public class RepaymentPlanRequestDTO implements Serializable {
/**
* 业务源
**/
@NotNull
private Integer businessSource;
/**
* 业务类型0,消费贷; 1,现金贷; 2,租房; 3:payday;4:无预约现金贷 5有钱贷,6指尖贷,7多享贷,8租机,9白条,10医美,11前置扣款
**/
@NotNull
private Integer type;
/**
* 业务规则
*/
private String businessRule;
/**
* 订单id
**/
@NotNull
private Integer orderId;
/**
* 期数
**/
@NotNull
private Integer period;
/**
* 应还总额
**/
@NotNull
private BigDecimal total;
/**
* 每期应还
**/
@NotNull
private BigDecimal every;
/**
* 本金
**/
@NotNull
private BigDecimal principal;
/**
* 每期利率
**/
@NotNull
private BigDecimal rateEvery;
/**
* 服务费
**/
private BigDecimal serviceFee;
/**
* 用户id
**/
@NotNull
private Integer userinfoId;
/**
* 商品id
**/
private Integer goodsId;
/**
* 渠道id
**/
private Integer channelId;
/**
* 资方id
**/
private Integer capitalId;
/**
* 起息日
*/
private LocalDateTime startInterestDate;
/**
* 贷款天数
**/
private Integer payDays;
/**
* 提单编号(规则O2O+订单编号+资方+重试次数)
*/
private String channelOrderNO;
/**
* 是否通知
* 需要资方生成还款计划后资方平台通知/回调的订单
*/
private boolean hasNotified;
/**
* 订单四要素
*/
@Valid
private PLUserInfoDTO plUserInfoDTO;
}可以嵌套校验 但需要在嵌套校验的字段上加@Valid
实现类上需要加@Validated
启动服务B,服务A调用接口,符合添加的valid校验标准
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
