SpringCloud study concluded (f) - service calls and load balancing Ribbon

Case Preparation

Use Case Project Address: Portalspring_cloud_ribbon

 

A, Ribbon service call

After the above study, it has achieved a service registration and service discovery. When starting a service, information can be registered to the registry in the form of HTTP, and the tool can be provided by SpringCloud obtain a list of registered service center. But the call between the service there are still many problems, how to be more convenient to call micro-services and how service providers plurality of micro-choice, how load balancing and so on.

 

1, Ribbon Overview

1.1 What is the Ribbon

Is Netflixfa released a load balancer, HTTP and TCP helps control client behavior. In the SpringCloud, Eureka is generally carried out with the use of Ribbon, Ribbon provides a functional client load balancing, using the Ribbon to read from Eureka in the service information when calling the service node provides service, would a reasonable load.

In SpringCloud the registry and can be used in conjunction with Ribbon, Ribbon automatically obtain a list of information service providers from the registry, and the built-in load balancing algorithm based service request

The main effect of 1.2 Ribbon

(1) service call based Ribbon implement service calls, is composed of (service name - the request path) through pull a list of all services to the mapping relationship. With RestTemplate final call

(2) load balancing service address when there are multiple service providers, Ribbon can automatically load-balancing algorithm to select the required call

 

2, Ribbon realize orders calling Goods

Whether Eureka based registry or registry-based Consul of, SpringCloudRibbon unified package, so for service calls, both ways is the same.

2.1 coordinate dependence

In the jar of service provided springcloud discovered and contained Ribbon dependence. So there is no need to import any additional coordinates, Eureka inherited Ribbon

2.2 Consumer Services

Modify the service consumer order_service module startup class OrderApplication, add @LoadBalanced annotation on a method to create RestTemplate

@SpringBootApplication 
@EntityScan ( "cn.hzp.order.domain" )
 public  class OrderApplication { 
    / ** 
     * Use spring provided RestTemplate http request to send Goods Services 
     * 1. Create RestTemplate objects to the container management 
     * 2. Use when the operation is completed call its methods (getXX, postxxx) 
     * * @LoadBalanced: ribbon is to provide load balancing annotation 
     * / 
    @LoadBalanced 
    @Bean 
    public RestTemplate RestTemplate () {
         return  new new RestTemplate (); 
    } 
    public  static  void main (String [] args) { 
        SpringApplication.run (OrderApplication. class , args); 
    }
}

 

 

Add the following method in OrderController order_service modules, and complete service calls using RestTemplate

 / ** 
     * based on the form of micro-ribbon remote service invocation 
     * 1. Statement @LoadBalanced RestTemplate 
     * 2. Alternatively ip address service name 
     * / 
    @RequestMapping (value = "/ Buy / {ID}", Method = RequestMethod.GET )
     public Product the findById (Long @PathVariable ID) {
         // service name service-product replacement address ip 
        Product Product restTemplate.getForObject = ( "HTTP: // service-product / Product /" + ID, Product. class );
         return Product ; 
    }

 


2.3 Test Code

The browser requests http: // localhost: 9002 / order / buy / 1 View showing the effect of the following, already has served in the form of name calling services to get data in micro-goods orders micro service.

 

 

 

Two, Ribbon load balancing

1, Load Balancing Overview

 

1.1 What is load balancing

In the construction of the site, if the web service performance and reliability of a single node can not meet the requirements; or in the use of external network services, often for fear of being compromised people, believe it will have a case to open outside ports, usually the when adding load balancing can effectively resolve service issues.

Load balancing is a network-based service, the principle is on the front load balancing service, in accordance with the specified load balancing algorithm to assign traffic to run through the back-end services cluster, thus providing the ability to parallel extensions to the system.

Load balancing scenarios include traffic packet forwarding rules, and back-end service, because the service has a network of internal and external cases, health checks and other functions, can effectively provide the security and availability of the system.

 

 

 

1.2 client load balancing and server load balancing

Note: Ribbon is a typical client load balancer.

Server load balancing

First sends a request to the server load balancing or software, then load balancing algorithm between the plurality of servers to access a selected; i.e., load balancing again allocation algorithm on the server side.

Client load balancing

The client will get a server address list, select a server through load balancing algorithm before sending the request, then visit, it is the client load balancing; that is to perform a load balancing algorithm on the client access to services address sent.

 

2, load balancing based on the Ribbon

More than 2.1 build Goods

1, the modified product_service application.yml profile, a plurality of instances arranged in the form of profiles

