微服務專題06-雲原生應用(Cloud Native Applications)

前言

前面的章節我們講了WebFlux 的原理與運用。本節,繼續微服務專題的內容分享,共計16小節,分別是:

本節內容重點爲:

  • Bootstrap 應用上下文:介紹 Spring Cloud 新引入的 Bootstrap 應用上下文,說明其與 Spring Framework 應用上下文之間的聯繫,進一步理解 Bootstrap 應用上下文在 Spring Boot 應用中的層次關係
  • 端點介紹:介紹 Spring Cloud 在 Spring Boot 基礎上新引入的端點(Endpoint),比如:上下文重啓:/restart、生命週期:/pause/resume

Spring Cloud 的特點

Spring Cloud致力於爲典型的用例和擴展機制提供良好的開箱即用體驗,以涵蓋其他用例。

  • 分佈式/版本化配置
  • 服務註冊和發現
  • 路由
  • 服務到服務的呼叫
  • 負載均衡
  • 斷路器
  • 分佈式消息傳遞

什麼是雲原生?

SpringCloud (Greenwich.SR5) 雲原生官方文檔

Cloud Native 是一種應用程序開發樣式,鼓勵在持續交付和價值驅動型開發領域輕鬆採用最佳實踐。一個相關的學科是構建 12要素 應用程序,其中開發實踐與交付和運營目標保持一致-例如,通過使用聲明性編程,管理和監視。Spring Cloud通過多種特定方式促進了這些開發風格。起點是一組功能,分佈式系統中的所有組件都需要輕鬆訪問這些功能。

Spring Cloud構建於其中的Spring Boot涵蓋了許多這些功能。Spring Cloud作爲兩個庫提供了更多功能:Spring Cloud上下文和Spring Cloud Commons。Spring Cloud Context爲ApplicationContextSpring Cloud應用程序提供實用程序和特殊服務(引導上下文,加密,刷新作用域和環境端點)。Spring Cloud Commons是在不同Spring Cloud實現中使用的一組抽象和通用類(例如Spring Cloud Netflix和Spring Cloud Consul)。

什麼是雲原生?有哪些發展方向?終於有人講明白了!

Spring 應用上下文 - ApplicationContext

工欲善其事必先利其器!學好 Spring Cloud 需要 Spring Boot 基礎,而學好 Spring Boot 需要深刻理解 Spring Framework。Spring 應用上下文又是整個 Spring 框架非常重要的一環。

在前面的章節我們多次提到了 Spring 應用上下文 ApplicationContext ,另外我們在本系列的第一節也提到了註解 Component “派生性”。那麼這其中又有什麼聯繫呢?我們又該如何理解 Spring 應用上下文的層次呢?

Spring 事件

回顧一下 Spring 事件 中關鍵的幾個類:

事件類:ApplicationEvent

事件監聽器: ApplicationListener

事件廣播器:ApplicationEventMulticaster 與其唯一實現類 SimpleApplicationEventMulticaster

事件發送器:ApplicationEventPublisher

理解上下文層次

Q:BeanFactoryApplicationContext類層次性:

A:我們看ApplicationContext 這個類,它擴展 ListableBeanFactory 以及 HierarchicalBeanFactory

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

從結構而言,ApplicationContext 關聯了 BeanFactory 實現。ApplicationContext 的抽象實現類 AbstractRefreshableApplicationContext 就包含了屬性 beanFactory DefaultListableBeanFactory

在這裏插入圖片描述
實際上就是 AppliationContext 繼承 BeanFactoy

這裏運用的設計模式就是裝飾者模式,繼承並擴展,底層實現基於被擴展示例。

總結:

  • BeanFactory 纔是真正 Bean 容器,管理 Bean 生命週期。

  • ApplicationContext 包含了 BeanFactory 職責,並且還有其他功能。

Q: ApplicationContext 繼承了 HierarchicalBeanFactory,給開發人員的提示?

A: ApplicationContext Bean 生命週期管理能力,來自於 BeanFactory,並且它又是 HierarchicalBeanFactory 子接口,說明它具備 BeanFactory 的層次性關係。同時,它也有 getParent() 方法返回雙親ApplicationContext,其子接口 ConfigurableApplicationContext 擁有設置雙親 ApplicationContext 的能力。

類比:

  • Parent BeanFactory (管理 10 個Bean)
  • Child BeanFactory (管理 20 個Bean)
  • Parent ClassLoader (加載 10 個類)
  • Child ClassLoader (加載 20 個類)

demo演示:設置spring上下文啓動

@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;
    }

}

運行此上下文,並訪問:http://localhost:9091/actuator/beans,得到:

在這裏插入圖片描述
說明,子上下文必須雙親上下文啓動,上圖所示的上下文關係爲:

  1. application-1 它的 parentId 是 test
  2. test 它的 parentId 是 bootstrap
  3. bootstrap 它的 parentId 是 null

Spring Boot 1.x 默認情況一個 ApplicationContext。如果獨立管理上下文 ,有兩個 ApplicationContext。
Spring Boot 2.0 合併一個 ApplicationContext,Spring Cloud 會增加 Bootstrap ApplicationContext。

是不是意味着 bootstrap 要提早加載什麼資源?

理解 Bootstrap 應用上下文

關鍵調用實現

Spring Boot 實現

  • org.springframework.boot.builder.ParentContextApplicationContextInitializer

Spring Cloud 實現

  • org.springframework.cloud.bootstrap.BootstrapApplicationListener 。其監聽的事件是 ApplicationEnvironmentPreparedEvent 。推理意思:Environment 已經準備好(被調整)

技術關聯: Spring 應用上下文層次,Spring 事件

理解 Environment

Spring Boot 外部化配置官方文檔

理解 Spring Boot Actuator Endpoints

我們通常說SpringBoot做健康檢查,用的就是此項技術,不過在實際應用中爲了保障安全,會設置不同的端點的權限,我們這裏只是簡單地介紹一下基本情況。

設置啓動類

@EnableAutoConfiguration
public class SpringBootApplicationBootstrap {

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

開放所有Web 管理 Endpoints

spring.application.name = first-spring-cloud-app
# 設置 Web 服務端口
server.port = 9090
# 設置 Web 管理端口(服務上下文和管理上線獨立)
management.server.port = 9091

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

啓動日誌輸出

啓動 spring 應用上下文,並訪問地址: http://localhost:9091/actuator
在這裏插入圖片描述
JSON展示:

{
    "_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
        }
    }
}

上面的配置文件中我將所有端口開放,所以通過訪問 /actuator後得到所有暴露的端點的地址,比如:

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

那麼我們此時訪問: http://localhost:9091/actuator/beans ,就會得到被Spring監控的Bean的詳情:
在這裏插入圖片描述

獲取環境端口(/actuator/env)

訪問端口:http://localhost:9091/actuator/env

在這裏插入圖片描述

/actuator/pause 和 /actuator/resume 端口

/actuator/pause 和 /actuator/resume 端口 默認失效,首先要在配置文件中開啓端點:

management.endpoint.restart.enabled=true
management.endpoint.pause.enabled=true
management.endpoint.resume.enabled=true
  • /actuator/pause -> ApplicationContext#stop() -> Spring LifeCycle Beans stop()。但是 LifeCycle 實例(ApplicationContext)不等於 LifeCycle Bean

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

端點介紹

Spring Boot 探索 | Actuator 端點詳細說明

後記

本節代碼地址:https://github.com/harrypottry/microservices-project/tree/master/spring-cloud-project/spring-cloud-native-application

更多架構知識,歡迎關注本套Java系列文章Java架構師成長之路

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章