zoukankan      html  css  js  c++  java
  • SpringCloud--Ribbon负载均衡

    Ribbon实现客户端负载均衡

    负载均衡:是对系统的高可用、网络压力的缓解和处理能力扩容的重要手段之一。

    硬件负载均衡:主要通过在服务器节点之间安装专门用于负载均衡的设备;

    软件负载均衡:通过在服务器上安装一些具有均衡负载功能或模块的软件来完成请求分发工作,比如Nginx。

     

    客户端负载均衡和服务端负载均衡最大的不同点在于上面所提到的服务清单所存储的位置。在客户端负载均衡中,所有客户端节点都维护着自己要访问的服务端清单,这些服务端的清单来自于服务注册中心。

    通过Spring Cloud Ribbon的封装,在微服务架构中使用客户端负载均衡调用需要如下二步:

      1)服务提供者只需要启动多个服务实例并注册待一个注册中心或多个相关联的服务注册中心;

      2)服务消费者直接通过调用被@LoadBalanced注解修饰过的RestTemplate来实现面向服务的接口调用。

    RestTemplate详解

    Get请求:在RestTemplate中,对get请求可以通过如下两个方法进行调用实现

      1)getForEntity函数:

        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://USER_SERVICE/user?name={1}",String.class,"change1");

        String body = responseEntity.getBody();

        备注:最后一个参数“change1”会替换url中的{1}占位符;返回的ResponseEntity对象中的body内容类型会根据第二个参数转换为String类型。如果希望返回某个Object类型,则传Object.class。

      2)getForObject函数:对getForEntity的进一步封装,它通过HttpMessageConverterExtractor对HTTP的请求响应body内容进行对象转换,实现请求直接返回包装好的对象内容

        RestTemplate restTemplate = new RestTemplate();

        String result = restTemplate.getForObject(url,String.class);

        备注:result为body内容,String.class类型,如果body是一个User对象,则可以这样User result = restTemplate.getForObject(url,User.class);

    POST请求:在RestTemplate中,对post请求可以通过如下三个方法进行调用实现

      1)postForEntity函数:

        RestTemplate restTemplate = new RestTemplate();

        User user = new User("didi",30);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://USER_SERVICE/user",user,String.class);

        String body = responseRntity.getBody();

        备注:user为提交的body内容,String.class为请求响应返回的bod类型。

      2)postForObject函数:

        RestTemplate restTemplate = new RestTemplate();

        User user = new User("didi",30);

        String postResult = restTemplate.postForObject("http://USER_SERVICE/user",user,String.class);

      3)postForLocation函数:返回新资源的URI

        RestTemplate restTemplate = new RestTemplate();

        User user = new User("didi",30);

        URI responseURI = restTemplate.postForLocation("http://USER_SERVICE/user",user);

    PUT请求:在RestTemplate中,对put请求可以通过put方法进行调用实现

      RestTemplate restTemplate = new RestTemplate();

      Long id = 10001L;

      User user = new User("didi",40);

      restTemplate.put("http://USER_SERVICE/user/{1}",user,id);

    DELETE请求:在RestTemplate中,对DELETE请求可以通过delete方法进行调用实现 

      RestTemplate restTemplate = new RestTemplate();

      Long id = 10001L;

      restTemplate.delete("http://USER_SERVICE/user/{1}",user,id);

      

  • 相关阅读:
    正则表达式例子
    addevent兼容函数 && 阻止默认行为 && 阻止传播
    addevent
    区分总结innerHeight与clientHeight、innerWidth与clientWidth、scrollLeft与pageXOffset等属性
    setattribute兼容
    随机分配位置
    浏览器类型
    统计一个字符串中相同字符的个数
    Appium发送中文或其他语言的问题
    Appium同时连接多台手机进行测试(多线程)
  • 原文地址:https://www.cnblogs.com/fqfanqi/p/9932102.html
Copyright © 2011-2022 走看看