博客
关于我
Spring Cloud Ribbon
阅读量:672 次
发布时间:2019-03-17

本文共 3684 字,大约阅读时间需要 12 分钟。

Ribbon 服务消费者

1.1 RestTemplate

Ribbon对RestTemplate进行了封装,提供负载均衡和重试功能。RestTemplate是Spring Boot提供的一个远程调用工具,可以执行GET和POST等请求。

RestTemplate 的方法

  • getForObject("url", 转换类型, 提交的参数)
  • `postForObject("url", 协议体数据, 转换类型)"

修改 sp06-ribbon 项目

  • 新建项目

    • 项目名称:sp06-ribbon
    • 依赖项:
      • spring-boot-starter-parent
      • spring-boot-starter-web
      • spring-cloud-starter-netflix-eureka-client
      • sp01-commons
  • application.yml

    spring:  application:    name: ribbon    server:      port: 3001  eureka:    client:      service-url:        defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
  • 主程序

    • 添加 @EnableDiscoveryClient 注解
    • 创建 RestTemplate 实例
  • 1.2 RibbonController

    @RestControllerpublic class RibbonController {    @Autowired    private RestTemplate rt;    @GetMapping("/item-service/{orderId}")    public JsonResult getItem(@PathVariable String orderId) {        return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);    }    @PostMapping("/item-service/decreaseNumber")    public JsonResult decreaseNumber(@RequestBody List
    items) { return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class); } @GetMapping("/user-service/{userId}") public JsonResult 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 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/", JsonResponse.class); }}

    1.3 启动服务并测试

    • 项目启动

      mvn spring-boot:run
    • 访问测试

      • http://eureka1:2001
      • http://localhost:3001/item-service/decreaseNumber
      • 使用 Postman Sending POST 请求,请求体为 [{"id":1, "name":"abc", "number":23},{"id":2, "name":"def", "number":11}]

    2.1 Ribbon 负载均衡

    修改项目

  • 添加 ripple 依赖

    org.springframework.cloud
    spring-cloud-starter-netflix-ribbon
  • 在主程序中加 @LoadBalanced 注解

  • 访问路径改为服务ID

  • 2.2 Ribbon 重试

  • 添加 retry 依赖

    org.springframework.retry
    spring-retry
  • 在 application.yml 配置重试参数

    spring:  application:    name: ribbon    server:      port: 3001  eureka:    client:      service-url:        defaultZone: http://eureka1:2001/eureka, http://eura2:2002/eureka      ribbon:        MaxAutoRetries: 1        MaxAutoRetriesNextServer: 2        OkToRetryOnAllOperations: true
  • 设置超时时间

    @Beanpublic RestTemplate getRestTemplate() {    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();    factory.setConnectTimeout(1000);    factory.setReadTimeout(1000);    return new RestTemplate(factory);}
  • 修改 ItemController 添加延迟

    @Slf4j@RestControllerpublic class ItemController {    @Autowired    private ItemService itemService;    @Value("${server.port}")    private int port;    @GetMapping("/{orderId}")    public JsonResult getItem(@PathVariable String orderId) throws Exception {        log.info("server.port = {}, orderId = {}", port, orderId);        if (Math.random() < 0.6) {            log.info("temp sleep: {}", new Random().nextInt(5000));            Thread.sleep(new Random().nextInt(5000));        }        List
    items = itemService.getItems(orderId); return JsonResult.ok(items); }}
  • 测试

    • 负载均衡测试
      • 同时访问 http://localhost:3001/item-service/decreaseNumber
    • 重试测试
      • ItemService 降低响应速度,测试Ribbon的自动重试能力

    转载地址:http://fxwhz.baihongyu.com/

    你可能感兴趣的文章
    [操作系统]内存连续分配管理方式
    查看>>
    C++ Primer Plus【复习笔记】-【复合类型】
    查看>>
    thinkphp 的一些重要知识点
    查看>>
    Python基础案例教程
    查看>>
    Java学习第二章——Java基本语句
    查看>>
    形状类似小于等于号的符号是啥
    查看>>
    C#中combox下拉框禁止键盘输入
    查看>>
    遇到问题之-yum update无法连接镜像问题解决
    查看>>
    遇到问题之-httpd服务启动报错182行错误
    查看>>
    pycharm如何设置(错误、警告类的标准提醒)
    查看>>
    Python3运行的时候错误:ModuleNotFoundError: No module named 'PIL'
    查看>>
    PHP是世界上最好的语言?Phython第一个不服
    查看>>
    Bugku CTF-web6
    查看>>
    Bugku CTF-web10 头等舱
    查看>>
    UML-配置图
    查看>>
    JS高级面向对象(二)-构造函数和原型
    查看>>
    python入门到秃顶(10):异常
    查看>>
    ES6_变量生明
    查看>>
    考研复试英语问答
    查看>>
    百度背景换肤案例
    查看>>