Spring Cloud's next day class notes

Keywords: Java

1. Feign applications

Objective: The role of Feign; Using Feign to invoke services in consumer-demo code

Analysis:

  1. Import starter dependency;
  2. Turn on Feign function;
  3. Write Feign client;
  4. Write a processor ConsumerFeignController, inject Feign client and use it;
  5. test

Summary:

Feign's primary role: Splicing http request addresses automatically based on parameters.

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

  • Feign client:
//Declare that the current class is a Feign client and specify a service name of user-service
@FeignClient("user-service")
public interface UserClient {

    //http://user-service/user/123
    @GetMapping("/user/{id}")
    User queryById(@PathVariable Long id);
}

2. Feign Load Balancing and Fusing

Target: Feign built-in ribbon configuration item and Hystrix fused Fallback configuration can be configured

Analysis:

  • load balancing
  • Service Fusion
  • Request Compression
  • log level

All can be turned on and used in Feign through configuration items.

Summary:

Configuration files in consumer-demo for service consumption engineering:

ribbon:
  ConnectTimeout: 1000 # Connection timeout
  ReadTimeout: 2000 # Data communication timeout
  MaxAutoRetries: 0 # Number of retries for the current server
  MaxAutoRetriesNextServer: 0 # How many service retries
  OkToRetryOnAllOperations: false # Whether to retry all requests
feign:
  hystrix:
    enabled: true # Turn on the fusing function of Feign
  compression:
    request:
      enabled: true # Turn on request compression
      mime-types: text/html,application/xml,application/json # Set Compressed Data Type
      min-request-size: 2048 # Set the lower limit of the size to trigger compression
    response:
      enabled: true
logging:
  level:
    com.itheima: debug

3. Introduction to the Spring Cloud Gateway Gateway

Target: Role of the Spring Cloud Gateway Gateway

Summary:

The core of Spring Cloud Gateway is a series of filters that forward client requests to different microservices. Main functions: filtering and routing.

4. Getting started with Spring Cloud Gateway

Goal: Set up Gateway Service Project to test Gateway Service Role

Analysis:

Requirements: Requests containing/user are routed to the gateway system heima-gateway http://127.0.0.1:9091/user/ User id

Steps to achieve:

  1. Create a project;
  2. Add starter dependency;
  3. Write boot class and configuration file;
  4. Modify the configuration file to set the routing information;
  5. Start test

http://127.0.0.1:10010/user/8 --> http://127.0.0.1:9091/user/8

Summary:

  • Starter Dependency
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

  • configuration file