Server: 
  Port: 9001 # port 
the Spring: 
  the Application: 
    name: Service-Service Product # Name 
  the DataSource: 
    Driver-class-name: com.mysql.jdbc.Driver 
    url: jdbc: MySQL: //192.168.126.99: 3306 / spring_cloud_demo? useUnicode = to true & characterEncoding = utf8 
    username: root 
    password: root 
  JPA: 
    Database: MySQL 
    Show-SQL: to true 
    Open-in-View: to true 
# configure Eureka 
Eureka: 
  Client: 
    Service-url: 
      defaultzone: HTTP: // localhost: 9000 / Eureka /, http: // localhost: with between 8000 / eureka / multiple # eurekaserver, separated 
  instance: 
    the prefer-ip-address: ip address registered to true # use 
    instance-ID: $ {address} spring.cloud.client.ip-: $ {#} to register the server.port registration service Center id 
    Lease-Renewal-in-seconds The interval The-: # 5 want to continue sending the heartbeat of registry about interval 5S 
    Lease-expiration--in-seconds the DURATION: 10 #eureka Client sends a heartbeat to the server side, renew the expiration time (default 90 seconds) 
# plurality of service instances goods 
--- 
# configure the product1 9001 configuration information for 
the Spring: 
  Profiles: product1 
Server: 
  port: 9001 # port 
--- 
# configure product1 9011 configuration information for 
the Spring: 
  Profiles: product2 
Server: 
  port: 9011 port #

 

 

 

2, modify the code module merchandise return service IP and port information

public class ProductController {
​
    @Autowired
    private ProductService productService;
​
    @Value("${server.port}")
    private String port;
    @Value("${spring.cloud.client.ip-address}")
    private String ip;
​
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable Long id) {
        Product product = productService.findById(id);
        product.setProductName(ip+":"+port);
        return product;
    }
}

 

 

3, IDEA two configuration Goods Services launch configuration:

 

 

 

 

 

 

In order service by load balancing call Goods

 

 

 

2.2 load balancing strategy

Ribbon with built-in load balancing strategy, responsible for complex internal balance top-level interface to com.netflix.loadbalancer.IRule, implementation follows

 

 

 

  • com.netflix.loadbalancer.RoundRobinRule : Round-robin fashion for load balancing.

  • com.netflix.loadbalancer.RandomRule : Random Strategy

  • com.netflix.loadbalancer.RetryRule : Retry strategy.

  • com.netflix.loadbalancer.WeightedResponseTimeRule: Weighting strategy. Each service will calculate the weight, the greater the higher the likelihood of being called.

Modify the load balancing policy in the service of consumers order-server module configuration file application.yml

# Modify ribbon load balancing strategy is consumer service name - ribbon - NFLoadBalancerRuleClassName: Strategy 
Service-Product: 
  ribbon: 
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

 

Strategies:

1, the same as if each machine configuration, it is recommended not to modify the policy (recommended)

2, if the strong part of the machine configuration, you can change the weight strategy WeightedResponseTimeRule

Request retry 2.3

 

 

 

scene:

Service A, B provide the same service. If consumers request service A, A hang up or if this time the timeout request, if the request is not configured to retry [], when the consumer access to the service A will complain, does not automatically go to access services B. So that when the load request to visit a polling error will occur.

solution:

Ribbon request retry configuration, when the load balance policy A polling access services, discovery hang A, B is to access another service, not being given.

 

1, a request to modify the service consumer Ribbon order-server module configuration file application.yml retry configuration

# Modify ribbon load balancing strategy service name - ribbon - NFLoadBalancerRuleClassName: Strategy 
Service-Product: 
  ribbon: 
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # weight strategy 
    ConnectTimeout: 250 # Ribbon connection timeout 
    ReadTimeout: 1000 # Ribbon of data read take timeout 
    OkToRetryOnAllOperations: true # whether all operations retry 
    MaxAutoRetriesNextServer: 1 # handover instances retries 
    MaxAutoRetries: 1 # current instance number of retries

 

2, to provide spring addition request retry coordinates

        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>

 

3, the test

SERVICE-PRODUCT two normal service

 

 

 

 

Now close one, repeated load balancing to call, an error does not occur. Orders can look at the log service requests, request retries can be found in the operation:

 

 

 

 

Third, source code analysis

// TODO To be added

 

 

 

 


 

We thank provided material itheima

Guess you like

Origin www.cnblogs.com/TvvT-kevin/p/12520159.html