A brief introduction to Spring Cloud and a simple introductory example

Keywords: Java Spring Spring Cloud Microservices

1 Overview
Spring Cloud is based on Spring Boot, which provides several components to help enterprises build micro-service systems. The main functions it provides are: Service Registry/Service Registration/Service Call/Load Balancing/Circuit Breaker, etc. Generally, it uses the existing open source software, which is based on the concept of Spring Boot to package, simplify the invocation of various components and the interaction between them.

2 Common components
Spring Cloud mainly contains the following common components:

2.1 Eureka
The registry eureka-server, which provides functions such as service registration/service application;
Service provider, which registers services with eureka-server;

Service consumer, which is used to obtain services from eureka-server;

2.2 Ribbon
Components responsible for client load balancing; Typically combined with RestTemplate, load balancing is handled when accessing services provided by provider s.
That is, Ribbon is used by service callers to make service calls to callees, and load balancing on the client side occurs when the server has more than one node;

2.3 Feign
With Ribbon function type, for service calls from both caller and callee, while handling client load balancing; However, it can provide a local call-like way to invoke services provided by remote EurekaClient s; It is actually further encapsulated on Ribbon to improve the simplicity of invoking services.


3.1 Sample Scenario
Suppose you now have a provider that provides services to the outside world and deploys two nodes at the same time. Consumerer invokes its services through Feign or Ribbon, and its deployment relationship and data flow diagram are as follows:


Step 1: Start the registration center; Service providers and callers register with the service center;
Step 2: The service caller requests the service from the service center and invokes the service provided by the service provider based on the address information returned by the service center.
Step 3: The registry detects the status of service providers by heart rate detection, and sends a message to notify all registrants when a provider cannot connect.

The implementation of each node is detailed below. See the specific code Springcloud-demo: Starter case for SpringCloud, which includes swagger2, eureka, zuul, openfeign, hystrix, etc.

3.2 Eureka Server
See the module named eureka-server in the GITEE project for more code.
a. MVN dependency introduction
Introducing eureka-server dependent packages

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
b. Spring Boot Annotation Introduction and Service Startup Class
 Mainly through EnableEurekaServer To indicate that the node is a server.
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {

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

}

c. application.yml To configure
 It mainly configures the port and whether to register with the service center and obtain registration information from the service center.
Both configurations need to be configured to false; A server-only node no longer needs to register with the server and apply for registration information.
eureka:
    client:
        fetch-registry: false
        register-with-eureka: false
    instance:
        hostname: localhost
        ip-address: 127.0.0.1
        lease-expiration-duration-in-seconds: 90
        lease-renewal-interval-in-seconds: 30
        prefer-ip-address: false
server:
    port: 2001
spring:
    application:
        name: eureka-server
    profiles:
        active: dev

Pass after startup http://localhost:2001/ You can see the monitoring page for EurekaServer; There is no node registration at this time;

3.3 Service Providers
See the module named provider in the GITEE project for more code.
a. MVN dependency introduction
The dependency packages associated with the EurekaClient need to be introduced;

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

b. Note introduction
 adopt EnableDiscoveryClient Annotations will make the application oriented eureka-server Register.
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {

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

}
@RestController
public class WebController {

    @RequestMapping("/")
    public String working() {
        return "this is provider client";
    }

}

3.4 Service Callers

3.4.1   Calling services through Feign
Feign is similar to Ribbon in functionality, except that Feign further encapsulates the call.
a. Dependency

<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-hystrix</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>


b. Start the service

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
        System.out.println("Local Document Path: http://127.0.0.1:2004/doc.html");
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public IRule ribbonRule() {
        return new RandomRule();//Configure the policy here, corresponding to the profile
    }

}


c. ProviderClient   Definition
When invoking a service through Feign, you mainly use the FeignClient annotation to specify on which node the service needs to be invoked. This comment works on the interface; Used in conjunction with RequestMapping, you can specify which interface of the remote server is called by a method of the interface.

@FeignClient(name = "provider")
public interface ProviderClient {

    @RequestMapping(value = "/")
    String working();

}



d. application.yml configuration

server:
    port: 2004
spring:
    application:
        name: consumer
    profiles:
        active: dev
consumer:
    ribbon:
        NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
eureka:
    client:
        serviceUrl:
            defaultZone: http://127.0.0.1:2001/eureka/


e. Service Calls
Through a predefined ProviderClient   Class to call the corresponding interface of the remote server;

package com.chiyi.controller;

import com.chiyi.model.UserDo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @date 2020/11/13 14:32
 */
@Api(tags = "Consumer Testing Api Interface")
@RestController
@RequestMapping("/web")
public class WebController {

    @Resource
    ProviderClient providerClient;


    @ApiOperation("Consumer Test Interface")
    @GetMapping("/work")
    public String working() {
        return "this is consumer client";
    }

}


After starting the main method, you can see another node named consumer through the monitoring page of eureka-server.
 

Posted by colmtourque on Thu, 11 Nov 2021 08:38:49 -0800