一、dubbo hello world入门示例
1、提出需求
某个电商系统,订单服务需要调用用户服务获取某个用户的所有地址;
我们现在需要创建两个服务模块进行测试:
模块 |
功能 |
订单服务web模块 |
创建订单等 |
用户服务service模块 |
查询用户地址等 |
测试预期结果:订单服务web模块在A服务器,用户服务模块在B服务器,A可以远程调用B的功能。
2、工程结构
根据 dubbo《服务化最佳实践》
a、分包
建议将服务接口,服务模型,服务异常等均放在 API 包中,因为服务模型及异常也是 API 的一部分,同时,这样做也符合分包原则:重用发布等价原则(REP),共同重用原则(CRP)。
如果需要,也可以考虑在 API 包中放置一份 spring 的引用配置,这样使用方,只需在 spring 加载过程中引用此配置即可,配置建议放在模块的包目录下,以免冲突,如:com/alibaba/china/xxx/dubbo-reference.xml。
b、粒度
服务接口尽可能大粒度,每个服务方法应代表一个功能,而不是某功能的一个步骤,否则将面临分布式事务问题,Dubbo 暂未提供分布式事务支持。服务接口建议以业务场景为单位划分,并对相近业务做抽象,防止接口数量爆炸。
不建议使用过于抽象的通用接口,如:Map query(Map),这样的接口没有明确语义,会给后期维护带来不便。
二、创建工程
1、创建project、module
本demo采用project以及多module的方式,project叫dubbo,module分别为gmall-interface、order-service-consumer、user-service-providor,如图:
a、父project
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.ty</groupId>
<artifactId>dubbo</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>gmall-interface</module>
<module>order-service-consumer</module>
<module>user-service-providor</module>
</modules> <!--如果不指定可能会报一个错误,@Override is not allowed when implementing interface method-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
b、公共接口层(gmall-interface)
结构如图:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>dubbo</artifactId>
<groupId>com.ty</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion> <artifactId>gmall-interface</artifactId> </project>
UserAddress
package com.ty.bean; import java.io.Serializable; /**
* 用户地址
* @author lfy
*
*/
public class UserAddress implements Serializable { private Integer id;
private String userAddress; //用户地址
private String userId; //用户id
private String consignee; //收货人
private String phoneNum; //电话号码
private String isDefault; //是否为默认地址 Y-是 N-否 public UserAddress() {
super();
// TODO Auto-generated constructor stub
} public UserAddress(Integer id, String userAddress, String userId, String consignee, String phoneNum,
String isDefault) {
super();
this.id = id;
this.userAddress = userAddress;
this.userId = userId;
this.consignee = consignee;
this.phoneNum = phoneNum;
this.isDefault = isDefault;
} public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getConsignee() {
return consignee;
}
public void setConsignee(String consignee) {
this.consignee = consignee;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getIsDefault() {
return isDefault;
}
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
} }
OrderService
package com.ty.service; import com.ty.bean.UserAddress; import java.util.List; public interface OrderService { /**
* 初始化订单
* @param userId
*/
public List<UserAddress> initOrder(String userId); }
UserService
package com.ty.service; import com.ty.bean.UserAddress; import java.util.List; /**
* 用户服务
* @author lfy
*
*/
public interface UserService { /**
* 按照用户id返回所有的收货地址
* @param userId
* @return
*/
public List<UserAddress> getUserAddressList(String userId); }
c、user-service-providor
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>dubbo</artifactId>
<groupId>com.ty</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion> <artifactId>user-service-providor</artifactId> <dependencies>
<dependency>
<groupId>com.ty</groupId>
<artifactId>gmall-interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency> <!-- 引入dubbo -->
<!-- https://mvnrepository.com/artifact/com.alibaba/dubbo -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
</dependency>
<!-- 注册中心使用的是zookeeper,引入操作zookeeper的客户端端 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency> </dependencies>
</project>
UserServiceImpl
package com.ty.service.impl; import com.ty.bean.UserAddress;
import com.ty.service.UserService; import java.util.Arrays;
import java.util.List; public class UserServiceImpl implements UserService { @Override
public List<UserAddress> getUserAddressList(String userId) {
System.out.println("UserServiceImpl.....old...");
// TODO Auto-generated method stub
UserAddress address1 = new UserAddress(1, "北京市昌平区宏福科技园综合楼3层", "1", "李老师", "010-56253825", "Y");
UserAddress address2 = new UserAddress(2, "深圳市宝安区西部硅谷大厦B座3层(深圳分校)", "1", "王老师", "010-56253825", "N");
/*try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
return Arrays.asList(address1,address2);
} }
UserServiceImpl2
package com.ty.service.impl; import com.ty.bean.UserAddress;
import com.ty.service.UserService; import java.util.Arrays;
import java.util.List; public class UserServiceImpl2 implements UserService { @Override
public List<UserAddress> getUserAddressList(String userId) {
System.out.println("UserServiceImpl.....new...");
// TODO Auto-generated method stub
UserAddress address1 = new UserAddress(1, "北京市昌平区宏福科技园综合楼3层", "1", "李老师", "010-56253825", "Y");
UserAddress address2 = new UserAddress(2, "深圳市宝安区西部硅谷大厦B座3层(深圳分校)", "1", "王老师", "010-56253825", "N"); return Arrays.asList(address1,address2);
} }
UserServiceStub
package com.ty.service.impl; import com.ty.bean.UserAddress;
import com.ty.service.UserService;
import org.springframework.util.StringUtils; import java.util.List; public class UserServiceStub implements UserService { private final UserService userService; /**
* 传入的是userService远程的代理对象
* @param userService
*/
public UserServiceStub(UserService userService) {
super();
this.userService = userService;
} @Override
public List<UserAddress> getUserAddressList(String userId) {
// TODO Auto-generated method stub
System.out.println("UserServiceStub.....");
if(!StringUtils.isEmpty(userId)) {
return userService.getUserAddressList(userId);
}
return null;
} }
MainApplication
package com.ty; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; public class MainApplication { public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("provider.xml");
ioc.start(); System.in.read();
} }
providor.xml
<?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://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!-- 1、指定当前服务/应用的名字(同样的服务名字相同,不要和别的服务同名) -->
<dubbo:application name="user-service-provider"></dubbo:application> <!-- 2、指定注册中心的位置 -->
<!-- <dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry> -->
<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"></dubbo:registry> <!-- 3、指定通信规则(通信协议?通信端口) -->
<dubbo:protocol name="dubbo" port="20882"></dubbo:protocol> <!-- 4、暴露服务 ref:指向服务的真正的实现对象 -->
<dubbo:service interface="com.ty.service.UserService"
ref="userServiceImpl01" timeout="1000" version="1.0.0">
<dubbo:method name="getUserAddressList" timeout="1000"></dubbo:method>
</dubbo:service> <!--统一设置服务提供方的规则 -->
<dubbo:provider timeout="1000"></dubbo:provider> <!-- 服务的实现 -->
<bean id="userServiceImpl01" class="com.ty.service.impl.UserServiceImpl"></bean> <dubbo:service interface="com.ty.service.UserService"
ref="userServiceImpl02" timeout="1000" version="2.0.0">
<dubbo:method name="getUserAddressList" timeout="1000"></dubbo:method>
</dubbo:service>
<bean id="userServiceImpl02" class="com.ty.service.impl.UserServiceImpl2"></bean> <!-- 连接监控中心 -->
<dubbo:monitor protocol="registry"></dubbo:monitor> </beans>
d、order-service-consumer
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>dubbo</artifactId>
<groupId>com.ty</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion> <artifactId>order-service-consumer</artifactId> <dependencies>
<dependency>
<groupId>com.ty</groupId>
<artifactId>gmall-interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- 引入dubbo -->
<!-- https://mvnrepository.com/artifact/com.alibaba/dubbo -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
</dependency>
<!-- 注册中心使用的是zookeeper,引入操作zookeeper的客户端端 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency> </dependencies>
</project>
OrderServiceImpl
package com.ty.service.impl; import com.ty.bean.UserAddress;
import com.ty.service.OrderService;
import com.ty.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* 1、将服务提供者注册到注册中心(暴露服务)
* 1)、导入dubbo依赖(2.6.2)\操作zookeeper的客户端(curator)
* 2)、配置服务提供者
*
* 2、让服务消费者去注册中心订阅服务提供者的服务地址
* @author lfy
*
*/
@Service
public class OrderServiceImpl implements OrderService { @Autowired
UserService userService; @Override
public List<UserAddress> initOrder(String userId) {
// TODO Auto-generated method stub
System.out.println("用户id:"+userId);
//1、查询用户的收货地址
List<UserAddress> addressList = userService.getUserAddressList(userId);
for (UserAddress userAddress : addressList) {
System.out.println(userAddress.getUserAddress());
}
return addressList;
} }
MainApplication
package com.ty; import com.ty.service.OrderService;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; public class MainApplication { @SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("consumer.xml"); OrderService orderService = applicationContext.getBean(OrderService.class); orderService.initOrder("1");
System.out.println("调用完成....");
System.in.read();
} }
consumer.xml
<?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://dubbo.apache.org/schema/dubbo"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<context:component-scan base-package="com.ty.service.impl"></context:component-scan> <dubbo:application name="order-service-consumer"></dubbo:application> <dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry> <!-- 配置本地存根--> <!--声明需要调用的远程服务的接口;生成远程服务代理 -->
<!--
1)、精确优先 (方法级优先,接口级次之,全局配置再次之)
2)、消费者设置优先(如果级别一样,则消费方优先,提供方次之)
-->
<!-- timeout="0" 默认是1000ms-->
<!-- retries="":重试次数,不包含第一次调用,0代表不重试-->
<!-- 幂等(设置重试次数)【查询、删除、修改】、非幂等(不能设置重试次数)【新增】 -->
<dubbo:reference interface="com.ty.service.UserService"
id="userService" timeout="5000" retries="3" version="*">
<!-- <dubbo:method name="getUserAddressList" timeout="1000"></dubbo:method> -->
</dubbo:reference> <!-- 配置当前消费者的统一规则:所有的服务都不检查 -->
<dubbo:consumer check="false" timeout="5000"></dubbo:consumer> <dubbo:monitor protocol="registry"></dubbo:monitor>
<!-- <dubbo:monitor address="127.0.0.1:7070"></dubbo:monitor> --> </beans>
三、测试
1、启动zooker的服务以及上篇博文中的dubbo-admin(java -jar的方式启动)
2、启动user-service-providor的MainApplication中的main方法
E:\jdk\bin\java.exe "-javaagent:E:\utils\Intellij idea\IntelliJ IDEA 2018.3.2\lib\idea_rt.jar=51328:E:\utils\Intellij idea\IntelliJ IDEA 2018.3.2\bin" -Dfile.encoding=UTF-8 -classpath E:\jdk\jre\lib\charsets.jar;E:\jdk\jre\lib\deploy.jar;E:\jdk\jre\lib\ext\access-bridge-64.jar;E:\jdk\jre\lib\ext\cldrdata.jar;E:\jdk\jre\lib\ext\dnsns.jar;E:\jdk\jre\lib\ext\jaccess.jar;E:\jdk\jre\lib\ext\jfxrt.jar;E:\jdk\jre\lib\ext\localedata.jar;E:\jdk\jre\lib\ext\nashorn.jar;E:\jdk\jre\lib\ext\sunec.jar;E:\jdk\jre\lib\ext\sunjce_provider.jar;E:\jdk\jre\lib\ext\sunmscapi.jar;E:\jdk\jre\lib\ext\sunpkcs11.jar;E:\jdk\jre\lib\ext\zipfs.jar;E:\jdk\jre\lib\javaws.jar;E:\jdk\jre\lib\jce.jar;E:\jdk\jre\lib\jfr.jar;E:\jdk\jre\lib\jfxswt.jar;E:\jdk\jre\lib\jsse.jar;E:\jdk\jre\lib\management-agent.jar;E:\jdk\jre\lib\plugin.jar;E:\jdk\jre\lib\resources.jar;E:\jdk\jre\lib\rt.jar;E:\workspaceidea\dubbo\user-service-providor\target\classes;E:\workspaceidea\dubbo\gmall-interface\target\classes;E:\respository\com\alibaba\dubbo\2.6.2\dubbo-2.6.2.jar;E:\respository\org\springframework\spring-context\4.3.16.RELEASE\spring-context-4.3.16.RELEASE.jar;E:\respository\org\springframework\spring-aop\4.3.16.RELEASE\spring-aop-4.3.16.RELEASE.jar;E:\respository\org\springframework\spring-beans\4.3.16.RELEASE\spring-beans-4.3.16.RELEASE.jar;E:\respository\org\springframework\spring-core\4.3.16.RELEASE\spring-core-4.3.16.RELEASE.jar;E:\respository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;E:\respository\org\springframework\spring-expression\4.3.16.RELEASE\spring-expression-4.3.16.RELEASE.jar;E:\respository\org\javassist\javassist\3.20.0-GA\javassist-3.20.0-GA.jar;E:\respository\org\jboss\netty\netty\3.2.5.Final\netty-3.2.5.Final.jar;E:\respository\org\apache\curator\curator-framework\2.12.0\curator-framework-2.12.0.jar;E:\respository\org\apache\curator\curator-client\2.12.0\curator-client-2.12.0.jar;E:\respository\org\apache\zookeeper\zookeeper\3.4.8\zookeeper-3.4.8.jar;E:\respository\log4j\log4j\1.2.16\log4j-1.2.16.jar;E:\respository\jline\jline\0.9.94\jline-0.9.94.jar;E:\respository\io\netty\netty\3.7.0.Final\netty-3.7.0.Final.jar;E:\respository\com\google\guava\guava\16.0.1\guava-16.0.1.jar;E:\respository\org\slf4j\slf4j-api\1.7.6\slf4j-api-1.7.6.jar com.ty.MainApplication
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
3、打开http://localhost:7001/
可以看到已经有两个服务了,说明user-service-providor启动ok
4、测试order-service-consumer(运行其main方法)
用户id:1
北京市昌平区宏福科技园综合楼3层
深圳市宝安区西部硅谷大厦B座3层(深圳分校)
调用完成....
说明消费方也调用成功
dubbo hello world已上传github:https://github.com/ali-mayun/dubbo