Dubbo RPC call parameters checksum error message automatically returns ---

Dubbo RPC calls in Consumer and Provider end can do mass participation validation of the method call, Bean Validation authentication parameters may be mentioned by way of JSR303 specification (Java Specification Requests) to verify, Dubbo official is so recommended. Best practices data model definition sub-section in the jar mentioned parameter passing the API package, if you do so, then the authentication parameters can be completed at the end of the Consumer, so that can reduce network overhead and early fail to get results.
    
The following description is based on Dubbo2.6.2 + Springboot2.1.3 environment, content will do some expansion on the basis of official documents on the Dubbo.
 
Hibernate Validation is an implementation of the Bean Validation is also Dubbo official recommended the implementation, use Hibernate Validation rely on the need to introduce the following:
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.16.Final</version>
</dependency>

<! - When starting the given java.lang.ExceptionInInitializerError then also introduced as el-api-dependent -> 
< dependency > 
    < the groupId > javax.el </ the groupId > 
    < the artifactId > javax.el-API </ the artifactId > 
    < Version > 3.0.0 </ Version > 
</ dependency >

Plus "@NotNull" mass participation notes in the DTO

@Data
public class AddressDto implements Serializable {

    @NotNull (message = "address can not be blank")
    private String address;
    private String city;
    private Boolean batch;

}

 

After adding annotation data requiring verification model-parameters, before the end of the Consumer RPC call requires called  ValidationFilter filter, the filter of the following acquisition JValidator validate method calls Dubbo provided to the validator

@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
    List<Class<?>> groups = new ArrayList<Class<?>>();
    String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
    Class<?> methodClass = null;
    try {
        methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
        groups.add(methodClass);
    } catch (ClassNotFoundException e) {
    }
    Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
    Method method = clazz.getMethod(methodName, parameterTypes);
    Class<?>[] methodClasses = null;
    if (method.isAnnotationPresent(MethodValidated.class)){
        methodClasses = method.getAnnotation(MethodValidated.class).value();
        groups.addAll(Arrays.asList(methodClasses));
    }
    // add into default group
    groups.add(0, Default.class);
    groups.add(1, clazz);

    // convert list to array
    Class<?>[] classgroups = groups.toArray(new Class[0]);

    Object parameterBean = getMethodParameterBean(clazz, method, arguments);
    if (parameterBean != null) {
        violations.addAll(validator.validate(parameterBean, classgroups ));
    }

    for (Object arg : arguments) {
        validate(violations, arg, classgroups);
    }

    if (!violations.isEmpty()) {
        logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
        throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
    }
}
  
ValidatorImpl.validate authentication parameters are used to provide a method Hibernate Validation is then performed after a further validate call private method in a for loop, the process type parameter passing DTO made a judgment, after verification return ConstraintVoilation complete set in the above method for the last set of violations done to determine whether the non-empty, non-empty represents the validation fails, and in the subsequent throw ConstraintViolationException exception that after a layer of your controller, can be defined ControllerAdvice we captured. Global exception handling reference , so only need to add a ExceptionHandler will be able to handle ConstraintViolationException Validation used in the annotated message returned to the calling terminal,
@ResponseBody
@ExceptionHandler(value = ValidationException.class)
public Result handleAddressException(ValidationException e){
    log.error(e.getMessage());
    ValidateMsg String = null ;
     // if the abnormality determination is ConstraintViolationException extracted message information 
    IF (E the instanceof ConstraintViolationException) {
        ConstraintViolationException cve = (ConstraintViolationException)e;
        Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations();
        for(ConstraintViolation cv : constraintViolations){
            validateMsg = cv.getMessage();
            break;
        }

        return ResultUtil.error(ResultEnum.VALIDATION_FAILURE.getCode(), validateMsg);
    }
    return ResultUtil.error(ResultEnum.VALIDATION_FAILURE.getCode(),e.getMessage());
}

 

JSON eventually get to the end result following the call

{
    "requestId": null,
    "success": false,
    "business": null,
    "code": "20001",
    "message": "地址不能为空",
    "date": null,
    "version": null,
    "obj": null
}

 

reference:

[1] Dubbo official documents

 

  

Guess you like

Origin www.cnblogs.com/mingorun/p/11013095.html