美文网首页
Spring Cloud之RestTemplate 详解

Spring Cloud之RestTemplate 详解

作者: 巨子联盟 | 来源:发表于2017-12-09 18:05 被阅读0次
  • 什么是客户端负载均衡

我们一般讲的负载均衡都是服务端的负载均衡,比如硬件负载均衡F5,软件负载均衡 Nginx. 什么是客户端的负载均衡呢?和服务端负载均衡的最大不同,是维护自己要访问的服务端清单所存储的位置
RibbonEurekaAutoConfiguration

  • 利用Ribbon实现负载均衡的步骤

  1. 服务提供者启动多个服务实例
  2. 服务消费者调用被@LoadBalanced注解过的RestTemplate
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
  • RestTemplate 用法详解

  1. GET请求

  • getForEntity

   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value="/ribbon-consumer1",method = RequestMethod.GET)
   public String helloConsumer1() {
       return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody();
   }
  • getForObject

    @RequestMapping(value="/getUser",method = RequestMethod.GET)
    public User getUser() {
        ResponseEntity<User> responseEntity= restTemplate.getForEntity("http://HELLO-SERVICE/getUser", User.class);
        User body = responseEntity.getBody();
        return body;
    }

有参数传递

    @RequestMapping(value="/getUserObject",method = RequestMethod.GET)
    public User getUserObject() {
        User responseEntity= restTemplate.getForObject("http://HELLO-SERVICE/getUser?name={1}", User.class,"zzj");
        return responseEntity;
    }

通过Map对象封装参数

    @RequestMapping(value="/getUserByMap",method = RequestMethod.GET)
    public User getUserByMap() {
        Map<String,String> map =new HashMap<>();
        map.put("name", "zzj");
        User responseEntity= restTemplate.getForObject("http://HELLO-SERVICE/getUser?name={name}", User.class,map);
        return responseEntity;
    }
  1. POST请求

POST和GET一样,有postForEntity和postForObject方法,参数大致相同

    @RequestMapping(value="/user",method = RequestMethod.POST)
    public boolean save() {
        User user = new User();
        user.setName("abc");
        user.setAge(111);
        return restTemplate.postForObject("http://HELLO-SERVICE/user", user, boolean.class);
    }

postForLocation返回URI

  1. PUT请求

  2. DELETE请求

  3. exchange 方法

该方法返回的是一个 ResponseEntity<T>
其中有个参数是传入 HttpEntity,HttpEntity是对请求的封装,包含请求头header和请求体body.

相关文章

网友评论

      本文标题:Spring Cloud之RestTemplate 详解

      本文链接:https://www.haomeiwen.com/subject/cavrixtx.html