Spring Cloud Netflix - Ribbon
Spring Cloud Netflix - Ribbon
什么是Ribbon
? Spring Cloud Ribbon是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过Spring Cloud的封装,可以让我们轻松地将面向服务的REST模版请求自动转换成客户端负载均衡的服务调用。Spring Cloud Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立部署,但是它几乎存在于每一个Spring Cloud构建的微服务和基础设施中。因为微服务间的调用,API网关的请求转发等内容,实际上都是通过Ribbon来实现的,包括后续我们将要介绍的Feign,它也是基于Ribbon实现的工具。所以,对Spring Cloud Ribbon的理解和使用,对于我们使用Spring Cloud来构建微服务非常重要。
服务消费者
springcloud-consumer-dept-80
依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> <version>2.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.2.2.RELEASE</version> </dependency>
配置
server: port: 80 eureka: client: register-with-eureka: false #消费者不需要向eureka注册中心注册自己 service-url: defaultZone: http://localhost:7001/eureka/
配置负载均衡
@Configuration public class ConfigBean{ @Bean @LoadBalanced //ribbon开启负载均衡 public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
控制器controller
@Autowired private RestTemplate restTemplate; //private static final String REST_URL_PERFIX = "http://localhost:8001"; //通过服务名访问 private static final String REST_URL_PERFIX = "http://SPRINGCLOUD-PROVIDER-DEPT"; @GetMapping("/dept") public List<Dept> all() { return restTemplate.getForObject(REST_URL_PERFIX + "/dept", List.class); }
自定义规则
@Bean public IRule myRule(){ //使用随机规则, 默认为轮询RoundRobinRule, 也可以自己编写规则 return new RandomRule(); }
启动类
@SpringBootApplication @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT", configuration = MyRule.class)//使用自定义的规则 public class DeptConsumer_80 { public static void main(String[] args) { SpringApplication.run(DeptConsumer_80.class, args); } }
相关推荐
baobaozai 2020-08-15
zfyaixue 2020-07-04
LUOPING0 2020-05-11
jiaming 2020-05-04
baobaozai 2020-04-30
natejeams 2020-04-02
jiaming 2020-02-26
IreanLau 2020-02-26
mikesno 2020-02-20
幸运小侯子 2020-02-14
IsanaYashiro 2020-02-13
qiaosym 2020-01-17
老谢的自留地 2020-01-06
深井兮兮 2019-12-30
isHooky 2019-12-24
NeverAgain 2019-12-20
jiangtie 2019-12-20
TS0 2019-12-17
benico 2019-12-17