SpringCloud之Ribbon

ribbon简介
Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.
译:Ribbon是一个客户端负载均衡器,它为您提供了对HTTP和TCP客户端行为的大量控制。feign已经使用了功能区,因此如果您使用的是@feignclient,那么本节也适用。

我们基于前面eureka的先启动注册中心再启动服客户端 客户端分别启动2个不同的服务端口

image.png

新建项目:添加pom依赖

  
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        
        
            org.springframework.cloud
            spring-cloud-commons
            2.1.1.RELEASE
        
spring:
  application:
    name: eureka-ribbon
server:
  port: 8764
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/eureka
#这边可以不关闭自动注册因为也可以把ribbon的当成一个服务注册过去

启动类

package com.tg.rabbin_customer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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 //启动一个eureka的客户端
public class RabbinCustomerApplication {

    public static void main(String[] args) {
        SpringApplication.run( RabbinCustomerApplication.class, args );
    }

    //开启负载均衡功能
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
package com.tg.rabbin_customer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

//编写一个接口
@Service
public class RestHeloService {

    @Autowired
    private RestTemplate restTemplate;


    //调用eureka注册中心的服务
    public String toSay() {
        return restTemplate.getForObject( "http://EUREKA-CLIENT/hi", String.class );
    }
}

编写一个restCOntroller测试
package com.tg.rabbin_customer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestHelloController {

    @Autowired
    private RestHeloService restHeloService;

    @GetMapping(value = "/hi")
    public String toRest() {
        return restHeloService.toSay();
    }
}
启动服务
多次访问

image.png

image.png

此时的系统架构


image.png

一个服务注册中心,eureka server,端口为8761
service-hi工程跑了两个实例,端口分别为8762,8763,分别向服务注册中心注册
sercvice-ribbon端口为8764,向服务注册中心注册
当sercvice-ribbon通过restTemplate调用service-hi的hi接口时,因为用ribbon进行了负载均衡,会轮流的调用service-hi:8762和8763 两个端口的hi接口;

你可能感兴趣的:(SpringCloud之Ribbon)