1. 程式人生 > 其它 >主流微服務一站式解決方案Spring Cloud Alibaba入門看這篇就足夠了

主流微服務一站式解決方案Spring Cloud Alibaba入門看這篇就足夠了

從Spring Cloud Alibaba為核心的微服務架構圖分層展開,涵蓋接入層、業務中臺層、技術中臺層、系統監控層完整網際網路推薦微服務架構體系,Spring Boot編碼示例實戰Spring Cloud Alibaba,演示Nacos配置中心和註冊中心服務註冊和服務發現使用、Spring Cloud Gateway微服務閘道器實現路由策略並整合Sentinel實現限流,微服務之間基於Open Feign遠端呼叫和整合Dubbo實現高效能RPC遠端呼叫。

學習路線

**本人部落格網站 **IT小神 www.itxiaoshen.com

生態概述

架構演進

什麼是微服務

https://martinfowler.com/microservices/

Microservices Guide

In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities

and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.

-- James Lewis and Martin Fowler (2014)

簡言之,微服務體系結構風格是一種將單個應用程式開發為一套小型服務的方法,每個服務都在自己的流程中執行,並與輕量級機制(通常是HTTP資源API)通訊。這些服務是圍繞業務能力構建的,可通過完全自動化的部署機制獨立部署。對這些服務的集中管理是最低限度的,這些服務可以用不同的程式語言編寫,並使用不同的資料儲存技術。

--詹姆斯·劉易斯和馬丁·福勒(2014)


架構演進

Dubbo文件

網站應用的演進

隨著網際網路的發展,網站應用的規模不斷擴大,常規的垂直應用架構已無法應對,分散式服務架構以及流動計算架構勢在必行,亟需一個治理系統確保架構有條不紊的演進。好的架構並不是一開始就設計出來的,而是不斷演進過來的

單一應用架構

當網站流量很小時,只需一個應用,將所有功能都部署在一起,以減少部署節點和成本。此時,用於簡化增刪改查工作量的資料訪問框架(ORM)是關鍵。

垂直應用架構

當訪問量逐漸增大,單一應用增加機器帶來的加速度越來越小,提升效率的方法之一是將應用拆成互不相干的幾個應用,以提升效率。此時,用於加速前端頁面開發的Web框架(MVC)是關鍵。

分散式服務架構

當垂直應用越來越多,應用之間互動不可避免,將核心業務抽取出來,作為獨立的服務,逐漸形成穩定的服務中心,使前端應用能更快速的響應多變的市場需求。此時,用於提高業務複用及整合的分散式服務框架(RPC)是關鍵。

流動計算架構

當服務越來越多,容量的評估,小服務資源的浪費等問題逐漸顯現,此時需增加一個排程中心基於訪問壓力實時管理叢集容量,提高叢集利用率。此時,用於提高機器利用率的資源排程和治理中心(SOA)是關鍵。

SOA服務架構和微服務架構


推薦架構

Spring Cloud官網

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer’s own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.

Spring Cloud為開發人員提供工具,用於快速構建分散式系統中的一些常見模式(例如配置管理、服務發現、斷路器、智慧路由、微代理、控制匯流排、一次性令牌、全域性鎖、領導選舉、分散式會話、叢集狀態)。分散式系統的協調導致鍋爐板模式,使用Spring雲開發人員可以快速建立實現這些模式的服務和應用程式。它們在任何分散式環境中都能很好地工作,包括開發人員自己的膝上型電腦、裸機資料中心和雲鑄造等託管平臺。


Spring Cloud Alibaba官網

Spring Cloud Alibaba provides a one-stop solution for distributed application development. It contains all the components required to develop distributed applications, making it easy for you to develop your applications using Spring Cloud.

With Spring Cloud Alibaba, you only need to add some annotations and a small amount of configurations to connect Spring Cloud applications to the distributed solutions of Alibaba, and build a distributed application system with Alibaba middleware.

阿里云為分散式應用開發提供一站式解決方案。它包含開發分散式應用程式所需的所有元件,使您可以輕鬆地使用SpringCloud開發應用程式。

通過阿里雲Spring雲,您只需新增一些註釋和少量配置,即可將Spring雲應用連線到阿里雲的分散式解決方案,並使用阿里雲中間件構建分散式應用系統。


Sentinel:流量控制和服務降級:阿里巴巴Sentinel流量控制、斷路和系統自適應保護

