乐趣区

关于java:SpringCloud梳理ribbon

1.ribbon 服务消费者

ribbon 提供了负载平衡和重试的性能

1.1 负载平衡

1. 从 eureka 取得地址表
2. 应用多个地址来回调用
3. 拿到一个地址, 应用 RestTemplate 执行近程调用

增加负载平衡

1. 增加 ribbon 依赖(eureka client 中曾经蕴含, 不要反复增加)
2. 增加 @LoadBalance 注解, 对 RestTemplate 进行加强
3. 用 RestTemplate 调用的地址, 改成 service-id(注册核心注册的服务名) rt.getForObject(“http://item-service/{1}”, ……)

1.2ribbon 重试

一种容错形式, 调用近程服务失败 (异样, 超时) 时, 能够主动进行重试调用.

增加重试

1. 增加 spring-retry 依赖
2. 配置重试参数
MaxAutoRtries- 单台服务器的重试次数
MaxAutoRtriesNextServer – 更换服务器的次数
OkToRetryOnAllOperations – 是否对所有类型申请都进行重试,默认只对 get 重试
ConnectTimeout – 和近程服务建设连贯的期待超时时长
ReadTimeout – 建设连贯并发送申请后,期待响应的超时时长
留神: 两个超时时长不能再配置文件中设置, 而是在 java 代码中设置.

2. 代码演示

2.1 新建 ribbon 我的项目


2.2 增加依赖

eureka-client 中曾经蕴含 ribbon 依赖
须要增加 sp01-commons 依赖
<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.tedu</groupId>
    <artifactId>springcloud-012-ribbon</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springcloud-012-ribbon</name>
    <description>Demo project for Spring Cloud</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <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>
        <dependency>
            <groupId>com.tedu</groupId>
            <artifactId>sp01-commons</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </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>

</project>

2.3 配置 application.yml 文件

spring:
  application:
    name: ribbon
    
server:
  port: 3001
  
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:2001/eureka

2.3 代码设置

创立 RestTemplate 实例
RestTemplate 是用来调用其余微服务的工具类, 封装了近程调用代码, 提供了一组用于近程调用的模板办法, 例如:getForObject() postForObject()等

2.3.1 启动类设置

package com.tedu.sp06;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@SpringBootApplication
public class Sp06RibbonApplication {
    
    // 创立 RestTemplate 实例,并存入 spring 容器
    @Bean
    public RestTemplate getRestTemplate() {return new RestTemplate();
    }

    public static void main(String[] args) {SpringApplication.run(Sp06RibbonApplication.class, args);
    }

}

2.3.2 RibbonController

package com.tedu.sp06.consoller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.tedu.sp01.pojo.Item;
import com.tedu.sp01.pojo.Order;
import com.tedu.sp01.pojo.User;
import com.tedu.web.util.JsonResult;

@RestController
public class RibbonController {
    @Autowired
    private RestTemplate rt;
    
    @GetMapping("/item-service/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
        // 向指定微服务地址发送 get 申请,并取得该服务的返回后果 
        //{1} 占位符,用 orderId 填充
        return rt.getForObject("http://localhost:8001/{1}", JsonResult.class, orderId);
    }

    @PostMapping("/item-service/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {
        // 发送 post 申请
        return rt.postForObject("http://localhost:8001/decreaseNumber", items, JsonResult.class);
    }

    /
    
    @GetMapping("/user-service/{userId}")
    public JsonResult<User> getUser(@PathVariable Integer userId) {return rt.getForObject("http://localhost:8101/{1}", JsonResult.class, userId);
    }

    @GetMapping("/user-service/{userId}/score") 
    public JsonResult addScore(@PathVariable Integer userId, Integer score) {return rt.getForObject("http://localhost:8101/{1}/score?score={2}", JsonResult.class, userId, score);
    }
    
    /
    
    @GetMapping("/order-service/{orderId}")
    public JsonResult<Order> getOrder(@PathVariable String orderId) {return rt.getForObject("http://localhost:8201/{1}", JsonResult.class, orderId);
    }

    @GetMapping("/order-service")
    public JsonResult addOrder() {return rt.getForObject("http://localhost:8201/", JsonResult.class);
    }
}

2.4 启动服务, 并拜访测试

2.4.1 测试地址

http://eureka1:2001
http://localhost:3001/item-service/35
http://localhost:3001/user-service/7
http://localhost:3001/user-service/7/score?score=100
http://localhost:3001/order-service/123abc
http://localhost:3001/order-service/

3.ribbon 负载平衡引入

批改 sp06-ribbon 我的项目
1. 增加 ribbon 起步依赖(可选)
2.RestTemplate 设置 @LoadBanlance
3. 拜访门路批改为服务 id

3.1 增加 ribbon 起步依赖

eureka 依赖中曾经蕴含了 ribbon 依赖, 能够不增加.
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

3.2RestTemplate 增加 @LoadBalance 注解

@LoadBalance 负载平衡注解, 会对 RestTemplate 实例进行封装, 创立动静代理对象, 并切入 (AOP) 负载平衡代码, 把申请扩散散发到集群中的服务器中.
启动类批改
package com.tedu.sp06;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@SpringBootApplication
public class Sp06RibbonApplication {
    
    @LoadBalanced // 负载平衡注解
    @Bean
    public RestTemplate getRestTemplate() {return new RestTemplate();
    }

    public static void main(String[] args) {SpringApplication.run(Sp06RibbonApplication.class, args);
    }

}

3.3 拜访门路设置为服务 id

package com.tedu.sp06.consoller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.tedu.sp01.pojo.Item;
import com.tedu.sp01.pojo.Order;
import com.tedu.sp01.pojo.User;
import com.tedu.web.util.JsonResult;

@RestController
public class RibbonController {
    @Autowired
    private RestTemplate rt;
    
    @GetMapping("/item-service/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
        // 这里服务器门路用 service-id 代替,ribbon 会向服务的多台集群服务器散发申请
        return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);
    }

    @PostMapping("/item-service/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
    }

    /
    
    @GetMapping("/user-service/{userId}")
    public JsonResult<User> getUser(@PathVariable Integer userId) {return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
    }

    @GetMapping("/user-service/{userId}/score") 
    public JsonResult addScore(@PathVariable Integer userId, Integer score) {return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score);
    }
    
    /
    
    @GetMapping("/order-service/{orderId}")
    public JsonResult<Order> getOrder(@PathVariable String orderId) {return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
    }

    @GetMapping("/order-service")
    public JsonResult addOrder() {return rt.getForObject("http://order-service/", JsonResult.class);
    }
}

