SpringCloud 中使用 Ribbon

在前两章已经给大家讲解了Ribbon负载均衡的规则 以及 如何搭建Ribbon并调用服务,那么在这一章呢 将会给大家说一说如何在SpringCloud中去使用Ribbon。在搭建之前 我们需要做一些准备工作。

1. 搭建Eureka服务器:springCloud-ribbon-server(项目名称)
2. 服务提供者:springCloud-ribbon-police(项目名称)
3. 服务调用者:springCloud-ribbon-person(项目名称)

搭建Eureka服务器

配置 pom.xml,加入springCloud核心依赖、配置及eureka服务器依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.13.RELEASE</version>
</parent>
<dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Dalston.SR5</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>
<dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka-server</artifactId></dependency>
</dependencies>

配置 application.yml(红色部分是必须要写的,黑色部分不写也能正常运行 但是建议写上,在这里笔者将官网的代码贴上)

server:port: 8761
eureka:instance:hostname: localhostclient:registerWithEureka: false  禁止向eureka注册服务,因为它自己本身就是服务器fetchRegistry: false  这里不需要抓取注册表serviceUrl:defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

创建启动类:Application.java(将服务跑起来放着,稍后会用到)配置 pom.xml,加入springCloud核心依赖、配置及eureka服务依赖

@SpringBootApplication
@EnableEurekaServer
public class Application {public static void main(String[] args) {new SpringApplicationBuilder(Application.class).web(true).run(args);}}

服务提供者 

配置 pom.xml,加入springCloud核心依赖、配置及eureka客户端依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.13.RELEASE</version>
</parent>
<dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Dalston.SR5</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>
<dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka</artifactId></dependency>
</dependencies>

配置 application.yml(需要使用defaultZone向服务器注册服务,否则就算该服务运行起来了,但没有向服务器注册服务,也是使用不了的)(name 这个名称是显示在服务列表中的名称,养成好习惯,一定要起有意义的名称)

spring:application:name: springCloud-ribbon-police
eureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/

因为该服务是提供服务的,所以下面会建一个实体类及Controller用来对外提供服务,创建实体类:Police.java

