Spring Cloud 是基于 Netflix Ribbon 开发公司实现的一套客户端负载开发公司均衡的工具;开发公司提供客户端的软件负载开发公司均衡算法和服务调用;
Ribbon开发公司工作时分两步:
开发公司第一步先选择 EurekaServer(或者nacos),开发公司它优先选择在同一个区域内负载较少的 server;
第二步再根据用户指定的策略,在从 server 取到的服务注册列表中选择一个地址;
一、Ribbon 核心组件
引入 Ribbon:
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
- </dependency>
IRule 定义了负载均衡的方式:
二、Ribbon 交互的三种级别层次
a)Spring DiscoveryClient:提供了对 Ribbon 和 Ribbon 中缓存的注册服务的最低层次访问;
b)启用了 RestTemplate 的 Spring DiscoveryClient;
c) Feign 客户端;
注册中心必不可少,在主程序类上添加注解
@EnableDiscoveryClient:表明可以被注册中心发现。是 Sring Cloud 的触发器,其作用是使应用程序能够使用 DiscoveryClient 和 Ribbon 库;
2.1、使用 DiscoveryClient 查找信息
- @Component
- public class ProviderDiscoveryClient {
-
- //自动注入 DiscoveryClient 类,该类用于与 Ribbon 交互
- @Autowired
- private DiscoveryClient discoveryClient;
-
- public Provide getProvide(String providerId) {
- RestTemplate restTemplate = new RestTemplate();
- //获取服务提供者的所有实例列表,ServiceInstance 用于保存关于服务的特定实例(包括主机名、端口荷 URL)
- List<ServiceInstance> instances = discoveryClient.getInstances("provider-instance-name");
-
- if (instances.size()==0) return null;
- //检索要调用的服务端点
- String serviceUri = String.format("%s/providers/%s",instances.get(0).getUri().toString(), providerId);
-
- //使用标准的 Spring REST 模板类去调用服务
- ResponseEntity< provider > restExchange =
- restTemplate.exchange(
- serviceUri,
- HttpMethod.GET,
- null, Provider.class, providerId);
-
- return restExchange.getBody();
- }
- }
2.2、使用带有 Ribbon 功能的 Spring RestTemplate 调用服务
需要对 RestTemplate 类用 @LoadBalanced 注解显示声明;
- @SpringBootApplication //只需要这个注解即可
- public class Application {
- @LoadBalanced //告诉 Spring Cloud 创建一个支持 Ribbon 的 RestTemplate
- @Bean
- public RestTemplate getRestTemplate(){
- return new RestTemplate();
- }
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
- }
使用 Ribbon 的 RestTemplate 来调用服务:
- @Component
- public class ProviderRestTemplateClient {
- //自动注入即可,不用实例化
- @Autowired
- RestTemplate restTemplate;
-
- public Provider getProvider(String providerId){
- ResponseEntity<Provider> restExchange =
- restTemplate.exchange(
- //使用 Eureka 服务 ID 来构建目标 URL
- "http://provider-instance-name/providers/{providerId}",
- HttpMethod.GET,
- null, Provider.class, providerId);
- return restExchange.getBody();
- }
- }
2.3、使用 Netflix Feign 客户端调用服务
引入:
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
在主程序类上添加注解 @EnableFeignClients:表示启用 Feign 客户端;
定义用于调用服务提供者的 Feign 接口
- @FeignClient("provider-instance-name") //标识服务为 feign 的客户端
- public interface ProviderFeignClient {
- //定义端点的路径和动作
- @RequestMapping(
- method= RequestMethod.GET,
- value="/providers/{providerId}",
- consumes="application/json")
- //定义传入端点的参数,该方法可以由客户端调用以触发组织服务
- Provider getProvider(@PathVariable("providerId") String providerId);
- }
要是用 ProviderFeignClient 类,开发人员只需要自动装配并使用它即可。
转自:https://www.cnblogs.com/dlhjw/p/15845348.html