Dubbo+Zookeeper笔记
Dubbo简介
Dubbo是阿里巴巴开源的一款Java RPC框架
-
一款分布式服务框架
-
高性能和透明化的RPC远程服务调用方案
-
SOA服务治理方案
核心功能
智能容错和负载均衡
服务注册和发现
面向接口的远程方法调用
角色
Provider(生产者):暴露服务的服务提供者
Container:服务运行的容器
Consumer(消费者):调用远程服务的消费者
Registry:服务注册和发现的注册中心
Minitor:统计服务调用次数和时间的监控中心
架构
1、单体应用
2、垂直应用
3、SOA 架构
4、微服务架构
dubbo+zookeeper
zookeeper是dubbo的注册中心,可以用于dubbo作负载均衡。
1、安装zookeeper
https://zookeeper.apache.org/releases.html
2、安装dubbo
https://github.com/apache/dubbo
配置 依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
<dependency>
<groupId>com.bx.dubbo</groupId>
<version>1.0-SNAPSHOT</version>
<artifactId>spring-cloud-dubbo-sample-api</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
多个服务端口使用一个通讯协议
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<dubbo:application name="world" />
<dubbo:registry id="registry" address="" username="admin" password="hello1234" />
<dubbo:protocol name="dubbo" port="20880" />
<!-- Use dubbo protocol to expose the service -->
<dubbo:service interface="com.alibaba.hello.api.HelloService" version="1.0.0" ref="helloService" />
<dubbo:service interface="com.alibaba.hello.api.DemoService" version="1.0.0" ref="demoService" />
</beans>
LoadBalance算法
@SPI(RandomLoadBalance.NAME)
public interface LoadBalance {
@Adaptive("loadbalance")
<T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException;
}
随机均衡算法
public class RandomLoadBalance extends AbstractLoadBalance {
public static final String NAME = "random";
private final Random random = new Random();
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
//provider 的数量
int length = invokers.size();
int totalWeight = 0;
boolean sameWeight = true;
for (int i = 0; i < length; i++) {
int weight = getWeight(invokers.get(i), invocation);
totalWeight += weight;
if (sameWeight && i > 0
&& weight != getWeight(invokers.get(i - 1), invocation)) {
sameWeight = false;
}
}
if (totalWeight > 0 && !sameWeight) {
int offset = random.nextInt(totalWeight);
for (int i = 0; i < length; i++) {
offset -= getWeight(invokers.get(i), invocation);
if (offset < 0) {
return invokers.get(i);
}
}
}
return invokers.get(random.nextInt(length));
}
}