Use dubbo parameter verification
- Dubbo supports validation of JSR-303 parameters. Validation =”true” is equivalent to enabling Dubbo’s ValidationFilter.
<dubbo:service retries="0" version="1.0.0" interface="cn.gov.zcy.hammurabi.facade.service.ConfigReadFacade"
ref="configReadFacadeImpl" timeout="1000" validation="true"/>
Copy the code
- However, errors directly thrown by Dubbo are encapsulated in multiple layers. It is difficult to use this parameter to verify failed errors. Therefore, a customized parameter validator is used to facilitate direct use of services.
Custom parameter validator
-
The functions of the customized parameter validator are basically the same as those of ValidationFilter, so the code can be basically the same as those of ValidationFilter. An error (parameter calibration is not thrown by dubbo internal error ConstraintViolationException) do their own packaging and processing.
-
To add your validator to the Dubbo framework for management, you need to implement the Invoke method of the Filter interface. Add the @activate annotation to identify the Filter as Dubbo
@Slf4j @Activate(order = -100, value = {"validation"}) public class ConfigValidationFilter implements Filter { private Validation validation; public void setValidation(Validation validation) { this.validation = validation; } @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { try { Validator validator = this.validation.getValidator(invoker.getUrl()); if(validator ! =null) { validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); }}catch(ConstraintViolationException e) { Set<ConstraintViolation<? >> constraintViolations = e.getConstraintViolations(); List<String> message = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()); ConfigParamException configParamException =new ConfigParamException(message.toString()); return new RpcResult(Response.fail(configParamException.getCode(), configParamException.getMessage())); } catch (RpcException var4) { throw var4; } catch (Throwable var5) { throw new RpcException(var5.getMessage(), var5); } returninvoker.invoke(invocation); }}Copy the code
-
Adding custom filters to dubbo also needs to be configured in dubbo. XML and resource files
dubbo.xml <! Filter --> <dubbo:provider filter="configValidationFilter"/>Under the meta-inf folder to create a folder of dubbo, installation of a com. Alibaba. The dubbo. RPC. The Filter file contents as follows: Full path configValidationFilter validators = cn. Gov. Zcy. Hammurabi. Facade. Filter. ConfigValidationFilterCopy the code