public class Police {private String id;// 警察编号,用来保存用户输入的参数private String url;// 处理请求的服务器urlprivate String message;// 提示信息public String getId() {return id;}public void setId(String id) {this.id = id;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}

创建对外提供服务的Controller:PoliceController.java(@RestController注解中包含了@Controller+@ResponseBody)

@RestController
public class PoliceController {@RequestMapping(value="/getPolice", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)public Police getPolice(HttpServletRequest request){Police p = new Police();p.setUrl(request.getRequestURL().toString());p.setMessage("警察派出成功");return p;}@RequestMapping(value="/getPoliceById/{id}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)public Police getPolice(HttpServletRequest request, @PathVariable("id") String id){Police p = new Police();p.setId(id);p.setUrl(request.getRequestURL().toString());p.setMessage("指定警察派出成功");return p;}
}

因为我们要测试负载均衡,所以这里的服务提供者需要开启多个服务实例,下面我们用读取手动输入端口号的方法,启动多个服务实例,笔者在这里启动了两个服务实例:8080、8081

@SpringBootApplication
@EnableEurekaClient
public class PoliceApplication {public static void main(String[] args) {Scanner scan = new Scanner(System.in);String port = scan.nextLine();new SpringApplicationBuilder(PoliceApplication.class).properties("server.port="+port).run(args);}}

如下图,出现了两个服务实例,分别是:8080、8081,红色的信息咱们先不管他,如果实在有看着不顺眼的小伙伴,可以配置心跳(简单的来说,就是配置服务器每隔多久检查一次服务实例状态,如果某个服务因为某些原因停掉 不能用了,那么就将该服务 从服务列表中移除掉)

服务调用者

配置 pom.xml,加入springCloud核心依赖、配置及eureka客户端依赖、Ribbon依赖

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.13.RELEASE</version>
</parent>
<dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Dalston.SR5</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>
<dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-ribbon</artifactId></dependency>
</dependencies>

配置 application.yml(这里也将该服务注册到服务器,一定要进行注册)

server:port: 9090
spring:application:name: springCloud-ribbon-person
eureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/

创建调用服务Controller:PersonController.java

RestTemplate 是由 Spring Web 模块提供的工具类,与 SpringCloud 无关,是独立存在的

因 SpringCloud 对 RestTemplate 进行了一定的扩展,所以 RestTemplate 具备了负载均衡的功能

@RestController
@Configuration
public class PersonController {@Bean@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();}@RequestMapping("/getPolice")public String getPolice(){RestTemplate rt = getRestTemplate();String result = rt.getForObject("http://springCloud-ribbon-police/getPolice", String.class);return result;}@RequestMapping("/getPoliceById/{id}")public String getPoliceById(@PathVariable("id") String id){RestTemplate rt = getRestTemplate();String result = rt.getForObject("http://springCloud-ribbon-police/getPoliceById/"+id, String.class);return result;}}

创建启动类:PersonApplication.java

@SpringBootApplication
@EnableEurekaClient
public class PersonApplication {public static void main(String[] args) {new SpringApplicationBuilder(PersonApplication.class).web(true).run(args);}}

到目前为止,eureka服务器、服务提供者、服务调用者(负载均衡)就已经全写好了,下面我们访问接口,来试一下 服务到底能不能调通

我们分别调用:http://localhost:9090/getPolicehttp://localhost:9090/getPoliceById/100

上面是默认的轮询规则,8080、8081轮询去访问服务,,,那么下面说一下如何自定义规则,在上一章的 “Ribbon 负载均衡机制(自定义负载均衡规则)” 中有贴过自定义负载均衡的自定义规则类,在这里就不再重复的贴了,大家可以到文章中去看一下。

那么下面就直接说,既然Ribbon和SpringCloud一起使用了,在这里给大家说一下如何使用配置类或者配置文件进行配置。

下面直接用一个配置类,直接搞定。这样每当请求过来的时候,那么该请求就会走咱们配置的自定义规则类了

//name:建议写服务名称     configuration:配置类
//http://springCloud-ribbon-police/getPolice 调用"springCloud-ribbon-police"这个服务ID的时候,将会启用下面的配置
@RibbonClient(name="springCloud-ribbon-police", configuration=LbConfig.class)
public class LbConfig {@Beanpublic IRule getRule(){return new MyRule();}}

再说一下,如何使用配置文件进行配置:

格式是:服务ID >>> 命名空间 >>> 配置属性

springCloud-ribbon-police:ribbon:NFLoadBalancerRuleClassName: com.lpx.pro.utils.MyRule

以上两种配置方法都是有效的,,由此可以看出,我们配置的自定义规则起作用了。那么以上 就是本章讲解的全部内容,通过这个简单的例子,希望可以帮到大家,感谢大家的支持!

转载于:https://www.cnblogs.com/lpxdbk/p/9815324.html

SpringCloud 中使用 Ribbon(默认轮询规则 + 自定义规则)相关推荐

  1. 【详解】Ribbon 负载均衡服务调用原理及默认轮询负载均衡算法源码解析、手写

    Ribbon 负载均衡服务调用 一.什么是 Ribbon 二.LB负载均衡(Load Balancer)是什么 1.Ribbon 本地负载均衡客户端 VS Nginx 服务端负载均衡的区别 2.LB负 ...

  2. 3.springcloud中使用Ribbon和Feign调用服务以及服务的高可用

    1.消费者使用Ribbon组件负载均衡的调用服务者接口 在上一节中只介绍了如何将服务者和消费者注册到Eureka注册中心中,消费者并没有调用服务者,现在开始介绍,首先为了避免混淆,不再用上一节的消费者 ...

  3. 在verto_communicator中添加视频floor轮询功能

    只是实现了简单的视频轮询功能,还需要修改完善!!! 1.在src/partials/chat.html中添加 <div><p>{{num}}</p><butt ...

