Microservices topic 06-Cloud Native Applications

Preface

In the previous chapter, we talked about the principle and application of WebFlux . In this section, continue to share the content of the microservice topic, a total of 16 sections, namely:

The key points of this section are:

  • Bootstrap application context: introduce the newly introduced Bootstrap application context of Spring Cloud, explain its connection with the Spring Framework application context, and further understand the hierarchical relationship of Bootstrap application context in Spring Boot applications
  • Endpoint Introduction: Introduction endpoint (Endpoint) Spring Cloud Spring Boot on the basis of the newly introduced, such as: context restart: /restartLife cycle: /pause, /resumeetc.

Features of Spring Cloud

Spring Cloud is committed to providing a good out-of-the-box experience for typical use cases and extension mechanisms to cover other use cases.

  • Distributed/versioned configuration
  • Service registration and discovery
  • routing
  • Service-to-service call
  • Load balancing
  • breaker
  • Distributed messaging

What is cloud native?

SpringCloud (Greenwich.SR5) Cloud Native Official Document

Cloud Native is a style of application development that encourages easy adoption of best practices in continuous delivery and value-driven development. A related discipline is the construction of 12-element applications, where development practices are aligned with delivery and operational goals-for example, through the use of declarative programming, management and monitoring. Spring Cloud promotes these development styles in a variety of specific ways. The starting point is a set of functions that all components in a distributed system need to access easily.

The Spring Boot that Spring Cloud is built on covers many of these features. Spring Cloud provides more functions as two libraries: Spring Cloud context and Spring Cloud Commons. Spring Cloud Context provides utilities and special services (boot context, encryption, refresh scope and environment endpoints) for ApplicationContext Spring Cloud applications. Spring Cloud Commons is a set of abstract and common classes used in different Spring Cloud implementations (such as Spring Cloud Netflix and Spring Cloud Consul).

What is cloud native? What are the development directions? Someone finally got it!

Spring application context- ApplicationContext

If you want to do well, you must first sharpen your tools! To learn Spring Cloud well requires Spring Boot foundation, and to learn Spring Boot well requires a deep understanding of Spring Framework. Spring application context is a very important part of the entire Spring framework.

In the previous chapters, we mentioned Spring application context many times ApplicationContext, and we also mentioned the annotation Component"derivation" in the first section of this series . So what is the connection? How should we understand the level of Spring application context?

Spring events

Review the key classes in Spring events:

Event class:ApplicationEvent

Event listener: ApplicationListener

Event broadcaster: ApplicationEventMulticasterits only implementation classSimpleApplicationEventMulticaster

Event sender:ApplicationEventPublisher

Understand the context level

Q: BeanFactorythe ApplicationContextclass hierarchy:

A: We look at ApplicationContextthis class, it extends ListableBeanFactorywellHierarchicalBeanFactory

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
		MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
    
    
		...
}

In terms of structure, ApplicationContextassociated with the BeanFactoryimplementation. ApplicationContextAbstract implementation class AbstractRefreshableApplicationContextcontains the properties beanFactoryDefaultListableBeanFactory

Insert picture description here
Actually AppliationContextinherited BeanFactoy.

The design pattern used here is the decorator pattern, inherited and extended, and the underlying implementation is based on the extended example.

to sum up:

  • BeanFactory It is the real Bean container, which manages the Bean life cycle.

  • ApplicationContextIt includes BeanFactoryduties, and other functions.

Q: ApplicationContextInherited HierarchicalBeanFactory, tips for developers?

A: ApplicationContextBean lifecycle management capabilities, from BeanFactory, and it is HierarchicalBeanFactorya sub-interface, indicating that it has a BeanFactoryhierarchical relationship. It also has a getParent()method to return parents ApplicationContext, their sub-interfaces ConfigurableApplicationContexthave set the parental ApplicationContextabilities.

analogy:

  • Parent BeanFactory(Manage 10 Beans)
  • Child BeanFactory(Manage 20 Beans)
  • Parent ClassLoader(load 10 classes)
  • Child ClassLoader(load 20 classes)

Demo demo: set spring context to start

@EnableAutoConfiguration
@RestController
public class SpringBootApplicationBootstrap {
    
    

    public static void main(String[] args) {
    
    

        AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext();
        parentContext.setId("test");
        // 在"test" 上下文注册一个 "helloWorld" String 类型的 Bean
        parentContext.registerBean("helloWorld", String.class, "Hello,World");
        // 启动"test" 上下文
        parentContext.refresh();

        new SpringApplicationBuilder(SpringBootApplicationBootstrap.class)
                .parent(parentContext) // 显式地设置双亲上下文
                .run(args);
    }

    @Autowired // String message Bean
    @Qualifier("helloWorld") // Bean 名称,来自于 “test” 上下文
    private String message;

    @RequestMapping("")
    public String index() {
    
    
        return message;
    }

}

Run this context and visit: http://localhost:9091/actuator/beans , get:

Insert picture description here
Explain that the child context must be activated by the parent context. The context relationship shown in the figure above is:

  1. application-1 Its parentId is test
  2. test its parentId is bootstrap
  3. bootstrap its parentId is null

