• 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);

      

  • 相关阅读:
    CF446C [DZY loves Fibonacci]
    [BZOJ2286] 消耗战
    [CF Round #278] Tourists
    BZOJ2553 [BJWC2011]禁忌
    NOI2018D2T1 屠龙勇士
    BZOJ2333 棘手的操作
    bzoj4196: [Noi2015]软件包管理器(树链剖分)
    bzoj1833: [ZJOI2010]count 数字计数(数位DP)
    bzoj1026: [SCOI2009]windy数(数位DP)
    bzoj3631: [JLOI2014]松鼠的新家(树上差分)
  • 原文地址:https://www.cnblogs.com/fqfanqi/p/9932102.html
Copyright © 2020-2023  润新知