Microservice framework

Nacos configuration management

  • Unified configuration management
  • Configure hot update

    Update the configuration in one place and take effect without restarting

  • Configure sharing
  • Build Nacos cluster

The configurations in nacos are all available in the cluster and need to be hot updated.

When the microservice is restarted, first read the configuration of the configuration center, and then read the local yaml configuration.

The address of nacos needs to be read as soon as the service is started. Therefore, it is better to put the configuration of nacos in bootstrap YML.

spring:
  application:
    name: userservice

  profiles:
    active: dev

  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yml # This needs to be the same as the suffix of DataId in the screenshot below

Hot updates can be displayed in 2 ways

@Value("${pattern.dateformat}")
private String dateFormat;
// The @ RefreshScope annotation needs to be added on the class
// ----------------

@Data
@Configuration
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties {
    private String dateFormat;
}

Multi environment configuration sharing

Some configurations are the same in environments such as redevelopment / production

[spring.application.name]-[spring.profiles.active].yaml, for example: userservice-dev.yaml

[spring.application.name].yaml, for example: userservice yaml

No matter how the profile changes, [spring. Application. Name] The yaml file must be loaded, so the multi environment sharing configuration can be written to this file

The priorities of various configurations are:
Service name - [active] Yaml > service name Yaml > local configuration
The local configuration is the lowest, the environment configuration in the configuration center is the highest, and the multi environment shared configuration is the second.

Cluster construction

Feign remote call

Declarative http client can send http requests more gracefully than RestTemplate.

Customize Feign configuration
  • journal

    Configuration file implementation

    feign:
      client:
        config:
          default:
            loggerLevel: FULL

    java code configuration

  • Response structure parser
  • Encoder sending request
  • Support annotation format. Spring MVC annotation is supported by default. Generally, it does not need to be set
  • The failure retry mechanism, which is not available by default, is implemented through the underlying Ribbon
Feign performance optimization

Feign's underlying implementation is implemented in three ways

  • URLConnection: the default implementation does not support link pool
  • Apache HttpClient: support connection pool
  • OKHttp: support connection pool

Change the default mode to support connection pool.

feign:
  client:
    config:
      default:
        loggerLevel: BASIC

  httpclient:
    enabled: true
    max-connections: 10
    max-connections-per-route: 50 #Maximum connections per path
Feign's best practices
  • The FeignClient of the consumer and the controller of the provider define a unified parent interface as the standard
  • Extract independent module

Both best practices have drawbacks
First: it will increase the degree of coupling
The second kind: many unnecessary interfaces will be introduced

For example, if the orderservice value requires some interfaces of feign API, when feign API is introduced, some unnecessary > will also be introduced

Unified Gateway

A protection for the entire microservice.

Two gateways are implemented in spring cloud

  • gateway
  • zuul

Comparison between the two: zuul is blocking programming, while gateway is weblux provided in spring 5. It belongs to responsive programming and has better performance.

Routing configuration

  • Route id: unique identifier of the route
  • uri: routing destination. lb and http are supported
  • Predictions: route assertion to judge whether the request meets the requirements. If it meets the requirements, it will be forwarded to the routing destination
  • Filters: routing filters that process requests or responses

Filter GateFilter:
Process the request to enter the gateway and the response returned by the microservice


One disadvantage of GateFilter is that it is configuration based and has limited functions.

GlobalFilter is a code based implementation that can handle complex filtering
Simple Liezi

@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 
     * @param exchange: parameter
     * @param chain:  Request chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // Get request parameters

        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        String s = params.getFirst("authorization");
        // Get parameter value
        if ("admin".equals(s)) {
            // Release
            return chain.filter(exchange);
        }

        // intercept
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}

Execution order of global filter default filter routing filter

Cross domain: domain name inconsistency is cross domain, mainly including:
Different domain names: www.taobao.com COM and www.taobao.com Org and www.jd.com COM and Miaosha jd. com
The domain name is the same, but the port is different: localhost:8080 and localhost8081
Cross domain problem: the browser prohibits cross domain ajax requests between the initiator of the request and the server, and the request is intercepted by the browser
Solution: CORS

Keywords: Spring

Added by prudens on Thu, 13 Jan 2022 15:42:54 +0200