简介
2、Ribbon(+ RestTemplate)
Ribbon+RestTemplate,组合使用刚好可以完成微服务的调用,并且实现内置的负载均衡。
-
优点:
-
跨域通过服务名称进行远程访问
-
可以做负载均衡,服务中心访问资源的时候做负载均衡
-
-
缺点:
-
负载均衡的配置策略写在了 Controller层,而不是在实现层,不合适
-
虽然是通过服务名称访问,但是是通过 RestTemplate 去访问的,所以 url 还是写死的,应该把服务名称这一段可重复拼接的地址抽离出去
-
2.1、客户端进行服务调用
2.1.1、pom.xml
在 spring-cloud-starter-netflix-eureka-client 这个依赖中,已经默认包含了 Ribbon 的相关依赖。
2.1.2、application.yml
server: port: 9002 spring: application: # 注册到服务中心后,当前微服务的名称(serviceID) name: client2 eureka: client: service-url: # 指定服务端的地址 defaultZone: http://localhost:8001/eureka instance: # 设置当前微服务在服务中心中的节点名称为 ip:port prefer-ip-address: true instance-id: ${spring.cloud.client.ip-address}:${server.port}
2.1.3、DemoApplication
-
注解 @EnableDiscoveryClient:要先发现服务后,才能去调用该服务
-
注解 @Bean:让Spring管理一个RestTemplate对象
-
注解 @LoadBalanced:表明这里需要负载均衡相关的功能支持
@EnableDiscoveryClient @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } // 这段其实是应该写在一个单独的配置类中 @Bean @LoadBalanced public RestTemplate restTemplate() {return new RestTemplate();} }
2.1.4、ConsumerController
使用 restTemplete给一个指定的 URL发送 get请求,其中 client1是客户端1在注册中心的服务名称 ServiceID。hello 是 Controller 中暴露出的 API接口。这样的话,即使客户端1的端口一直改变,但是只要服务名称不变,就可以通过注册中心找到然后进行使用。
@RestController public class ConsumerController { @Resource private RestTemplate restTemplete; @GetMapping("/consumer") public String consumber() { return restTemplete .getForObject("http://client1/hello?name=tom",String.class); } }