博客
关于我
Spring Cloud Ribbon
阅读量:676 次
发布时间: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/

    你可能感兴趣的文章
    MySQL 常见的 9 种优化方法
    查看>>
    MySQL 常见的开放性问题
    查看>>
    Mysql 常见错误
    查看>>
    mysql 常见问题
    查看>>
    MYSQL 幻读(Phantom Problem)不可重复读
    查看>>
    mysql 往字段后面加字符串
    查看>>
    mysql 快照读 幻读_innodb当前读 与 快照读 and rr级别是否真正避免了幻读
    查看>>
    MySQL 快速创建千万级测试数据
    查看>>
    mysql 快速自增假数据, 新增假数据,mysql自增假数据
    查看>>
    MySql 手动执行主从备份
    查看>>
    Mysql 批量修改四种方式效率对比(一)
    查看>>
    mysql 批量插入
    查看>>
    Mysql 报错 Field 'id' doesn't have a default value
    查看>>
    MySQL 报错:Duplicate entry 'xxx' for key 'UNIQ_XXXX'
    查看>>
    Mysql 拼接多个字段作为查询条件查询方法
    查看>>
    mysql 排序id_mysql如何按特定id排序
    查看>>
    Mysql 提示:Communication link failure
    查看>>
    mysql 插入是否成功_PDO mysql:如何知道插入是否成功
    查看>>
    Mysql 数据库InnoDB存储引擎中主要组件的刷新清理条件:脏页、RedoLog重做日志、Insert Buffer或ChangeBuffer、Undo Log
    查看>>
    mysql 数据库中 count(*),count(1),count(列名)区别和效率问题
    查看>>