主流微服务一站式解决方案Spring Cloud Alibaba入门看这篇就足够了
阅读原文时间:2021年12月17日阅读:1

学习路线

**本人博客网站 **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

系统监控层:分布式链路追踪、基于容器化的监控和告警

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返回限流提供,我们也可以实现自定义限流提示