3.4 拜访测试

http://localhost:3001/item-service/34

4.ribbon 重试引入

4.1 增加依赖 pom.xml 增加 spring-retry 依赖

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>

4.2application.yml 文件配置 ribbon 重试

spring:
  application:
    name: ribbon
    
server:
  port: 3001
  
eureka:
  client:    
    service-url:
      defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
      
ribbon:
  MaxAutoRetriesNextServer: 2
  MaxAutoRetries: 1
  OkToRetryOnAllOperations: true

4.3 主启动类 ### 设置 RestTemplate 的申请工厂的超时属性

package com.tedu.sp06;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@SpringBootApplication
public class Sp06RibbonApplication {

    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate() {SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
        f.setConnectTimeout(1000);
        f.setReadTimeout(1000);
        return new RestTemplate(f);
        
        //RestTemplate 中默认的 Factory 实例中,两个超时属性默认是 -1,// 未启用超时,也不会触发重试
        //return new RestTemplate();}

    public static void main(String[] args) {SpringApplication.run(Sp06RibbonApplication.class, args);
    }

}

4.4item-service 的 ItemController 增加提早代码,以便测试 ribbon 的重试机制

package com.tedu.sp02.item.controller;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.tedu.sp01.pojo.Item;
import com.tedu.sp01.service.ItemService;
import com.tedu.web.util.JsonResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class ItemController {
    @Autowired
    private ItemService itemService;
    
    @Value("${server.port}")
    private int port;
    
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws Exception {log.info("server.port="+port+", orderId="+orderId);

        ///-- 设置随机提早
        long t = new Random().nextInt(5000);
        if(Math.random()<0.6) {log.info("item-service-"+port+"- 暂停"+t);
            Thread.sleep(t);
        }
        ///~~
        
        List<Item> items = itemService.getItems(orderId);
        return JsonResult.ok(items).msg("port="+port);
    }
    
    @PostMapping("/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {itemService.decreaseNumbers(items);
        return JsonResult.ok();}
}

拜访测试重启机制

http://localhost:3001/item-service/35

ribbon 的重试机制,在 feign 和 zuul 中进一步进行了封装,后续能够应用 feign 或 zuul 的重试机制

退出移动版