在上一篇中提到了路由网关spring-cloud-zuul,其主要介于外部服务调用者和微服务集群之间,提供了反向代理,负载均衡,拦截器等多种功能,适合于向外界提供微服务接口功能。就好比我们自己公司有多个微服务,这时有个其他公司需要调用我们的微服务接口,这时就可以使用zuul,而如果我们自己公司的这几个微服务之间需要互相调用服务接口的话,可以使用ribbon+restTemplate或feign来实现。
这里继续使用上一篇中的项目来扩展。用到的项目如下:
1.SpringCloudConfig
2.SpringCloudServiceCenter
3.SpringCloudServiceI
4.SpringCloudServiceII
5.SpringCloudServiceIII
一共一个配置中心,一个注册中心,3个微服务生产者(其中I和III的service id相同)
代码下载
一.ribbon+restTemplate
Ribbon是Netflix发布的负载均衡器,在与Eureka结合使用时,在配置完服务提供地址后,Ribbon就能根据配置的srevice id,到Eureka注册中心获取到该service id的所有实际地址,然后根据配置的负载均衡算法进行负载均衡。
新建SpringCloudCustomerI项目,作为服务消费者I
(1)pom.xml配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
(2)application.properties配置
这里我就不在路径前加项目名了
#server.servlet.context-path=/myCustomerI
server.port=8770
spring.application.name=myCustomerI
eureka.client.service-url.defautZone=http://serviceCenter:8761/eureka/
(3)启动项SpringCloundCustomerIApplication.java
@LoadBalanced
轮询方式。
package com.m