Teach you how to build a SpringCloud project (5) Build a producer cluster version

What are microservices? A series will be seen at a glance!

1. Teach you how to build a SpringCloud project (1) Detailed explanation with pictures and texts, fool-like operation

2. Teach you how to build a SpringCloud project (2) Producers and consumers

3. Teach you how to build a SpringCloud project (3) Integrate the Eureka service registration center

4. Teach you how to build the SpringCloud project (4) Eureka cluster version construction

5. Teach you how to build the SpringCloud project (5) Build the producer cluster version

6. Teach you how to build a SpringCloud project (6) Eureka realizes service discovery

7. Teach you how to build a SpringCloud project (7) Integrate the Consul service registration center

8. Teach you how to build a SpringCloud project (8) Integrated Ribbon load balancer

9. Teach you how to build a SpringCloud project (9) Integrate OpenFeign service interface calls

10. Teach you how to build a SpringCloud project (10) Integrate Hystrix service downgrade

11. Teach you to build a SpringCloud project (11) Integrating Hystrix's service fuse

12. Teach you how to build a SpringCloud project (12) Integrate Hystrix's graphical Dashboard real-time monitoring

13. Teach you how to build a SpringCloud project (13) Integrate a new generation of Gateway

14. Teach you how to build a SpringCloud project (14) Integrated Config Distributed Configuration Center

15. Teach you how to build a SpringCloud project (15) Integrated Bus message bus

16. Teach you how to build a SpringCloud project (16) Integrated Stream message driver

17. Teach you how to build a SpringCloud project (17) Integrating Sleuth distributed link tracking

Continue to update, welcome to like and follow!
This article mainly demonstrates the construction of the producer cluster 负载均衡, that is, the service we pay. We refer to the previously built service cloud-provide-payment with port 8001. Now we build cloud-provide-payment02 service with port 7002.

The previous steps of creating and configuring are omitted, and the specific steps can be found in the previous article. The main thing here is to change the port number in the yml file. As shown below:

server:
  port: 8002 #服务端口
#spring相关配置
spring:
  application:
    name: mcroservice-payment  #服务名
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource  #当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver  #数据库驱动包
    url: jdbc:mysql://localhost:3306/db01?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
    username: root
    password: root
#mybatis:配置
mybatis:
  mapperLocations: classpath:dao/*.xml
  type-aliases-package: com.buba.springcloud.pojo    # 所有pojo别名类所在包
#eureka配置
eureka:
  client:
    #表示是否将自己注册进eureka  默认为true
    register-with-eureka: true
    #是否从EurekaServer中抓取已有的注册信息,默认为true,单点无所谓,集群必须设置true才能和ribbon使用负载均衡
    fetch-registry: true
    service-url:
      #集群配置
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
  instance:
    instance-id: payment8002
    prefer-ip-address: true

Start 7001, 7002 and then start 8001, 8002, 80 projects to check the effect, visit localhost:8001/payment/get/1 for self-test, the success interface is as follows:

insert image description here

Visit localhost:8002/payment/get/1 for self-test, the successful interface is as follows:

insert image description here

We visit http://localhost/consumer/payment/get/1, and always visit the producer service that uses port 8001. The producer service with port 8002 will not be called.
insert image description here

The reason is that in the controller layer of the consumer service, we hard-coded the request path, as shown in the following figure:

insert image description here

We just need to change to the service name of the producer, as shown in the figure below:

insert image description here

However, when accessing localhost/consumer/payment/get/1, the following error message will appear:
insert image description here

The reason is that we have configured access by service name, but we cannot determine which service it is. So we need to enable load balancing for restTemplate, the default is round robin. Just add the @LoadBalanced annotation to the restTemplate configuration class, which enables load balancing. As shown below:

package com.buba.springclould.order.config;
 
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
 
@Configuration
public class ApplicationContextConfig {
    
    
    @Bean
    //RestTemplate 的负载均衡能力
    @LoadBalanced
    public RestTemplate getRestTemplate(){
    
    
        return new RestTemplate();
    }
}

Then we restart the consumer service, visit localhost/consumer/payment/get/1 again, load balancing has been turned on, and the two services of the producer rotate alternately, as shown in the following figure:
insert image description here

Let's take a look at the source code of the @LoadBalanced annotation, as shown below:

/**
 * Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient
 * @author Spencer Gibb
 */
@Target({
    
     ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Qualifier
public @interface LoadBalanced {
    
    
}

You can see that @LoadBalanced is an annotation used to mark the RestTemplate bean to be configured to use LoadBalancerClient. Then let's take a look at LoadBalancerClient, as shown below:

public interface ServiceInstanceChooser {
    
    
    ServiceInstance choose(String serviceId);
}
public interface LoadBalancerClient extends ServiceInstanceChooser {
    
    <T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException;<T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request) throws IOException;
​
    URI reconstructURI(ServiceInstance instance, URI original);
}

LoadBalancerClient is an interface with four methods. Let's take a look at the functions of these methods:

  1. ServiceInstance choose(String serviceId) selects an instance of the corresponding service from the client load balancer according to the incoming service name serviceId.

  2. T execute() , use the service instance selected from the load balancer to execute the request.

  3. URI reconstructURI(ServiceInstance instance, URI original) means constructing a suitable URI for the system. We
    used the logical name of the service (http://HELLO-SERVICE/hello) when sending the request in the article Discovery and Consumption of Services in Spring Cloud Instead of a specific service address, in the reconstructURI method, the first parameter ServiceInstance instance is a specific service instance with host and port, the second parameter URI is the URI defined as host and port using the logical service name, and The returned URI is a specific request address in the form of host:port concatenated from the service instance details of ServiceInstance. In a word, it is to convert an address similar to http://HELLO-SERVICE/hello to an address similar to http://195.124.207.128/hello (the IP address may also be a domain name).

At this point, the construction of the producer cluster version and the realization of load balancing are completed! Is it so easy?

insert image description here

In the next article, learn Eureka's service discovery Discovery, continue to pay attention and like it. We continue to update.
insert image description here

Guess you like

Origin blog.csdn.net/weixin_39570655/article/details/131775500