转自:https://www.jianshu.com/p/562045489d9d

4.1使用LoadBalancerClient

在Spring Cloud Commons中提供了大量的与服务治理相关的抽象接口,包括DiscoveryClient、LoadBalancerClient等。从LoadBalancerClient接口的命名中,可以看出这是一个负载均衡客户端的抽象定义,下面笔者将使用Spring Cloud提供的负载均衡器客户端接口来实现服务的消费。

首先,将利用上一篇中构建的eureka-server作为服务注册中心、provider-test作为服务提供者为基础。

  • 创建一个叫voyer-consumer-test的Spring Boot项目,引入相关maven包。
<?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.voyer</groupId>
<artifactId>voyer-consumer-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>voyer-consumer-test</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.M9</spring-cloud.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> <repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories> </project>
  • 然后配置application.yml,指定服务注册中心地址、端口号以及名称
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: consumer-test
  • 在默认的启动程序中注入RestTemplate
@SpringBootApplication
public class VoyerConsumerTestApplication { public static void main(String[] args) {
SpringApplication.run(VoyerConsumerTestApplication.class, args);
} @Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
  • 创建com.voyer.web包路径,创建ConsumerController,并注入 LoadBalancerClientRestTemplate,并在/hi接口的实现中,先通过loadBalancerClientchoose函数来负载均衡的选出一个provider-test的服务实例,这个服务实例的基本信息存储在ServiceInstance中,然后通过这些对象中的信息拼接出访问/hi接口的详细地址,最后再利用RestTemplate对象实现对服务提供者接口的调用:
@RestController
public class ConsumerController {
@Autowired
LoadBalancerClient loadBalancerClient;
@Autowired
RestTemplate restTemplate; @RequestMapping("/hi")
public String hello(){
ServiceInstance serviceInstance = loadBalancerClient.choose("provider-test");
String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/hi";
System.out.println(url);
return restTemplate.getForObject(url, String.class);
}
}

访问http://localhost::8764/hi ,会发现每次访问的返回的信息会循环输出hello world! I am from 8763 和 hello world! I am from 8762

4.2使用Ribbon

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。它是一个基于HTTP和TCP的客户端负载均衡器。它可以通过在客户端中配置ribbonServerList来设置服务端列表去轮询访问以达到均衡负载的作用。
每个load balancer都是组件的一部分,这些组件协同工作,Spring Cloud通过使用RibbonClientConfiguration为每个指定的客户端创建一个新的套装,这包括ILoadBalancer、RestClient和ServerListFilter。

  • 创建一个叫voyer-consumer-ribbon的Spring Boot项目,(操作顺序同上)引入相关maven包
        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
  • 修改默认启动类。增加为@EnableEurekaClient注解(此处为什么不用@EnableDiscoveryClient,读者可以百度一下这两者的区别),RestTemplate增加@LoadBalanced注解:
@SpringBootApplication
@EnableEurekaClient
public class VoyerConsumerRibbonApplication { public static void main(String[] args) {
SpringApplication.run(VoyerConsumerRibbonApplication.class, args);
} @Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
  • 修改配置文件application.yml
eureka:
client:
registerWithEureka: false
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8765
spring:
application:
name: consumer-ribbon
  • 修改ConsumerController:
@RestController
public class ConsumerController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("/hi")
public String hello(){
return restTemplate.getForObject("http://PROVIDER-TEST/hi", String.class);
}
}

启动程序,然后访问http://localhost:8765,会发现

hello world! I am from 8762
hello world! I am from 8763

这两个循环出现。到此ribbon消费者成功。

4.3使用Feign

Feign是一个声明性的web服务客户端,它使编写web服务客户机变得更容易。使用Feign创建接口并对其进行注释。它有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插入式的编码器和解码器。Spring Cloud增加了对Spring MVC注释的支持,并支持在Spring Web中使用默认的HttpMessageConverters。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载平衡的http客户端。(来自有道翻译)
总结两点:1、Feign采用的是接口加注解;2、Feign 整合了ribbon

  • 创建一个叫voyer-consumer-feign的Spring Boot项目,(操作顺序同上)引入相关maven包
        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
  • 配置文件:registerWithEureka: false自身是消费者,不注册为服务提供者。
eureka:
client:
registerWithEureka: false
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8766
spring:
application:
name: consumer-feign
  • 默认启动类增加@EnableDiscoveryClient@EnableFeignClients注解:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class VoyerConsumerFeignApplication { public static void main(String[] args) {
SpringApplication.run(VoyerConsumerFeignApplication.class, args);
}
}
  • 创建service包路径,然后新建一个ConsumerService的接口,通过@ FeignClient(“服务名”),来指定调用哪个服务:
@FeignClient(value = "provider-test")
public interface ConsumerService {
@RequestMapping(value = "/hi",method = RequestMethod.GET)
String hiFromProvider();
}
  • 创建com.voyer.web包路径,创建ConsumerController:
@RestController
public class ConsumerController {
@Autowired
ConsumerService consumerService;
@RequestMapping(value = "/hi",method = RequestMethod.GET)
public String hi(){
return consumerService.hiFromProvider();
}
}

启动程序,然后访问http://localhost:8766,会发现

hello world! I am from 8762
hello world! I am from 8763

这两个循环出现。到此feign消费者成功。

服务消费(LoadBalancerClient、Ribbon、Feign)的更多相关文章

  1. Spring Boot + Spring Cloud 实现权限管理系统 后端篇(十九):服务消费(Ribbon、Feign)