Nacos registration and discovery:服務註冊和發現:可以向阿里巴巴Nacos註冊例項,客戶端可以使用spring管理的bean發現例項。支援Ribbon,通過Spring Cloud Netflix的客戶端負載均衡器

Nacos config:分散式配置:使用阿里巴巴Nacos作為資料儲存

Seata:一種高效能、易於使用的分散式事務解決方案,適用於微服務架構。解決微服務中的分散式事務問題

Dubbo:Apache Dubbo 是一款高效能、輕量級的開源服務框架,提供了六大核心能力:面向介面代理的高效能RPC呼叫,智慧容錯和負載均衡,服務自動註冊和發現,高度可擴充套件能力,執行期流量排程,視覺化的服務治理與運維。

Spring Cloud Stream:事件驅動,使用 RocketMQ Binder構建高度可伸縮的事件驅動微服務

Spring Cloud Bus:訊息匯流排:使用Spring Cloud Bus連線分散式系統的節點

Spring Cloud Netflix Ribbon:客戶端負載均衡器: Nacos客戶端預設整合ribbon

Spring Cloud Gateway:提供了一個在Spring WebFlux上構建API閘道器的庫。Spring Cloud Gateway旨在提供一種簡單而有效的方式來路由到api,併為它們提供橫切關注點,如:安全性、監控/指標和彈性。

Appache SkyWalking:分散式系統的應用程式效能監控工具,特別為微服務,雲本地和基於容器(Docker, Kubernetes, Mesos)架構設計。

基於Spring Cloud Alibaba推薦的微服務生態架構,基於分層架構實現。

接入層:最外層為LVS+Keepalived,可承受幾十萬級高併發流量洪峰,然後再通過內層的nginx叢集將客戶端請求通過負載均衡策略轉發至基於JAVA後端技術棧的Spring Cloud Gateway叢集;

業務中臺層:Spring Cloud Gateway微服務通過Nacos獲取路由配置資訊和路由後端微服務提供者的發現,通過OAuth2做統一登入授權,並整合整合Sentinel針對請求做限流、熔斷、降低,基於dubbo協議的高效能RPC進行微服務呼叫或者服務聚合呼叫,而後端微服務之間呼叫也是採用dubbo協議的rpc,對於需要分散式事務服務端則通過Seata實現。

技術中臺層:資料儲存層包括記憶體、資料庫、全文檢索搜尋引擎儲存層;基礎服務層提供分散式系統常見基礎元件功能;日誌採集層採用ELK

系統監控層:分散式鏈路追蹤、基於容器化的監控和告警

Maven簡易整合工程入門案例

shopping-demo原始碼地址
https://gitee.com/yongzhebuju/shopping

功能簡介


本示例主要對微服務使用Nacos實現配置中心讀取、服務註冊和服務發現,微服務閘道器實現路由策略並整合sentinel實現限流,微服務之間使用Dubbo高效能RPC進行呼叫。

本案例主要包含一下幾個demo模組

commons:公共服務模組,存放公共pojo實體類和微服務介面模組,比如Dubbo服務提供者介面定義、基於Open Feign遠端呼叫服務提供者介面定義等,公共模組pom可以配置一些公共引用依賴如spring-cloud-starter-alibaba-nacos-config和spring-cloud-starter-alibaba-nacos-discovery等,這樣其他微服務只需依賴公共模組即可

gateway:微服務入口閘道器模組,負責微服務路由、授權認證、微服務聚合等功能處理

users:使用者模組,提供獲取使用者介面

good:商品模組,提供商品介面,需要呼叫使用者介面

核心原始碼和配置

工程父pom檔案主要包含Spring Boot、Spring Cloud、Spring Cloud Alibaba的父依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itxs</groupId>
    <artifactId>shopping</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
    </parent>

    <modules>
        <module>shopping_commons</module>
        <module>shopping_goods</module>
        <module>shopping_users</module>
        <module>shopping_gateway</module>
    </modules>

    <properties>
        <java.verson>1.8</java.verson>
        <spring.cloud.verison>Hoxton.SR12</spring.cloud.verison>
        <spring.cloud.alibaba.verison>2.2.1.RELEASE</spring.cloud.alibaba.verison>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.verison}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring.cloud.alibaba.verison}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