Spring Boot 1.x has an ApplicationContext by default. If you manage the context independently, there are two ApplicationContexts.
Spring Boot 2.0 merges an ApplicationContext, and Spring Cloud will add Bootstrap ApplicationContext.

Does it mean what resources bootstrap should load earlier?

Understand Bootstrap application context

Key call implementation

Spring Boot implementation

  • org.springframework.boot.builder.ParentContextApplicationContextInitializer

Spring Cloud implementation

  • org.springframework.cloud.bootstrap.BootstrapApplicationListener. The event it monitors is ApplicationEnvironmentPreparedEvent. Reasoning meaning: Environmentready (adjusted)

Technical association: Spring application context level, Spring event

Understand Environment

Spring Boot external configuration official document

理解 Spring Boot Actuator Endpoints

We usually say that SpringBoot performs health checks and uses this technology, but in actual applications, in order to ensure security, different endpoint permissions will be set. Here we just briefly introduce the basic situation.

Set startup class

@EnableAutoConfiguration
public class SpringBootApplicationBootstrap {
    
    

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

Open all Web management Endpoints

spring.application.name = first-spring-cloud-app
# 设置 Web 服务端口
server.port = 9090
# 设置 Web 管理端口(服务上下文和管理上线独立)
management.server.port = 9091

# 开放 所有Web 管理 Endpoints
management.endpoints.web.exposure.include = *

Start log output

Start the spring application context and visit the address: http://localhost:9091/actuator
Insert picture description here
JSON display:

{
    
    
    "_links":{
    
    
        "self":{
    
    
            "href":"http://localhost:9091/actuator",
            "templated":false
        },
        "auditevents":{
    
    
            "href":"http://localhost:9091/actuator/auditevents",
            "templated":false
        },
        "beans":{
    
    
            "href":"http://localhost:9091/actuator/beans",
            "templated":false
        },
        "health":{
    
    
            "href":"http://localhost:9091/actuator/health",
            "templated":false
        },
        "conditions":{
    
    
            "href":"http://localhost:9091/actuator/conditions",
            "templated":false
        },
        "configprops":{
    
    
            "href":"http://localhost:9091/actuator/configprops",
            "templated":false
        },
        "env":{
    
    
            "href":"http://localhost:9091/actuator/env",
            "templated":false
        },
        "env-toMatch":{
    
    
            "href":"http://localhost:9091/actuator/env/{toMatch}",
            "templated":true
        },
        "info":{
    
    
            "href":"http://localhost:9091/actuator/info",
            "templated":false
        },
        "loggers":{
    
    
            "href":"http://localhost:9091/actuator/loggers",
            "templated":false
        },
        "loggers-name":{
    
    
            "href":"http://localhost:9091/actuator/loggers/{name}",
            "templated":true
        },
        "heapdump":{
    
    
            "href":"http://localhost:9091/actuator/heapdump",
            "templated":false
        },
        "threaddump":{
    
    
            "href":"http://localhost:9091/actuator/threaddump",
            "templated":false
        },
        "metrics-requiredMetricName":{
    
    
            "href":"http://localhost:9091/actuator/metrics/{requiredMetricName}",
            "templated":true
        },
        "metrics":{
    
    
            "href":"http://localhost:9091/actuator/metrics",
            "templated":false
        },
        "scheduledtasks":{
    
    
            "href":"http://localhost:9091/actuator/scheduledtasks",
            "templated":false
        },
        "httptrace":{
    
    
            "href":"http://localhost:9091/actuator/httptrace",
            "templated":false
        },
        "mappings":{
    
    
            "href":"http://localhost:9091/actuator/mappings",
            "templated":false
        },
        "refresh":{
    
    
            "href":"http://localhost:9091/actuator/refresh",
            "templated":false
        },
        "features":{
    
    
            "href":"http://localhost:9091/actuator/features",
            "templated":false
        }
    }
}

In the above configuration file, I open all ports, so I get the addresses of all exposed endpoints by accessing /actuator, such as:

        "beans":{
    
    
            "href":"http://localhost:9091/actuator/beans",
            "templated":false
        },

Then we visit: http://localhost:9091/actuator/beans at this time , and we will get the details of the beans monitored by Spring:
Insert picture description here

Get the environment port (/actuator/env)

Access port: http://localhost:9091/actuator/env

Insert picture description here

/actuator/pause and /actuator/resume ports

The /actuator/pause and /actuator/resume ports are disabled by default. First, you must enable the endpoint in the configuration file:

management.endpoint.restart.enabled=true
management.endpoint.pause.enabled=true
management.endpoint.resume.enabled=true
  • /actuator/pause -> ApplicationContext#stop()-> Spring LifeCycle Beans stop(). But LifeCycle instance (ApplicationContext) is not equal to LifeCycle Bean

  • /actuator/resume -> ApplicationContext#start() -> Spring LifeCycle Beans start()

Endpoint introduction

Spring Boot Exploration | Actuator Endpoint Detailed Description

postscript

The code address of this section: https://github.com/harrypottry/microservices-project/tree/master/spring-cloud-project/spring-cloud-native-application

For more architectural knowledge, please pay attention to this series of articles on Java : The Road to Growth of Java Architects

Guess you like

Origin blog.csdn.net/qq_34361283/article/details/106445747