原文地址:啟用dubbo validation后hessian反序列化異常解決方案
現(xiàn)象
啟用dubbo參數(shù)驗證潮酒,當(dāng)在provider端開啟驗證validation="true"贤牛。調(diào)用接口時,若接口參數(shù)為對象類型犁河,對象屬性驗證失敗,客戶端會報如下異常魄梯。
2019-04-25T09:57:18.544+0800 [ERROR] business-service o.a.c.c.C.[.[.[.[dispatcherServlet] - - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.reflect.UndeclaredThrowableException] with root cause
com.alibaba.dubbo.remoting.RemotingException: com.alibaba.com.caucho.hessian.io.HessianFieldException: org.hibernate.validator.internal.engine.ConstraintViolationImpl.constraintDescriptor: 'org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl' could not be instantiated
com.alibaba.com.caucho.hessian.io.HessianFieldException: org.hibernate.validator.internal.engine.ConstraintViolationImpl.constraintDescriptor: 'org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl' could not be instantiated
at com.alibaba.com.caucho.hessian.io.JavaDeserializer.logDeserializeError(JavaDeserializer.java:167)
at com.alibaba.com.caucho.hessian.io.JavaDeserializer$ObjectFieldDeserializer.deserialize(JavaDeserializer.java:410)
at com.alibaba.com.caucho.hessian.io.JavaDeserializer.readObject(JavaDeserializer.java:276)
at com.alibaba.com.caucho.hessian.io.JavaDeserializer.readObject(JavaDeserializer.java:203)
at com.alibaba.com.caucho.hessian.io.SerializerFactory.readObject(SerializerFactory.java:526)
... more
Caused by: com.alibaba.com.caucho.hessian.io.HessianProtocolException: 'org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl' could not be instantiated
at com.alibaba.com.caucho.hessian.io.JavaDeserializer.instantiate(JavaDeserializer.java:316)
at com.alibaba.com.caucho.hessian.io.JavaDeserializer.readObject(JavaDeserializer.java:201)
at com.alibaba.com.caucho.hessian.io.Hessian2Input.readObjectInstance(Hessian2Input.java:2818)
at com.alibaba.com.caucho.hessian.io.Hessian2Input.readObject(Hessian2Input.java:2145)
at com.alibaba.com.caucho.hessian.io.Hessian2Input.readObject(Hessian2Input.java:2074)
at com.alibaba.com.caucho.hessian.io.Hessian2Input.readObject(Hessian2Input.java:2118)
at com.alibaba.com.caucho.hessian.io.Hessian2Input.readObject(Hessian2Input.java:2074)
at com.alibaba.com.caucho.hessian.io.JavaDeserializer$ObjectFieldDeserializer.deserialize(JavaDeserializer.java:406)
... 41 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.alibaba.com.caucho.hessian.io.JavaDeserializer.instantiate(JavaDeserializer.java:312)
... 48 more
Caused by: java.lang.NullPointerException
at org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl.<init>(ConstraintDescriptorImpl.java:176)
at org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl.<init>(ConstraintDescriptorImpl.java:233)
... more
版本
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.1</version>
</dependency>
同時測試了2.6.5也有同樣的問題桨螺。
分析
異常表象為'org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl' could not be instantiated,在繼續(xù)跟蹤棧信息是在下面的地方拋出了NullPointerException異常酿秸。
Caused by: java.lang.NullPointerException
at org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl.<init>(ConstraintDescriptorImpl.java:176)
at org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl.<init>(ConstraintDescriptorImpl.java:233)
進(jìn)入ConstraintDescriptorImpl.java:176行看下灭翔,代碼如下:
public ConstraintDescriptorImpl(ConstraintHelper constraintHelper,
Member member,
ConstraintAnnotationDescriptor<T> annotationDescriptor,
ElementType type,
Class<?> implicitGroup,
ConstraintOrigin definedOn,
ConstraintType externalConstraintType) {
this.annotationDescriptor = annotationDescriptor;
this.elementType = type;
this.definedOn = definedOn;
this.isReportAsSingleInvalidConstraint = annotationDescriptor.getType().isAnnotationPresent(ReportAsSingleViolation.class);
... more
報空指針的位置就是
this.isReportAsSingleInvalidConstraint = annotationDescriptor.getType().isAnnotationPresent(ReportAsSingleViolation.class);
結(jié)論
dubbo使用默認(rèn)序列化協(xié)議hessian,在反序列化時根據(jù)構(gòu)造函數(shù)參數(shù)個數(shù)優(yōu)先級來取參數(shù)最少的構(gòu)造器辣苏,由于ConstraintDescriptorImpl該類只一個構(gòu)造器肝箱,debug進(jìn)入發(fā)現(xiàn)在初始化時傳入的參數(shù)全部為null,這就造成了NullPointerException異常稀蟋,導(dǎo)致序列化失敗煌张。
從ConstraintViolationException繼承結(jié)構(gòu)可以看到其繼承自ValidationException,并增加了一個參數(shù)private final Set<ConstraintViolation<?>> constraintViolations;用來將驗證信息傳遞到consumer退客,反序列化的問題就是出在了Set<ConstraintViolation<?>>上骏融。
解決方案
知道了問題出在哪里,那解決起來還是很方便的萌狂。既然Set<ConstraintViolation<?>> constraintViolations是為了將校驗信息傳遞到consumer档玻,那我們自己自定義一個校驗信息體就OK啦。
使用dubbo驗證擴(kuò)展自定義一個validation茫藏。
具體實現(xiàn)如下:
實現(xiàn)一個Validation接口误趴,返回一個自定義的Validator
package com.example.demo.dubbo.validation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
/**
* @ClassName CustomValidation
* @Description
* @Author lixin
* @Date 2019-04-23 17:34
*/
public class CustomValidation implements Validation{
@Override
public Validator getValidator(URL url) {
return new CustomValidator(url);
}
}
CustomValidation實現(xiàn),這里只需要簡單的捕獲一下ConstraintViolationException異常务傲,將violations取出重新格式化即可冤留,同時還保持了dubbo validation的原生邏輯支持
package com.example.demo.dubbo.validation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.json.JSONArray;
import org.apache.dubbo.common.json.JSONObject;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.validation.support.jvalidation.JValidator;
import org.apache.dubbo.validation.Validator;
import javax.validation.*;
import java.util.*;
/**
* 繼承自{@link JValidator}保證了dubbo原生的vidation邏輯。
* 修改點:1树灶、捕獲ConstraintViolationException異常纤怒,將驗證未通過異常改為ValidationException,解決dubbo hessian反序列化失敗問題
* 2天通、格式化驗證提示泊窘,使用json格式響應(yīng)
*
* @Author lixin
* @Date 2019-04-23 17:35
*/
public class CustomValidator extends JValidator implements Validator {
private final Class<?> clazz;
@SuppressWarnings({"unchecked", "rawtypes"})
public CustomValidator(URL url) {
super(url);
this.clazz = ReflectUtils.forName(url.getServiceInterface());
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
try{
super.validate(methodName,parameterTypes,arguments);
}catch (ConstraintViolationException e){
throw new ValidationException(constraintMessage(clazz.getName(),methodName,e.getConstraintViolations()));
}
}
private String constraintMessage(String className,String methodName,Set<ConstraintViolation<?>> violations){
JSONObject json = new JSONObject();
json.put("service",className);
json.put("method",methodName);
JSONArray details = new JSONArray();
for(ConstraintViolation violation : violations){
JSONObject detail = new JSONObject();
detail.put("bean",violation.getRootBean().getClass().getName());
detail.put("property",violation.getPropertyPath().toString());
detail.put("message",violation.getMessage());
details.add(detail);
}
json.put("details",details);
return json.toString();
}
}
使用方式
provider端啟用(注解方式)
@Service(validation = "xxx")
consumer端啟用(注解方式)
@Reference(validation = "xxx")
建議
1、在consumer端開啟驗證,以減少無用的請求打到provider端烘豹。
2瓜贾、自定義的model類,增加默認(rèn)構(gòu)造器携悯。