概述
Dubbo环境搭建
Windows-安装zookeeper
1、下载zookeeper:https://archive.apache.org/dist/zookeeper/zookeeper-3.4.13/
2、解压zookeeper,运行bin/zkServer.cmd,初次运行会报错,没有zoo.cfg配置文件
3、修改conf/zoo.cfg配置文件:将conf下的zoo_sample.cfg复制一份改名为zoo.cfg,注意几个重要位置:
dataDir=./ 临时数据存储的目录
clietPort=2181 zookeeper的端口号
修改完成后再次启动zookeeper
4、使用bin/zkcli.cmd测试,另起一个cmd运行
get / 获取根节点的值
ls / 列出zookeeper根下保存的所有节点
create -e /atguigu 123 创建一个atguigu节点,值为123
get /atguigu 获取/atguigu节点的值
搭建监控中心
https://github.com/apache/incubator-dubbo
1、修改 dubbo-admin/src/main/resources/application.properties
dubbo.registry.address=zookeeper://127.0.0.1:2181
2、进入dubbo-admin,cmd执行 mvn clean package 进行构建打包 ,打包成功后会在target中出现相应jar包
将jar包放置根目录,然后cmd执行命令运行jar包 java -jar dubbo-admin-0.0.1-SNAPSHOT.jar
浏览器输入:localhost:7001 访问dubbo控制台 密码root 账号root (注意,控制台启动前一定要保持zookeeper也在启动状态)
3、IDEA中编写相关代码
代码结构:
gmall-interface/src/main/java/gmall/bean/OrderService.java
package gmall.bean;
import gmall.bean.UserAddress;
import java.util.List;
public interface OrderService {
/**
* 初始化订单
* @param userId
*/
public List<UserAddress> initOrder(String userId);
}
gmall-interface/src/main/java/gmall/bean/UserAddress.java
package gmall.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;
}
}
gmall-interface/src/main/java/gmall/bean/UserService.java
package gmall.bean;
import gmall.bean.UserAddress;
import java.util.List;
/**
* 用户服务
* @author lfy
*
*/
public interface UserService {
/**
* 按照用户id返回所有的收货地址
* @param userId
* @return
*/
public List<UserAddress> getUserAddressList(String userId);
}
user-service-provider/src/main/java/gmall/service/impl/UserServiceImpl.java
package gmall.service.impl;
import gmall.bean.UserAddress;
import gmall.bean.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);
}
}
user-service-provider/src/main/java/gmall/MainApplication.java
package gmall;
import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApplication {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("provider.xml");
ioc.start();
System.in.read();
}
}
user-service-provider/src/main/resources/provider.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="20880"></dubbo:protocol>
<!-- 4、暴露服务 ref:指向服务的真正的实现对象 -->
<dubbo:service interface="gmall.bean.UserService"
ref="userServiceImpl" timeout="1000" version="1.0.0">
<dubbo:method name="getUserAddressList" timeout="1000"></dubbo:method>
</dubbo:service>
<!--统一设置服务提供方的规则 -->
<dubbo:provider timeout="1000"></dubbo:provider>
<!-- 服务的实现 -->
<bean id="userServiceImpl" class="gmall.service.impl.UserServiceImpl"></bean>
<!-- 连接监控中心 -->
<dubbo:monitor protocol="registry"></dubbo:monitor>
</beans>
user-service-provider/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-example-test</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>user-service-provider</artifactId>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>gmall-interface</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
order-service-consumer/src/main/java/gmall/service/impl/OrderServiceImpl.java
package gmall.service.impl;
import java.util.List;
import gmall.bean.OrderService;
import gmall.bean.UserAddress;
import gmall.bean.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 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;
}
}
order-service-consumer/src/main/java/gmall/MainApplication.java
package gmall;
import gmall.bean.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();
}
}
order-service-consumer/src/main/resources/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="gmall.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="gmall.bean.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>
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-example-test</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>order-service-consumer</artifactId>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>user-service-provider</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
运行 user-service-provider/src/main/java/gmall/MainApplication.java,查看管理控制台–>服务治理–>提供者:
运行 order-service-consumer/src/main/java/gmall/MainApplication.java,查看管理控制台–>服务治理–>消费者:
4、搭建监控中心
进入E:zookeeperincubator-dubbo-ops-masterdubbo-monitor-simple,执行:mvn clean package 进行打包
解压 dubbo-monitor-simple-2.0.0-assembly.tar.gz ,将解压后的 dubbo-monitor-simple-2.0.0 复制出来
修改配置文件 dubbo-monitor-simple-2.0.0confdubbo.properties:
启动 dubbo-monitor-simple-2.0.0assembly.binstart.bat
配置监控
重新启动 user-service-provider/src/main/java/gmall/MainApplication.java 和 order-service-consumer/src/main/java/gmall/MainApplication.java
访问:localhost:8080/services.html
整合SpringBoot
方法一
导入dubbo-start,在application.properties配置属性,使用@Service[暴露服务],使用Reference[引用服务]
代码编写:
springboot-user-service-provider/src/main/java/com/gmall/impl/UserServiceImpl.java
package com.gmall.impl;
import com.alibaba.dubbo.config.annotation.Service;
import gmall.bean.UserAddress;
import gmall.bean.UserService;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Service //暴露服务
@Component
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);
}
}
springboot-user-service-provider/src/main/java/com/gmall/SpringbootUserServiceProviderApplication.java
package com.gmall;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
/**
* 1、导入依赖
* 1)、导入dubbo-starter
* 2)、导入dubbo的其他依赖
*/
@EnableDubbo // 开启基于注解的dubbo功能
@SpringBootApplication
public class SpringbootUserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootUserServiceProviderApplication.class, args);
}
}
springboot-user-service-provider/application.properties
dubbo.application.name=user-service-provider
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
dubbo.monitor.protocol=registry
springboot-user-service-provider/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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.atguigu</groupId>
<artifactId>springboot-user-service-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-user-service-provider</name>
<description>springboot-user-service-provider</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>gmall-interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>
spring-cloud-starter-netflix-hystrix
</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
springboot-order-service-consumer/src/main/java/com/gmall/controller/OrderController.java
package com.gmall.controller;
import gmall.bean.OrderService;
import gmall.bean.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class OrderController {
@Autowired
OrderService orderService;
@ResponseBody
@RequestMapping("/initOrder")
public List<UserAddress> initOrder(@RequestParam("uid") String userId){
return orderService.initOrder(userId);
}
}
springboot-order-service-consumer/src/main/java/com/gmall/impl/OrderServiceImpl.java
package com.gmall.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import gmall.bean.OrderService;
import gmall.bean.UserAddress;
import gmall.bean.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
@Reference
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;
}
}
springboot-order-service-consumer/src/main/java/com/gmall/SpringbootOrderServiceConsumerApplication.java
package com.gmall;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableDubbo
@SpringBootApplication
public class SpringbootOrderServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootOrderServiceConsumerApplication.class, args);
}
}
springboot-order-service-consumer/src/main/resources/application.properties
server.port=8081
dubbo.application.name=boot-order-service-consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.monitor.protocol=registry
springboot-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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.atguigu</groupId>
<artifactId>springboot-order-service-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-order-service-consumer</name>
<description>springboot-order-service-consumer</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>gmall-interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>
spring-cloud-starter-netflix-hystrix
</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
运行 SpringbootUserServiceProviderApplication.java 和 SpringbootOrderServiceConsumerApplication.java
访问:http://localhost:7001/governance/providers 和 http://localhost:7001/governance/consumers
访问:http://localhost:8080/services.html 和 http://localhost:8081/initOrder?uid=1
方法二
保留dubbo xml配置文件:导入subbo-start,使用@ImportResource导入dubbo的配置文件即可
代码编写(上述代码中修改以下文件):
springboot-user-service-provider/src/main/java/com/gmall/SpringbootUserServiceProviderApplication.java
package com.gmall;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(locations = "classpath:provider.xml" )
@SpringBootApplication
public class SpringbootUserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootUserServiceProviderApplication.class, args);
}
}
springboot-user-service-provider/src/main/java/com/gmall/impl/UserServiceImpl.java
package com.gmall.impl;
import com.alibaba.dubbo.config.annotation.Service;
import gmall.bean.UserAddress;
import gmall.bean.UserService;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Component
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);
}
}
springboot-user-service-provider/src/main/resources/provider.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="springboot-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="20880"></dubbo:protocol>
<!-- 4、暴露服务 ref:指向服务的真正的实现对象 -->
<dubbo:service interface="gmall.bean.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.gmall.impl.UserServiceImpl"></bean>
<!-- 连接监控中心 -->
<dubbo:monitor protocol="registry"></dubbo:monitor>
</beans>
运行 springboot-user-service-provider/src/main/java/com/gmall/SpringbootUserServiceProviderApplication.java
访问 http://localhost:7001/governance/providers
方法三
使用注解API方式:将每一个组件手动创建到容器中,让dubbo扫描每一个组件
代码编写:
springboot-user-service-provider/src/main/java/com/gmall/config/MyDubboConfig.java
package com.gmall.config;
import com.alibaba.dubbo.config.*;
import gmall.bean.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class MyDubboConfig {
//<dubbo:application name="springboot-user-service-provider"></dubbo:application>
@Bean
public ApplicationConfig applicationConfig(){
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("springboot-user-service-provider");
return applicationConfig;
}
//<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"></dubbo:registry>
@Bean
public RegistryConfig registryConfig(){
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setProtocol("zookeeper");
registryConfig.setAddress("127.0.0.1:2181");
return registryConfig;
}
//<dubbo:protocol name="dubbo" port="20880"></dubbo:protocol>
@Bean
public ProtocolConfig protocolConfig(){
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(20882);
return protocolConfig;
}
/*
<dubbo:service interface="gmall.bean.UserService"
ref="userServiceImpl01" timeout="1000" version="1.0.0">
<dubbo:method name="getUserAddressList" timeout="1000"></dubbo:method>
</dubbo:service>
*/
@Bean
public ServiceConfig<UserService> userServiceServiceConfig(UserService userService){
ServiceConfig<UserService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(UserService.class);
serviceConfig.setRef(userService);
serviceConfig.setVersion("1.0.0");
//配置每一个method的信息
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("getUserAddressList");
methodConfig.setTimeout(1000);
//将method的设置关联到service配置中
List<MethodConfig> methods = new ArrayList<>();
methods.add(methodConfig);
serviceConfig.setMethods(methods);
return serviceConfig;
}
//<dubbo:provider timeout="1000"></dubbo:provider>
@Bean
public ProviderConfig providerConfig(){
ProviderConfig providerConfig = new ProviderConfig();
providerConfig.setTimeout(1000);
return providerConfig;
}
//<dubbo:monitor protocol="registry"></dubbo:monitor>
@Bean
public MonitorConfig monitorConfig(){
MonitorConfig monitorConfig = new MonitorConfig();
monitorConfig.setProtocol("registry");
return monitorConfig;
}
}
springboot-user-service-provider/src/main/java/com/gmall/impl/UserServiceImpl.java
package com.gmall.impl;
import com.alibaba.dubbo.config.annotation.Service;
import gmall.bean.UserAddress;
import gmall.bean.UserService;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Service //暴露服务
@Component
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);
}
}
springboot-user-service-provider/src/main/java/com/gmall/SpringbootUserServiceProviderApplication.java
package com.gmall;
import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.ImportResource;
@EnableDubbo(scanBasePackages = "com.gmall")
@SpringBootApplication
public class SpringbootUserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootUserServiceProviderApplication.class, args);
}
}
运行 springboot-user-service-provider/src/main/java/com/gmall/SpringbootUserServiceProviderApplication.java
访问 http://localhost:7001/governance/providers
xml相关配置
参考:https://dubbo.apache.org/zh/docsv2.7/user/references/xml/
高可用
1、zookeeper宕机可与dubbo直连
现象:zookeeper注册中心当即,还可以消费暴露的服务
实现:
springboot-order-service-consumer/src/main/java/com/gmall/impl/OrderServiceImpl.java
// 直接加url 直连
@Reference(url="127.0.0.1:20882")
原因:
- 监控中心当即不影响使用,只是丢失部分采样数据
- 数据库宕机后,注册中心仍能通过缓存提供服务列表查询,但不能注册新服务
- 注册中心对等集群,任意一台宕掉后,将自动切换到另一台
- 注册中心全部宕机后,服务提供者和服务消费者仍能通过本地缓存通讯
- 服务提供者无状态,任意一台宕机后,不影响使用
- 服务提供者全部宕机后,服务消费者应用将无法使用,并无限次重连等待服务提供者恢复
2、集群下dubbo负载均衡配置
在集群负载均衡时,Dubbo提供了多种负载均衡策略,缺省为random随机调用
负载均衡策略:默认使用Random LoadBalance
可在全局搜索RandomLoadBalance.class,鼠标移至AbstractLoadBalance,快捷键CTRL+H查看继承树:
-
Random LoadBalance
随机,按权重设置随机概率。在一个截面上碰撞的概率高,但调用量越大分布越均匀,而且按概率使用权重后也比较均匀,有利于动态调整提供者权重
-
RoundRobin LoadBalance
轮询,按公约后的权重设置轮询比率。存在慢的提供者累积请求的问题,比如:第二台机器很慢,但没挂,当请求调用到第二台时就卡在那,久而久之,所有请求都卡在调用的第二台上了
-
LeastActive LoadBalance
最少活跃调用数,相同活跃数的随机,活跃数指调用前后计数差。使慢的提供者收到更少的请求,因为慢的提供者的调用前后计数差会越大
-
ConslstentHash LoadBalance
一致性Hash,相同参数的请求总是发送到同一提供者。当某一台提供者挂掉时,原本发往该提供者的请求,基于虚拟节点,平摊到其他提供者,不会引起剧烈变动
参照更改负载均衡配置:https://dubbo.apache.org/zh/docsv2.7/user/examples/loadbalance/
3、服务降级
当服务器压力剧增的情况下,根据实际业务情况及流量,对一些服务和页面有策略的不处理或换种简单的方式处理。从而释放服务器资源以保证核心交易正常运作或高效运作。
实现:通过服务降级功能临时频闭某个出错的非关键服务,并定义降级后的返回策略。像注册中心写入动态配置覆盖规则
RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
Registry registry = registryFactory.getRegistry(URL.valueOf("zookeeper://10.20.153.10:2181"));
registry.register(URL.valueOf("override://0.0.0.0/com.foo.BarService?category=configurators&dynamic=false&application=foo&mock=force:return+null"));
- mock=force:return+null 表示消费方对该服务的方法调用都直接返回null值,不发起远程调用,用来屏蔽不重要服务不可用时对调用方的影响
- mock=fail:return+null 表示消费方对该服务的方法调用在失败后,再返回 null 值,不抛异常。用来容忍不重要服务不稳定时对调用方的影响
4、集群容错
在集群调用失败时,Dubbo 提供了多种容错方案,缺省为 failover 重试
集群容错模式及实现:
-
Failover Cluster
失败自动切换,当出现失败,重试其它服务器。通常用于读操作,但重试会带来更长延迟。可通过 retries=“2” 来设置重试次数(不含第一次)
重试次数配置如下: <dubbo:service retries="2" /> 或 <dubbo:reference retries="2" /> 或 <dubbo:reference> <dubbo:method name="findFoo" retries="2" /> </dubbo:reference>
-
Failfast Cluster
快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录
-
Failsafe Cluster
失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作
-
Failback Cluster
失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作
-
Forking Cluster
并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks=“2” 来设置最大并行数
-
Broadcast Cluster
广播调用所有提供者,逐个调用,任意一台报错则报错 [2]。通常用于通知所有提供者更新缓存或日志等本地资源信息
-
集群模式配置
<dubbo:service cluster="failsafe" /> 或 <dubbo:reference cluster="failsafe" />
4、整合
其它原理
标签解析:BeanDefinitionParser ctrl+H DubboBeanDefinitionParser
获取xml中的配置信息,并封装起来:
将之前的配置信息保存起来:
监听暴露服务:
暴露url地址:
拉取注册中心列表,加载协议地址端口:
最后
以上就是腼腆草莓为你收集整理的dubbo环境搭建的全部内容,希望文章能够帮你解决dubbo环境搭建所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复