    技术背景 上一篇教程中,我们利用Consul注册中心,实现了服务的注册和发现功能,这一篇我们来聊聊服务的调用.单体应用中,代码可以直接依赖,在代码中直接调用即可,但在微服务架构是分布式架构,服务都运行 ...

  2. 白话SpringCloud | 第四章:服务消费者(RestTemple+Ribbon+Feign)

    前言 上两章节,介绍了下关于注册中心-Eureka的使用及高可用的配置示例,本章节开始,来介绍下服务和服务之间如何进行服务调用的,同时会讲解下几种不同方式的服务调用. 一点知识 何为负载均衡 实现的方 ...

  3. 服务消费者(RestTemplate+Ribbon+feign)

    负载均衡 ​ spring cloud 体系中,我们知道服务之间的调用是通过http协议进行调用的.注册中心就是维护这些调用的服务的各个服务列表.在Spring中提供了RestTemplate,用于访 ...

  4. Spring Cloud 入门Eureka -Consumer服务消费(Ribbon)(二)

    前面一篇介绍了LoadBalancerClient来实现负载均衡, 这里介绍Spring cloud ribbon 1.ribbon Spring Cloud Ribbon 是一个基于Http和TCP ...

  5. 【一起学源码-微服务】Eureka+Ribbon+Feign阶段性总结

    前言 想说的话 这里已经梳理完Eureka.Ribbon.Feign三大组件的基本原理了,今天做一个总结,里面会有一个比较详细的调用关系流程图. 说明 原创不易,如若转载 请标明来源! 博客地址:一枝 ...

  6. 微服务 - 服务消费(六)Ribbon

    Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具.它是一个基于HTTP和TCP的客户端负载均衡器.它可以通过在客户端中配置ribbonServer ...

  7. 玩转Spring Cloud之服务注册发现(eureka)及负载均衡消费(ribbon、feign)

    如果说用Spring Boot+Spring MVC是开发单体应用(或单体服务)的利器,那么Spring Boot+Spring MVC+Spring Cloud将是开发分布式应用(快速构建微服务)的 ...

  8. Spring Cloud Alibaba基础教程:支持的几种服务消费方式(RestTemplate、WebClient、Feign)

    通过<Spring Cloud Alibaba基础教程:使用Nacos实现服务注册与发现>一文的学习,我们已经学会如何使用Nacos来实现服务的注册与发现,同时也介绍如何通过LoadBal ...

  9. spring cloud(服务消费者(利用ribbon实现服务消费及负载均衡)——初学二)

    Ribbon是一个基于HTTP和TCP客户端的负载均衡器,利用ribbon实现服务消费,并实现客户端的负载均衡. 一.准备工作(利用上一节的内容) 启动服务注册中心 启动computer-servic ...

  10. springcloud微服务实战:Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin

    相信现在已经有很多小伙伴已经或者准备使用springcloud微服务了,接下来为大家搭建一个微服务框架,后期可以自己进行扩展.会提供一个小案例: 服务提供者和服务消费者 ,消费者会调用提供者的服务,新 ...

随机推荐

  1. linux网络route

    一.网络基础知识: 设备端获取的IP路由表 [root@HKVS /] # route –n Kernel IP routing table Destination     Gateway       ...

  2. xtrabackup备份失败(error writing file 'UNOPENED')

    xtrabackup备份失败 解决了,是因为limit open files值设置太小了 (3)修改资源限制参数 vi /etc/security/limits.conf nproc:用户创建进程数限 ...

  3. ARC100E. Or Plus Max

    题目 好题.没想出解法. 官方题解: 这个解法和 Small Multiple 那道题的解法有异曲同工之妙. 扩展 若把 $\mathsf{or}$ 改成 $\mathsf{and}$ 或者 $\ma ...

  4. 【Java学习】类、对象、实例—类是对象的抽象,对象是类的实例

    类.对象.实例的关系是什么,如果不能很好的理解什么是类什么是对象就无法讲清楚, 类:某种事物与另一种事物具有相似性,比如哈士奇和泰迪,我们发现他们有一些相似的特性和行为,在生物学上,他们都属于“狗”, ...

  5. 用CTime类得到当前日期 时间

    (1)定义一个CTime类的对象CTime time: (2)得到当前时间time = CTime::GetCurrentTime(); (3)Get Year(),GetMonth(),GetDay ...

  6. 学习 Laravel - Web 开发实战入门笔记(1)

    本笔记根据 LearnKu 教程边学边记而成.该教程以搭建出一个类似微博的Web 应用为最终成果,在过程中学习 Laravel 的相关知识. 准备开发环境 原教程使用官方推荐的 Homestead 开 ...

  7. 树莓派驱动开发 helloworld

    编写Makefile ifneq ($(KERNELRELEASE),) obj-m := MiniX.o else KDIR := /home/hi/pi/kernel/linux/ all: ma ...

  8. 史上最全的MySQL高性能优化实战总结!

    1.1 前言 MySQL对于很多Linux从业者而言,是一个非常棘手的问题,多数情况都是因为对数据库出现问题的情况和处理思路不清晰.在进行MySQL的优化之前必须要了解的就是MySQL的查询过程,很多 ...

  9. Linq操作之Except,Distinct,Left Join 【转】

    最近项目中用到了Linq中Except,Distinct,Left Join这几个运算,这篇简单的记录一下这几种情形. Except      基础类型使用Linq的运算很简单,下面用来计算两个集合的 ...

  10. arcgis之隐藏设置放大缩小按钮

    arcgis之隐藏设置放大缩小按钮 隐藏按钮: view.ui._removeComponents(['zoom']) 设置按钮: let zoom = new Zoom({ view: this.v ...