Dubbo入门案例(一)
Dubbo入门案例(二)
Dubbo入门案例(三)
Dubbo入门案例(四)
Dubbo入门案例(五)
Dubbo入门案例(六)
Dubbo入门案例(七)
Dubbo入门案例(八)
在集群负载均衡时,Dubbo 提供了多种均衡策略,缺省为 random 随机调用。
① 负载均衡策略
LoadBalance 中文意思为负载均衡,它的职责是将网络请求,或者其他形式的负载“均摊”到不同的机器上。避免集群中部分服务器压力过大,而另一些服务器比较空闲的情况。通过负载均衡,可以让每台服务器获取到适合自己处理能力的负载。在为高负载服务器分流的同时,还可以避免资源浪费,一举两得。负载均衡可分为软件负载均衡和硬件负载均衡。在我们日常开发中,一般很难接触到硬件负载均衡。但软件负载均衡还是可以接触到的,比如 Nginx。在 Dubbo 中,也有负载均衡的概念和相应的实现。Dubbo 需要对服务消费者的调用请求进行分配,避免少数服务提供者负载过大。服务提供者负载过大,会导致部分请求超时。因此将负载均衡到每个服务提供者上,是非常必要的。
② Dubbo 提供了4种负载均衡实现
分别是基于权重随机算法的 RandomLoadBalance、
基于最少活跃调用数算法的 LeastActiveLoadBalance、
基于 hash 一致性的 ConsistentHashLoadBalance,
以及基于加权轮询算法的 RoundRobinLoadBalance
8.2.1 代码演示,随机算法
修改 dubbo提供者,pom配置文件tomcat的端口,applicationContext-service.xml配置文件中dubbo端口,修改sayHello方法return 返回值 数字。运行提供者,然后在运行消费者。会发现,dubbo默认使用的是随机算法。
8.2.2 代码演示,轮询算法
修改消费者@Reference 注解
package com.maweiqi.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.maweiqi.service.HelloService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* HelloController
*
* @Author: 马伟奇
* @CreateTime: 2019-07-19
* @Description:
*/
@Controller
@RequestMapping("/demo")
public class HelloController {
@Reference(loadbalance = "roundrobin")
private HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String getName(String name){
//远程调用
String result = helloService.sayHello(name);
System.out.println(result);
return result;
}
}
直接运行测试:
启动三个提供者,一个消费者
8.2.3 代码演示,权重算法
package com.maweiqi.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.maweiqi.service.HelloService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* HelloController
*
* @Author: 马伟奇
* @CreateTime: 2019-07-19
* @Description:
*/
@Controller
@RequestMapping("/demo")
public class HelloController {
@Reference(loadbalance = "random")
private HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String getName(String name){
//远程调用
String result = helloService.sayHello(name);
System.out.println(result);
return result;
}
}
进入管理控制台,修改权重
访问http://localhost:8080/dubbo-admin-2.6.0/

直接运行测试:
启动三个提供者,一个消费者
网友评论