spring cloud netflix microservice instance

Posted by AlanG on Sun, 19 Dec 2021 20:16:51 +0100

Project introduction

spring cloud netflix provides a full set of support for microservices, including service registration and discovery, routing, load balancing, circuit breaker, etc. you can see the principles and usage Official website corresponding to spring The content of the official website is quite practical. You should pay attention to the version correspondence when looking up. First go to the spring cloud project of the corresponding version, and then find its sub project spring cloud netflix. In this example, eureka is used to realize service registration and discovery, zuul routing, hystrix is used as circuit breaker, and ribbon is used to realize load balancing. In order to facilitate observation, springboot actuator is introduced. The project code can be found in github and gitee If you have any questions, please leave a message.

Project structure

 

Project explanation

eureka-server

After the project dependency is introduced, basically everything is completed with the help of the server. You only need to configure it and start the server instance. In CAP theory, eureka server satisfies AP, and there is no distinction between master and slave in the cluster, and the communication between servers is equal. The core dependencies of the project are as follows:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

application. The YML configuration is as follows. You need to modify the host file to map localhost1 and localhost2 to 127.0 0.1. When starting the server instance, you need to specify the profile:

spring:
  application:
    name: eureka-server
---
spring:
  profiles: server1
eureka:
  instance:
    hostname: localhost1
  client:
    service-url:
      defaultZone:  http://localhost2:9091/eureka
    register-with-eureka: true
    fetch-registry: true
server:
  port: 9090
---
spring:
  profiles: server2
eureka:
  instance:
    hostname: localhost2
  client:
    service-url:
      defaultZone:  http://localhost1:9090/eureka
    register-with-eureka: true
    fetch-registry: true
server:
  port: 9091

micro-services-consumer

Service consumers consume services only for debugging. In fact, you can call services through postman without writing controller. The core role of the mudule is actually gateway, circuit breaker and load balancing. The consumer's consumption code is as follows:

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/getResult/{num}")
    public Object getResult(@PathVariable("num") Integer num){

        List<ServiceInstance> instances = discoveryClient.getInstances("micro-services-provider");
        // Get the first service information
        ServiceInstance instanceInfo = instances.get(0);
        //Get ip
        String ip = instanceInfo.getHost();
        //Get port
        int port = instanceInfo.getPort();
        String url  ="http://"+ip+":"+port+"/provider/calculateResult/"+num;
        return restTemplate.getForObject(url, Integer.class);
    }

}

The dependencies are as follows. The zuul dependency actually includes hystrix and ribbon, which need not be introduced again:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

application.yml configuration:

server:
  port: 8080
spring:
  application:
    name: micro-services-consumer
#eureku client configuration
eureka:
  client:
    service-url:
      defaultZone: http://localhost1:9090/eureka,http://localhost2:9091/eureka
    register-with-eureka: true
    fetch-registry: true
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}:@project.version@
#Configure the springboot actuator to enable all functions
management:
  endpoints:
    web:
      exposure:
        include:  '*'
#zuul configuration
zuul:
  routes:
    # Set the service path name
    services-provider:
      path: /provider/**
      # The registered name of the service, i.e. the service provider's spring application. name
      serviceId: micro-services-provider
    #services-provider1:
      #path: /provider1/**
      #serviceId: micro-services-provider1
  host:
    connect-timeout-millis: 3000
    socket-timeout-millis: 10000
#If it exceeds 6 seconds, the circuit breaker will be triggered to return the result
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000

Attention should be paid to the idempotency of the service. The request may have been sent to the service provider, but hystrix returned in advance because the processing time is too long. Generally speaking, if it is a very time-consuming processing, the service requester should send the request monitoring processing result, and the provider should return the result first and then process the task asynchronously.

micro-services-provider 

 pom. Core dependencies in XML:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

The service provider provides the following services:

@RestController
@RequestMapping("/provider")
public class ProviderController {
    @Value("${server.port}")
    private Integer port;

    @GetMapping("/calculateResult/{num}")
    public Integer calculateResult(@PathVariable("num") Integer num){
        return num^2;
    }

    @GetMapping("/getServerPort")
    public Integer getServerPort(){
        return port;
    }
}

 application.yml configuration:

server:
  port: 7070
spring:
  application:
    name: micro-services-provider
eureka:
  client:
    service-url:
      defaultZone: http://localhost1:9090/eureka,http://localhost2:9091/eureka
    fetch-registry: true
    register-with-eureka: true
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}:@project.version@

management:
  endpoints:
    web:
      exposure:
        include: [info, health, mappings]


info:
  app.name: micro-services-provider
  company.name: sherwin.com
  build.artifactId: @project.artifactId@
  build.version: @project.version@

Project operation diagram:

server runtime monitoring diagram

Call microservice through gateway:

Topics: Java Spring Spring Cloud