Spring Cloud(二)服务消费者(Rest+Ribbon)

一、 Ribbon简介

Spring Cloud有两种微服务调用方式:

  1. ribbon+restTemplate (本文将介绍这种方式)
  2. feign

Spring Cloud Ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为,它是基于Netflix Ribbon实现的。Feign默认集成了ribbon。
RestTemplate是Spring自己提供的对象,用于发送Http请求。

服务端负载均衡和客户端负载均衡

首先,负载均衡分为硬件负载均衡和软件负载均衡两种,这里只说软件负载均衡。

软件负载均衡中又分为两种,即服务端负载均衡客户端负载均衡。无论是那种负载均衡,都是需要维护一个服务的清单,并通过心跳机制来定期清理那些故障的服务断点。服务端负载均衡和客户端负载均衡的却别在于其所维护的服务清单所存储的位置不同,一个在服务端一个在客户端。

在spring cloud ribbon中使用客户端负载均衡只需要完成以下两个步骤:

  1. 服务的提供者只需要启动多个服务的实例,并将实例注册到一个注册中心或者注册到多个相互关联的注册中心中
  2. 服务的消费者直接调用被@LoadBalanced注解修饰过的RestTemplate来实现面向服务的接口调用。

二、 简单实例

2.1 新建ribbon-consumer model

pom文件中添加netflix-ribbon依赖,同样也是Euraka Client,需要注册到Euraka Server中

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
2.2 修改springboot启动类

SpringBoot启动类添加EnableEurekaClien注解,并注册RestTemplate Bean,并添加LoadBalanced注解。

@SpringBootApplication
@EnableEurekaClient
public class RibbonConsumerApplication {

	public static void main(String[] args) {
		SpringApplication.run(RibbonConsumerApplication.class, args);
	}
	
	@Bean
	@LoadBalanced
	RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

2.3 资源文件

指定端口,指定Euraka地址

server.port=8083
spring.application.name=ribbon-consumer
eureka.client.service-url.defaultZone = http://localhost:8080/eureka/
2.4 添加service请求相关API

添加service 请求Rest API,案例是请求上一节中的eureka-client中的hello API。

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    public String hiService() {
        return restTemplate.getForObject("http://eureka-client/hello",String.class);
    }
}
2.5 添加controller
@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping(value = "/hi")
    public String hi() {
        return helloService.hiService();
    }
}

代码就大致这么多

三、 Demo

3.1 启动Euraka Service
3.2 启动Euraka Client
  1. 设置8081端口启动
  2. 设置8082端口启动

这样简单模拟一个集群环境。

附:如何在IDEA启动多个Spring Boot工程实例
Spring Cloud(二)服务消费者(Rest+Ribbon)
Spring Cloud(二)服务消费者(Rest+Ribbon)

取消选中复选框之后,改配置文件端口,再次run springboot启动类。

3.3 启动我们刚新建的 ribbon-consumer

浏览器访问我们刚新建的API。
http://localhost:8083/hi
当我们多次访问,浏览器交替显示:

hi ,i am from port:8081
hi ,i am from port:8082

这说明当我们通过调用restTemplate.getForObject(“http://eureka-client/hello”,String.class);方法时,已经做了负载均衡,访问了不同的端口的服务实例。

四、 流程图

Spring Cloud(二)服务消费者(Rest+Ribbon)

GitHub项目地址:https://github.com/PayneYu/spring-cloud-study