介绍
- 是一个基于http/tcp的客户端负载均衡工具,基于Netflix Ribbon实现
- 可以将面向服务的REST模板请求自动转换为客户端负载均衡的调用
- 服务发现由Eureka的客户端完成,服务消费由Ribbon完成
使用步骤
- 服务提供者启动多个服务实例注册到同一个注册中心或者相互关联的注册中心
- 服务消费者直接通过调用被@LoadBalanced注释修饰过的RestTemplate来实现面向服务的调用(创建一个消费者)
RestTemplate详解
- GET请求
- 有两种方式getForEntity和getForObject,当不需要关注body时,可以通过第二种方式直接获取响应内容
- 示例:请求HELLO-SERVICE服务的/get接口,请求参数是message=“billy”,返回类型为String
ResponseEntity<String> responseEntity = restTemplate.getForEntity(
"http://HELLO-SERVICE/get?message={1}", String.class, "billy");
logger.info("GET:{}", responseEntity.getBody());
Object responseBody = restTemplate.getForObject(
"http://HELLO-SERVICE/get?message={1}", String.class, "billy");
logger.info("GET:{}", responseBody.toString());
- POST请求
- 有三种方式,postForEntity,postForObject和postForLocation
- 示例:请求HELLO-SERVICE服务的/post接口,请求参数是一个对象,返回类型为String
ResponseEntity<String> postForEntity = restTemplate.postForEntity(
"http://HELLO-SERVICE/post", new User("billy", 24), String.class);
logger.info("POST:{}", postForEntity.getBody());
Object responseBody = restTemplate.postForObject(
"http://HELLO-SERVICE/post", new User("billy", 24), String.class);
logger.info("POST:{}", responseBody);
- 注意:如果请求参数是对象,服务提供者的接口列表需要用@RequestBody,否则接收到的字段值为null
- PUT请求
- 返回viod,所以不需要指定responseType
- 增加一个用户
restTemplate.put("http://HELLO-SERVICE/put", new User("billy", 24));
- DELETE请求
restTemplate.delete("http://HELLO-SERVICE/delete/{1}", id);
拓展Ribbon简单配置
下一篇服务容错保护Spring Cloud Hystrix