1、ribbon简介
微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。
A、ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。
B、ribbon 已经默认实现了这些配置bean:
IClientConfig ribbonClientConfig: DefaultClientConfigImpl
IRule ribbonRule: ZoneAvoidanceRule
IPing ribbonPing: NoOpPing
ServerList ribbonServerList: ConfigurationBasedServerList
ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter
ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer
2、ribbon负载均衡架构图
一个服务注册中心,eureka server,端口为8761
eureka-client工程跑了两个实例,端口分别为8762,8763,分别向服务注册中心注册
eureka-ribbon端口为8764,向服务注册中心注册
当eureka-ribbon通过restTemplate调用service-hello的hi接口时,因为用ribbon进行了负载均衡,会轮流的调用eureka-client:8762和8763 两个端口的hi接口;
3、搭建客户端服务eureka-client,端口号:8763
启动后,eureka-client在eureka-server注册了2个实例,这就相当于一个小的集群。
注意:eureka-client保持一样
访问localhost:8761如图所示:
4、搭建客户端消费者eureka-ribbon
A、导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
</dependencies>
B、application.yml
server:
port: 8764
spring:
application:
name: eureka-ribbon
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
C、@EnableDiscoveryClient向服务中心注册
并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class EurekaRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
D、HelloService
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String hiService(String name) {
return restTemplate.getForObject("http://EUREKA-CLIENT/hello?name="+name,String.class);
}
}
E、HelloControler
@RestController
public class HelloControler {
@Autowired
HelloService helloService;
@GetMapping(value = "/hello")
public String hi(@RequestParam String name) {
return helloService.hiService(name);
}
}
F、多次访问http://localhost:8764/hello?name=zs,浏览器“交替”显示:
hello zs,i am from port:8762
hello zs,i am from port:8763