The Ribbon is a load balancer for clients. When consumers can invoke a service through a service alias, the Ribbon is used as a load balancer to access the actual service invocation address.

By simple analogy, we go to See Tony. There are usually many Tony teachers in a barber shop. But there will also be a staff similar to the front desk to arrange for the free Tony teacher to have his hair cut. The staff is just like Ribbon. Is it arranged sequentially or randomly?

Ribbon + Eureka

Create a project

Create an empty Ribbon module, and then create a Ribbon – Consume9101 submodule under the Ribbon empty module. Add dependencies to the poM file of the empty module’s parent class

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    </dependency>
</dependencies>
Copy the code

When you introduce Eureka dependencies, you already introduce Ribbon dependencies. So if you use Ribbon + Eureka, you can run the Ribbon without the Ribbon dependencies.

The overall project structure after creation is shown in the figure

The configuration file

application.yml

server:
  port: 9101

spring:
  application:
    name: ribbon-consume
eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8001/eureka/
  instance:
    instance-id: ribbon-consume9101
Copy the code

Startup and business classes

Note that the provider of our service is eureka-provide service. The name of this service may be more accurate with provide alone, which may be changed in the future project reconstruction.

When it comes to service-to-service calls, you typically choose RestTemplate and need to inject it into the Spring container, so use configuration classes

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced       // Annotations needed for load balancing
    public RestTemplate getRestTemplate(a) {
        return newRestTemplate(); }}Copy the code

Next up is the main launch class

@SpringBootApplication
@EnableEurekaClient
@RestController
public class RibbonConsume9101 {
    final String PROVIDE_URL = "http://eureka-provide";

    RestTemplate restTemplate;

    public RibbonConsume9101(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/ribbon/consume")
    public String getInfo(a) {
        return "i am consumer, but actually invoke other service: [" + restTemplate.getForObject(PROVIDE_URL + "/eureka/provide", String.class) + "]";
    }

    public static void main(String[] args) { SpringApplication.run(RibbonConsume9101.class, args); }}Copy the code

test

  1. Open EureakThe registryEurekaServer8001
  2. Enabled for 3 different portsService providerEurekaProvide7001EurekaProvide7002 , EurekaProvide7003
  3. Open the Ribbon you just createdconsumersRibbonConsume9101

If you first look at the Eureka registry, you can see that three service providers and one consumer have all registered with Eureka.

Then consumers access interface http://localhost:9101/ribbon/consume, can see from the service provider side access to the service, you can see can call three different port service provider side, and in turn calls in sequence (* * * * polling, is also the default rules).

Custom configuration classes

If you want to call the service in a different way, you need to customize the configuration class.

The Ribbon has six main components

  • ServerList:Define get server list
  • ServerListFilter:Perform secondary filtering for the ServerList list
  • ServerListUpdater:Define service update policies
  • Iping:Check whether the service list is alive
  • IRlue:Select a service in the list of services to invoke based on the algorithm
  • ILoadBalancer:Software load balancer entry, integrating all of the above components to achieve load functions
@Configuration
public class RibbonCustomConfig {
    @Bean
   public IRule ribbonRule(a) {
       return newRandomRule(); }}Copy the code

IRlue interface is to invoke the service provider with what rules, can look at the implementation of the interface class

To make the Ribbon aware of the configuration file, use the @RibbonClient annotation. Create an empty annotation class and add annotations and configuration classes to customize the Ribbon configuration.

@Configuration
@RibbonClient(name = "eureka-provide", configuration = RibbonCustomConfig.class)
public class RibbonConfig {}Copy the code

Here is what we need to call the name of the server in the configuration file springcloud. Application. The value of the name. It should be noted that there is such a passage in the official document

In this case, RibbonCustomConfig is scanned into Spring if it is in the same package as the main launch class, which results in the configuration file being shared by all @RibbonClients. You can also exclude configuration files with @ComponentScan.

Restart RibbonConsume9101 services, other don’t have to move, also called consumers access interface at http://localhost:9101/ribbon/consume

When I clicked, what, why did I keep calling port 7001? Did other services fail? We can see that the speed of the service is obviously increased.

Custom configuration files

In addition to customizing the Ribbon through configuration classes, you can also customize it through configuration files

ClientName here is also a need to call the server in the configuration file springcloud. Application. The value of the name. If it is a completely written class, need to implement the corresponding interface, here also uses The RandomRule class written by Netflix.

Delete the RibbonCustomConfig and RibbonConfig or comment them all out to modify the configuration file

server:
  port: 9101

spring:
  application:
    name: ribbon-consume
eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8001/eureka/
  instance:
    instance-id: ribbon-consume9101

# add the following content
eureka-provide:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
Copy the code

Eureka-provide is the clientName. Then restart RibbonConsume9101 service, other don’t have to move, also called consumers access interface at http://localhost:9101/ribbon/consume

It is important to note that variables configured in the configuration file are of higher priority than those configured in the configuration class.

Ribbon

The above shows that both the consumer end and the server end have registered with Eureka, which means that consumers find the services of other service providers through Eureka. How do you solve this problem if you accept the new consumer side in your real business and don’t register with Eureka?

Let’s take a look at what happens when you don’t register

Create a project

Also create a sub-module below the Ribbon parent module

The configuration file

Since you don’t need to register with Eureka, the configuration file needs to be modified accordingly

server:
  port: 9102

spring:
  application:
    name: ribbon-consume-without-eureka

# disable Eureka. It doesn't matter if you disable Eureka because there is no import
ribbon:
  eureka:
    enabled: false
Copy the code

Startup and business classes

You also need to import the RestTemplate so you can copy the previous submodule directly

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(a) {
        return newRestTemplate(); }}Copy the code

The main startup class can also be copied directly, without Eureka, by removing the @enableEurekaclient annotation and changing the class name

@SpringBootApplication
@RestController
public class RibbonConsumeWithoutEureka9102 {
    final String PROVIDE_URL = "http://eureka-provide";

    RestTemplate restTemplate;
	
    public RibbonConsumeWithoutEureka9102(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/ribbon/consume")
    public String getInfo(a) {
        return "i am consumer, but actually invoke other service: [" + restTemplate.getForObject(PROVIDE_URL + "/eureka/provide", String.class) + "]";
    }

    public static void main(String[] args) { SpringApplication.run(RibbonConsumeWithoutEureka9102.class, args); }}Copy the code

How does the consumer know where to find the provider’s service when they call it, so they need to move the configuration file

server:
  port: 9102

spring:
  application:
    name: ribbon-consume-without-eureka
ribbon:
  eureka:
    enabled: false

# Add content below
eureka-provide:
  ribbon:
    listOfServers: localhost:7001, localhost:7002, localhost:7003
Copy the code

The eureka – dojo.provide is need to call the server in the configuration file springcloud. Application. The value of the name

Open RibbonConsume9102 service, other don’t have to move, call consumers access interface, http://localhost:9102/ribbon/consume, you can see is also able to invoke services in accordance with the default polling.

Creation is not easy, if it is helpful to you, welcome to like, collect and share!

Article update continuously, you can follow wechat public account CodeNone, basic 2,3 days 1 more technical article!!