server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # Route id, can be any
        - id: user-service-route
          # Service Address of Agent
          uri: http://127.0.0.1:9091
          # Routing assertion: mapped paths can be matched
          predicates:
            - Path=/user/**

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    prefer-ip-address: true

5. Service-oriented routing

Target: Use services registered in eureka as routing addresses

Analysis:

Writing the routing service address to death is obviously unreasonable; In Spring Cloud Gateway, dynamic routing can be configured to solve this problem.

Summary:

Service-oriented routing; Similar routing paths need to be specified in the configuration file: lb://user-service

Service names written after lb must be registered in eureka to be used

6. Routing prefix processing

Target: You can add or remove prefixes to addresses that request Gateway Services

Analysis:

Address to provide service: http://127.0.0.1:9091/user/8

  • Add prefix: The prefix path is added to the request address before it is used as the service address of the proxy;

http://127.0.0.1:10010/8 --> http://127.0.0.1:9091/user/8 Add prefix path/user

  • Remove prefix: Remove some prefix paths from the request address before serving as the proxy address;

http://127.0.0.1:10010/api/user/8 --> http://127.0.0.1:9091/user/8 Remove prefix path/api

Summary:

If the client's request address is inconsistent with the service address of the micro service, the path prefix can be added and removed by configuring a path filter.

7. Introduction to filters

Target: Gateway default filter usage and filter type

Summary:

  • Usage: Specify the name of the filter to use in the configuration file;
  • Type: local, global;
  • Use scenarios: request authentication, exception handling, record call duration, and so on.

8. Customize local filters

Target: Write and configure a custom local filter based on the default filter that can get the requested parameter values from the parameter names in the configuration file

Analysis:

Requirements: In the filter (MyParamGatewayFilterFactory), the http://localhost:10010/api/user/8? The value of parameter name in name=itcast is obtained and output to the console; And parameter names are variable, that is, they are not always names; You need to configure parameter names when configuring filters.

Steps to achieve:

  1. Configure filters;
  2. Write filters;
  3. test

Summary:

  • To configure; Configuration is consistent with other filters.

  • Implement filters

package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {

    static final String PARAM_NAME = "param";

    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARAM_NAME);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // http://localhost:10010/api/user/8?name=itcast   config.param ==> name
            //Gets the parameter value of the parameter name corresponding to the param in the request parameter
            ServerHttpRequest request = exchange.getRequest();
            if(request.getQueryParams().containsKey(config.param)){
                request.getQueryParams().get(config.param).
                        forEach(value -> System.out.printf("------------Local filter--------%s = %s------", config.param, value));
            }
            return chain.filter(exchange);
        };
    }


    public static class Config{
        //Corresponds to the parameter name specified when configuring the filter
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}

9. Customize Global Filters

Target: Define a global filter to check for token parameters in requests

Analysis:

Requirements: Write a global filter that checks if the request address carries a token parameter. If the value of the token parameter exists, it is released. If the parameter value of token is empty or does not exist, set the status code returned to be: unauthorized and no longer executed.

Steps to achieve:

  1. Write global filters;
  2. test

Summary:

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("--------------Global filter MyGlobalFilter------------------");
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if(StringUtils.isBlank(token)){
            //Set response status code to unauthorized
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //The smaller the value, the earlier the execution
        return 1;
    }
}

10. Gateway Other Configuration Notes

Target: Load Balancing and Fuse Parameter Configuration for Gateway

Summary:

Gateway Service Profile:

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        # Route id, can be any
        - id: user-service-route
          # Service Address of Agent
          #uri: http://127.0.0.1:9091
          # lb represents getting a specific service from eureka
          uri: lb://user-service
          # Routing assertion: mapped paths can be matched
          predicates:
            #- Path=/user/**
            #- Path=/**
            - Path=/api/user/**
          filters:
            # Add prefix to request path
            #- PrefixPath=/user
            #1 means filter one path, 2 means two paths, and so on
            - StripPrefix=1
            - MyParam=name
      # Default filter, valid for all routes
      default-filters:
        - AddResponseHeader=X-Response-Foo, Bar
        - AddResponseHeader=abc-myname,heima
      globalcors:
        corsConfigurations:
          '[/**]':
            #allowedOrigins: * # Either this or below, * means all
            allowedOrigins:
              - "http://docs.spring.io"
            allowedMethods:
              - GET
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    prefer-ip-address: true
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000
ribbon:
  ConnectTimeout: 1000
  ReadTimeout: 2000
  MaxAutoRetries: 0
  MaxAutoRetriesNextServer: 0

Gateway is usually used directly for terminal requests; Feign is typically invoked between microservices.

11. Introduction to Spring Cloud Config Distributed Configuration Center

Target: The role of the Distributed Configuration Center

Summary:

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-cRXbpOdx-1638370181161)(assets/1560919656472.png)]

spring cloud config role: you can modify the configuration files of all other micro services by modifying the configuration files in the git repository.

12. Set up Configuration Center Micro-Service

Target: Create a remote open git repository in CodeCloud, and set up a configuration center micro-service config-server

Analysis:

  • Create a git warehouse: Create a warehouse on the code cloud
  • Build Configuration Center config-server: Build and configure using spring boot

Summary:

  • Configuration Center Dependency
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

  • Configuration Center Profile
server:
  port: 12000
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/goheima/heima-config.git
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

Modifying the configuration file in gitee will update the configuration center service in time.

13. Get the configuration center configuration

Target: To transform user-service for user micro-service, profile information is no longer provided by the micro-service project, but is obtained from the configuration center

Analysis:

Requirements: Delete the application.yml configuration file of the service provider project user-service and modify it to be obtained from the configuration center config-server.

Steps to achieve:

  1. Add starter dependency;
  2. Modify the configuration file;
  3. Start test

Summary:

Delete the original application.yml; Then add the bootstrap.yml configuration file, which is also the default configuration file for spring boot, whose contents often configure fixed configuration items in some projects. If the project is constantly changing, it should be configured in application.yml, and now using the configuration center, it should be configured in the configuration file for the git repository.

  • rely on
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
  • Configuration file bootstrap.yml
spring:
  cloud:
    config:
      # To be consistent with the application of the configuration file in the repository
      name: user
      # To be consistent with the profile of the configuration file in the repository
      profile: dev
      # To be the same version (branch) as the configuration file in the repository
      label: master
      discovery:
        # Use Configuration Center
        enabled: true
        # Configuration Center Service Name
        service-id: config-server

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

14. Introduction to Spring Cloud Bus

Goal: Understand the role of Spring Cloud Bus

Summary:

Role of Spring Cloud Bus: Update the git repository's configuration file to synchronize to the various microservices in a timely manner without restarting the system.

15. Spring Cloud Bus Applications

Target: Start RabbitMQ to update configuration items in user microservices in a timely manner by sending a Post request after modifying the configuration file in the code cloud

Analysis:

Requirements: Modify the user-dev.yml configuration file in the git repository in CodeCloud to update the configuration file in time without restarting user-service.

Steps to achieve:

  1. Start RabbitMQ;
  2. Modify the configuration center config-server;
  3. Modify service provider project user-service;
  4. test

Summary:

  • Dependent add content for config-server
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-bus</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
        </dependency>

  • Configuration file additions for config-server
server:
  port: 12000
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/goheima/heima-config.git
  # Configure rabbitmq information; Configuration is not required if both are consistent with defaults
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
management:
  endpoints:
    web:
      exposure:
        # Expose the address of the trigger message bus
        include: bus-refresh
  • Dependent add content for user-service
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-bus</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

  • Configuration file additions for user-service
  # Configure rabbitmq information; Configuration is not required if both are consistent with defaults
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

  • Modification of UserController

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-okXNXJ6L-1638370181164)(assets/1561003475491.png)]

16. Comprehensive application of Spring Cloud system technology

Target: Understand the comprehensive application of Eureka, GateWay, Config, Bus, Feign and other technologies in Spring Cloud

Summary:

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-AimFV13Z-1638370181167) (assets/1561004983897(1))].png)

r-rabbit


org.springframework.boot
spring-boot-starter-actuator



- user-service Configuration File Add Content

```yml
  # Configure rabbitmq information; Configuration is not required if both are consistent with defaults
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

  • Modification of UserController

[img-okXNXJ6L-1638370181164)]

16. Comprehensive application of Spring Cloud system technology

Target: Understand the comprehensive application of Eureka, GateWay, Config, Bus, Feign and other technologies in Spring Cloud

Summary:

[img-AimFV13Z-1638370181167)].png)

Posted by Nandini on Wed, 01 Dec 2021 14:10:00 -0800