在描述这个BUG之前,我想先说一个需求场景,假设我们有一个DemoService接口:
public interface DemoService {
String sayHello(String name);
String sayHello2(String name);
}
我们想单独设置这两个方法的超时时间,该如何设置呢?
当然我们可以在consumer端通过@Reference注解的parameters注解实现(PS:基于XML的配置可以配置MethodConfig元素,but基于注解的配置没有单独设置某个method的配置,只能曲线救国,我们只要清楚一点就是所有的配置都会作为url参数的一部分就OK了,所以我们可以通过配置注解的parameters参数来往url上附加额外参数来达到相同的目的):
@RestController
public class DemoConsumerController {
@Reference(
version = "${demo.service.version}",
application = "${dubbo.application.id}",
registry = "${dubbo.registry.id}",
parameters = {"sayHello.timeout", "3000", "sayHello2.timeout", "5000"}
)
private DemoService demoService;
@RequestMapping("/sayHello")
public String sayHello(@RequestParam String name) throws ExecutionException, InterruptedException {
return demoService.sayHello(name);
}
@RequestMapping("/sayHello2")
public String sayHello2(@RequestParam String name) throws ExecutionException, InterruptedException {
return demoService.sayHello2(name);
}
}
这里我们将sayHello.timeout设置了3000毫秒,sayHello2.timeout设置了5000毫秒。运行程序,没有啥毛病。
但是dubbo官方推荐做法是尽量在provider端多做配置,比如timeout这种配置,应该在服务提供者端配置,而不是在消费者端配置,因为提供者更清楚他提供的方法大致会花费多长时间。(虽然按照dubbo的配置覆盖规则,在consumer端的配置会覆盖provider端的配置)。
好吧,那我们还是按官方的建议来调整这个配置,把timeout配置到@Service注解上去:
@Service(
version = "${demo.service.version}",
application = "${dubbo.application.id}",
protocol = "${dubbo.protocol.id}",
registry = "${dubbo.registry.id}"
, parameters = {"sayHello.timeout", "3100", "sayHello2.timeout", "5000"}
)
public class DefaultDemoService implements DemoService {
@Override
public String sayHello(String name) {
System.out.println("get request");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "sayHello Hello, " + name + " (from Spring Boot)";
}
@Override
public String sayHello2(String name) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "sayHello2 Hello, " + name + " (from Spring Boot)";
}
}
启动程序你会发现竟然报错了:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ServiceBean:defaultDemoService:com.kingnet.blockdata.service.DemoService:${demo.service.version}': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.Map' for property 'parameters'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String[]' to required type 'java.util.Map' for property 'parameters': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:589) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$97/1279271200.getObject(Unknown Source) ~[na:na]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:137) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.kingnet.blockdata.DubboProviderDemo.main(DubboProviderDemo.java:20) [classes/:na]
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.Map' for property 'parameters'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String[]' to required type 'java.util.Map' for property 'parameters': no matching editors or conversion strategy found
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:590) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:604) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:219) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1660) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1616) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1363) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:580) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 15 common frames omitted
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String[]' to required type 'java.util.Map' for property 'parameters': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:299) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 21 common frames omitted
原因很明显,@Service里面的parameters是String[]类型,但是要映射到ServiceBean的parameters属性是一个Map<String,String>类型,没法自动转换映射上去,所以报了这个错误。
那么如何解决这个问题呢?
我们查看源码发现ServiceBean是通过:
com.alibaba.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationBeanPostProcessor#registerServiceBean
这个BeanPostProcessor注册进来的,这里面扫描了所有打了@Service的类,把他们注册成了ServiceBean。
于是我们就有了曲线救国的方法,我们在定义一个BeanPostProcessor,在ServiceAnnotationBeanPostProcessor之后执行,然后在ServiceBean真正实例化之前转换一下parameters这个参数为Map<String,String>就好了:
import com.alibaba.dubbo.config.spring.ServiceBean;
import com.alibaba.dubbo.config.spring.convert.converter.StringArrayToMapConverter;
import com.alibaba.dubbo.config.spring.convert.converter.StringArrayToStringConverter;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import java.beans.PropertyDescriptor;
import java.util.Map;
/**
* 解决@Service注解配置parameters参数时无法将String[]转化成Map<String,String>的bug
*
* @author : xiaojun
* @since 13:16 2018/7/23
*/
public class ServiceParameterBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements PriorityOrdered {
@Override
public int getOrder() {
return PriorityOrdered.LOWEST_PRECEDENCE;
}
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
// pvs.getPropertyValue("parameter")
if (bean instanceof ServiceBean) {
PropertyValue propertyValue = pvs.getPropertyValue("parameters");
ConversionService conversionService = getConversionService();
if (propertyValue != null && propertyValue.getValue() != null && conversionService.canConvert(propertyValue.getValue().getClass(), Map.class)) {
Map parameters = conversionService.convert(propertyValue.getValue(), Map.class);
propertyValue.setConvertedValue(parameters);
}
}
return pvs;
}
private ConversionService getConversionService() {
DefaultConversionService conversionService = new DefaultConversionService();
conversionService.addConverter(new StringArrayToStringConverter());
conversionService.addConverter(new StringArrayToMapConverter());
return conversionService;
}
}
细心的读者可能已经发现了点端倪,为毛@Reference注解里面的parameters可以正确映射到ReferenceBean的Map<String,String> parameters上来。。。说来也有点坑,这两个注解Bean的实现方式竟然不统一。但是dubbo提供了一个Converter:
com.alibaba.dubbo.config.spring.convert.converter.StringArrayToMapConverter;
我们也用这个converter将原始PropertySource里面的String[] parameters转换成Map<String,String> parameters就行了。
这里还实现了Ordered接口,让我们的这个BeanPostProcessor的优先级最低,这样可以保证在dubbo自己的那个BeanPostProcessor之后执行,才能顺利转换这个属性。
当然,别忘了注册bean:
@Bean
ServiceParameterBeanPostProcessor serviceParameterBeanPostProcessor() {
return new ServiceParameterBeanPostProcessor();
}
启动程序查看一下console的url信息:
dubbo://192.168.56.1:12345/com.kingnet.blockdata.service.DemoService?anyhost=true&application=dubbo-provider-demo&dubbo=2.6.2&generic=false&interface=com.kingnet.blockdata.service.DemoService&methods=sayHello,sayHello2&pid=9052&revision=1.0.0&sayHello.timeout=3100&sayHello2.timeout=5000&side=provider&status=server×tamp=1532588660430&version=1.0.0
发现parameters的配置信息成功附加到url的参数里面了。