sumer,相较于之前pom.xml,我们新增了spring-cloud-starter-ribbon
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
- 创建完pom.xml,在ribbon-consumer 启动类加上
@EnableDiscoveryClient
注解,让该注解注册为Eureka客户端,以获得服务发现的能力,同时,创建RestTemplate
对象,加上@LoadBalance
注解开启负载均衡。
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
}
- 在src目录下新建一个
RibbonController
类,注入@RestTemplate
,构造一个方法来调用server-provider
中的/hello 方法。代码如下
@RestController
public class RibbonController {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/ribbon-consumer",method = RequestMethod.GET)
public String helloConsumer(){
return restTemplate.getForEntity("http://server-provider/hello",String.class).getBody();
}
}
在helloConsumer方法上面采用Restful 风格的编码方式,这个方法远程调用了server-provider
中的hello方法,在这里不像是http://ip:端口号这种书写方式,而是直接采用 服务名/方法名来直接调用方法,因为你不知道具体的方法在哪个ip的机器上,需要由Eureka进行调用,这样消费者就不用关心由谁提供了服务,只要提供了服务即可,这也是面向对象方法的一种体现,同时也能很好的解耦。
- 在
application.properties
配置如下
spring.application.name=ribbon-consumer
server.port=9000
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/
因为ribbon-consumer需要由客户端来主动调用方法,所以需要提供实例名称,端口号,并在注册中心注册ribbon-consumer服务
- 启动服务,访问Eureka主页发现Ribbon-consumer的服务也注册进来了。
INFO 29397 --- [nio-9000-exec-1] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client server-provider initialized: DynamicServerListLoa