什么是泛化调用?
说白一点就是服务消费者并没有服务的接口。
先定义一个简单的接口
public interface EasyCommonService {
public String helloService(String name);
}
接口的具体实现
public class EasyCommonServiceImpl implements EasyCommonService {
public String helloService(String name) {
System.out.println("name is "+ name);
return "hello " + name;
}
}
服务端的spring配置文件
<?xml version="1.1" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<dubbo:application owner="lyncc" name="bazinga-app" />
<!--zookeeper注册中心 -->
<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"/>
<dubbo:protocol name ="dubbo" port="20880" />
<bean id="easyCommonService" class="org.bazinga.service.impl.EasyCommonServiceImpl" />
<dubbo:service interface="org.bazinga.service.EasyCommonService" ref="easyCommonService" />
</beans>
消费端的spring配置文件
<?xml version="1.1" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<dubbo:application owner="lyncc" name="bazinga-consumer" />
<!--zookeeper注册中心 -->
<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"/>
<dubbo:reference id="easyCommonService" interface="org.bazinga.service.EasyCommonService" generic="true"/>
</beans>
有两点需要注意:第一个是interface,其实该接口在消费者并不存在,第二个地方需要注意的地方就是generic="true",表示该接口支持泛型调用。
public class DubboConsumerGenericService {
public static void main(String[] args) {
/Spring泛化调用/
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"spring-dubbo-consumer-generic.xml");
context.start();
GenericService easyCommonService = (GenericService) context.getBean("easyCommonService");
Object result = easyCommonService.$invoke("helloService", new String[] { "java.lang.String" }, new Object[] { "hello" });
System.out.println(result);
}
}
最后欢迎大家访问我的个人网站:1024s