  4. 基于MThings配置MODBUS数据中常见的几种时间概念介绍(超时时间、间隔时间、轮询时间)

    超时时间: 主机使用,主机请求发出后,依据该时间判定从机回复的最大时间范围,超出该时间后,主机判定请求超时.如果超时时间设置过小,从机可能会在超时时间范围外才能回复请求,此时可能会导致总线中持续的报文 ...

  5. Node中的事件轮询机制

    文章目录 2 node中的事件循环模型 2-1 一些属性 2-2 循环模型 node事件循环总共有==六个阶段== process.nextTick()函数 __实例__ 2 node中的事件循环模型 ...

  6. ribbon 默认负载均衡 是什么_面试官:说说Ribbon是如何实现负载均衡的?

    你知道的越多,不知道的就越多,业余的像一棵小草! 你来,我们一起精进!你不来,我和你的竞争对手一起精进! 编辑:业余草 来源:blog.csdn.net/LO_YUN/article/details/ ...

  7. 深入biztalk消息以及消息订阅发布路由机制(四)-消息的轮询和执行

    一. 消息的轮询和执行 1.  轮询机制 消息路由到MessageBox数据库中,只是在数据库中写入了相关记录,表示哪个消息需要由哪个服务实例去执行,并没有付诸实施,还需要在进程中实实在在的去实例化这 ...

  8. round robin arbiter 轮询仲裁器设计

    前言 仲裁器Arbiter是数字设计中非常常见的模块,应用也非常广泛.定义就是当有两个或两个以上的模块需要占用同一个资源的时候,我们需要由仲裁器arbiter来决定哪一个模块来占有这个资源.一般来说, ...

  9. CP340/CP341基于ASCII驱动协议的多站点轮询

    西门子SIMATIC S7系列串行通信模块,包括CP340.CP341.CP440-1.CP441-1/2.CPU313C/314C-2PtP以及ET200S的1SI 3964/ASCII等,都支持A ...

  10. java定时轮询_RxJava应用场景之轮询定时任务

    Android开发中必不可少会遇到轮询或定时任务,在RxJava诞生之前,我们常常使用Handler+postDelay,或者Java中的Timer来实现,实际上RxJava也可以实现这类需求.下面, ...

最新文章

  1. live555 学习笔记
  2. 布道微服务_10注册中心与RPC框架的选型
  3. Docker知识1:Docker-hub简介
  4. 什么是nodejs呢?
  5. 打开高效文本编辑之门_Linux Sed模拟常见文件命令
  6. idea使用MybatisCodeHelperPro逆向生成
  7. rabbitmq实战_RabbitMQ 实战系列之:消息传递
  8. Oracle 获取本周、本月、本季、本年的第一天和最后一天
  9. 多媒体交互应用基础(11)
  10. 计算机网络资料篇(一)——HTTP
  11. RTP协议解析和H264码流提取
  12. C语言学习笔记(五):《C语言深度剖析》笔记
  13. 【一天一个C++小知识】003.C++中的void指针类型
  14. py 操作Mysql数据库
  15. python显示文字框_python如何使用文本框
  16. 网吧计费系统数据库修复/网吧收银系统数据库恢复
  17. 2022年最全Java面试题库基础篇
  18. C语言新手入门练习之三子棋
  19. 新手建站十大免费空间推荐-稳定,可用的免费空间及其使用体验
  20. 检测站营销系列文章:机动车检测站如何做精益营销?

热门文章

  1. 常用实例:js格式化手机号为3 4 4形式
  2. 法学界四大主流“数据权利与权属”观点
  3. [Android]使用Dagger 2依赖注入 - 自定义Scope(翻译)
  4. 使用cocoapods install友盟时报错Error installing UMengAnalytics
  5. Applese 涂颜色(欧拉降幂)
  6. ActiveMQ面试题
  7. smali注入常用代码
  8. NOIP模拟赛20161016R1
  9. 南阳acm-206-矩形的个数(水题)
  10. perl的bareword