微服務yml配置檔案,微服務的配置都放在Nacos配置中心,每個微服務本地配置檔案只需配置服務名稱、啟用的環境以及配置中心地址、配置副檔名、名稱空間和組即可。下面為閘道器配置檔案,其他模組配置檔案與此類似

spring:
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yaml
        namespace: 54c53c3a-6008-4ecc-90fe-2ffcae64b95b
        group: shopping
  application:
    name: gateway

commons 實體類和暴露獲取使用者介面服務

package com.itxs.entity;

import java.io.Serializable;

public class User implements Serializable {
    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}
package com.itxs.service;

import com.itxs.entity.User;

public interface UserService {
    User getUser(String userId);
}

users微服務獲取使用者介面實現

package com.itxs.service;

import com.itxs.entity.User;
import org.apache.dubbo.config.annotation.Service;

@Service
public class UserServiceImpl implements UserService{
    @Override
    public User getUser(String userId) {
        System.out.println("userId:"+userId);
        return new User("zhangsan",16);
    }
}

users controller實現類,在這裡也提供http協議呼叫方式

package com.itxs.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping("/users/1")
    public String getUser(){
        return "hello users";
    }
}

goods controller

package com.itxs.controller;

import com.itxs.entity.User;
import com.itxs.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GoodsController {

    @Reference
    UserService userService;

    @RequestMapping("/goods/1")
    public String getGoods(){
        return "hello goods";
    }

    @RequestMapping("/goods/user")
    public String getUserInfo(){
        User user = userService.getUser("a1001");
        return user.toString();
    }
}

Nacos 配置中心

啟動本地Nacos server端,訪問本地nacos管理介面http://localhost:8848/nacos,預設埠是8848,預設使用者密碼nacos/nacos,在dev名稱空間下有閘道器、使用者、商品微服務配置檔案,都使用shoopping組

users-dev.yaml

server:
  port: 8081
spring:
  profiles:
    active: dev
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.3.3:8848
        namespace: 54c53c3a-6008-4ecc-90fe-2ffcae64b95b
        group: shopping
    sentinel:
      enabled: true
      transport:
        dashboard: localhost:8888
        port: 8719
  application:
    name: users

goods-dev.yaml

server:
  port: 8082
spring:
  profiles:
    active: dev
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.3.3:8848
        namespace: 54c53c3a-6008-4ecc-90fe-2ffcae64b95b
        group: shopping
    sentinel:
      enabled: true
      transport:
        dashboard: localhost:8888
        port: 8729
  application:
    name: goods

gateway-dev.yaml

server:
  port: 8083
spring:
  profiles:
    active: dev
  main:
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.3.3:8848
        namespace: 54c53c3a-6008-4ecc-90fe-2ffcae64b95b
        group: shopping
    sentinel:
      enabled: true
      transport:
        dashboard: localhost:8080
        port: 8719
    gateway:
      discovery:
        locator:
          lowerCaseServiceId: true
          enabled: true
      routes:
        - id: users_route
          uri: lb://users
          predicates:
            - Path=/users/**

        - id: goods_route
          uri: lb://goods
          predicates:
            - Path=/goods/**    
  application:
    name: gateway
management:
  endpoints:
    web:
      exposure:
        include: "*"

Sentinel控制檯

通過Sentinel原始碼專案啟動Sentinel控制檯,是一個Spring Boot專案

訪問本地Sentinel控制檯介面http://localhost:8080/,預設埠是8080,預設使用者密碼sentinel/sentinel,由於暫時沒有做持久化功能,所以剛進來是內容是空的

微服務啟動

啟動閘道器、使用者、商品三個微服務,使用者微服務埠為8081,商品微服務埠為8082,閘道器微服務埠為8083

先不通過閘道器直接訪問goods微服務http://localhost:8082/goods/1,走http方式呼叫介面

通過閘道器路由配置我們訪問使用者服務http://localhost:8083/users/users/1 ,訪問結果正確

繼續訪問商品介面服務http://localhost:8083/goods/goods/1 ,訪問結果正確

訪問商品服務呼叫使用者服務 http://localhost:8083/goods/goods/user ,訪問結果正確

Sentinel控制檯設定下限流規則,針對goods/goods/user 這個觸點鏈路進行流控設定

當我們每秒訪問在兩次內還是會訪問正常,我們連續快速按F5重新整理則會出現Blocked by Sentinel: FlowException,這個是預設Sentinel返回限流提供,我們也可以實現自定義限流提示