【springcloud研究 第三篇】Ribbon进程级负载均衡
一,概述
1,当前市面上进行负载均衡有三个层级
nginx | 软件级 |
f5 | 硬件级 |
ribbon | 进程级 |
2,本文需要的资源下载地址
https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-chapter2
3,本文涉及到的项目
eureka-server | 服务注册与发现 |
service-hi | 客户端访问 |
service-ribbon | 负载均衡器 |
二,开始研究
1 service-ribbon项目分析
pom
<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>
properties
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: service-ribbon
java代码
package com.forezp.serviceribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run( ServiceRibbonApplication.class, args );
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
负载均衡的关键注解
@LoadBalanced
通过这个注解可以让restTemplate具有负载均衡的效果,栗子
restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
如果此时调用如上的方法,将会自动轮询注册在节点上的多个(应用名为service-hi)
server:
port: 8763
spring:
application:
name: service-hi
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
中的其中一个
效果
hi forezp,i am from port:8762
hi forezp,i am from port:8763
三,
1 架构图
四,总结
1 ribbon通过注册在eurka上的多个相同service-hi实例,现实论询
2 eurka是所有服务的注册点,连通eurka就能获得相应的资源,比如负载均衡
3 restTemplate是个好东西