1. Provider暴露服务
provider.xml配置:java
<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" xdi: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 name="aaron-user-app" /> <!— 使用zookeeper暴露服务地址 --> <dubbo:registry address="zookeeper://127.0.0.1:2181" client="zkclient"/> <!-- 用dubbo协议在20880端口暴露服务 --> <dubbo:protocol name="dubbo" port="20880" /> <dubbo:service interface="aaron.dubbo.provider.UserService" ref="userService"/> <bean id="userService" class="aaron.dubbo.provider.UserServiceImpl"/> </beans>
因为dubbo的服务器已经停服,因此dubbo.xsd须要引用本地,在setting—>Languages & FrameWorks —> Schemas and DTDS中,引用dubbo.jar中的dubbo.xsd便可。
定义接口:spring
public interface UserService { String getName(Long id); }
接口实现:服务器
public class UserServiceImpl implements UserService { @Override public String getName(Long id) { return "hello world!"; } }
启动服务:app
public class Provider { public static void main(String[] args) throws IOException { System.out.println("Provider"); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("provider.xml"); context.start(); System.in.read(); } }
2. Consumer引用服务
consumer.xml配置:ide
<?xml version="1.0" 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 name="consumer-of-aaron-user-app" /> <!— 使用zookeeper暴露发现服务地址 --> <dubbo:registry address="zookeeper://127.0.0.1:2181" client="zkclient"/> <!-- 生成远程服务代理,能够和本地bean同样使用demoService --> <dubbo:reference id="userService" interface="aaron.dubbo.provider.UserService" /> </beans>
一样这样也须要引用dubbo.jar中的dubbo.xsd。代理
定义接口:code
public interface UserService { String getName(Long id); }
调用服务:xml
public class Consumer { public static void main(String[] args) { System.out.println("Consumer"); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("consumer.xml"); context.start(); UserService userService = (UserService) context.getBean("userService"); String name = userService.getName(1L); System.out.println(name); } }