Teach you to draw architecture diagrams with code

ChatGPT has been soaring for 160 days, and the world is no longer what it used to be.

A new artificial intelligence Chinese website https://ai.weoknow.com
updates the available chatGPT resources available in China every day


1 Introduction

This article will introduce you to a concise and clear software architecture visualization model - C4 model, and teach you how to use code to draw a beautiful C4 architecture diagram.

After reading this article, the architecture diagram drawn by the reader will look like this:

Note: The legend is only used as a drawing example, and its completeness and feasibility are not guaranteed.

2. C4 model

2.1 Overall introduction of C4 model

C4 is a solution for software architecture visualization. Architectural visualization refers to the use of legends to accurately, clearly and beautifully represent the software architecture design. Architecture visualization is not to guide developers on how to design architecture, but to guide developers to express architecture design and produce concise and intuitive architecture diagrams.

There are many methods for architectural visualization, the mainstream ones are "4+1" view model and C4 model. The view model describes the architecture itself. After the architecture is determined, no matter what model is used to express it, it should be essentially the same, and there is no distinction between good and bad.

The C4 model is an easy-to-learn, developer-friendly software architecture illustration method. The C4 model does not stipulate the use of specific graphics or specific modeling languages ​​to draw diagrams, so users can generate architecture diagrams very flexibly.

The C4 model divides the system into four layers of views: System Context, Containers, Components, and Code from top to bottom. Each layer is the improvement and expansion of the previous layer, and the system is described layer by layer, as shown in the figure below.


2.2 System Context diagram

The System Context (system context) view is located at the top layer and is the starting point of the software system architecture diagram, expressing the overall picture of the system. The System Context view focuses on the system boundaries, system-related users, other supporting systems, and interactions with the system. This layer does not go into specifics such as technology choices, protocols, deployment scenarios, and other low-level details, so System Context is a good way to introduce the system to non-technical people.

Role: Clearly demonstrate the system to be built, the users, and the existing IT infrastructure.

Scope: The core system to be described and its related users and supporting systems, and other systems unrelated to the core system should not appear. For example, if we want to describe a taxi-hailing system, we should not draw unrelated pharmacy systems into it, and we must ensure that a System Context has only one software system to be described.

Main elements: the software system to be described within the Context.

Supporting elements: People (such as users, actors, roles, or roles) and external dependent systems that are directly related in scope to the software system in the primary element. Often, these externally dependent systems reside outside the boundaries of our own software systems.

Target Audience: Everyone, both technical and non-technical, inside and outside of the software development team.

Recommended for most teams: Yes.

Example:

This is the system context diagram of the online banking system. It shows who is using it, and what other software systems are related to that system. The online banking system is the system to be built. Individual customers of the bank use the online banking system to check their bank account information and make payments. The online banking system itself uses the bank's existing mainframe banking system to do this, and uses the bank's existing email system to send emails to customers.

legend:

2.3 Container diagram

The Container (container) view is a magnification of the System Context and a supplement to the details of the System Context.

Note that the container here does not refer to container middleware such as Docker. The scope of a Container's description is a single runnable/deployable unit. Containers generally refer to applications and dependent middleware, such as server-side web applications, single-page applications, desktop applications, mobile applications, database architectures, file systems, Redis, ElasticSeach, MQ, etc.

Containers show the high-level shape of the software architecture and the division of responsibilities between containers within the system.

At the Container level, it also shows the main technology selection of the system and the communication and interaction between containers.

Function: Show the overall development boundary of the system, reflect high-level technology selection, and expose the division of labor and interaction between containers in the system.

Scope: A single software system, focusing on the application composition within the system.

Main elements: containers within the software system, such as Spring Boot packaged applications, MySQL databases, Redis, MQ, etc.

Supporting elements: People who work directly with containers and external dependent systems.

Intended Audience: Technical staff inside and outside of the software development team, including software architects, developers, and operations/support staff.

Recommended for most teams: Yes.

Note: The Container view does not account for deployment scenarios, clustering, replication, failover, etc. Deployment-related views will be displayed through the Deployment view.

Example:

The online banking system (the system in the System Contenxt has been expanded at this time, so it is represented by a dashed box) consists of five containers: server-side Web application, single-page application, mobile application, server-side API application, and database.

  • The web application is a Java/Spring MVC web application that serves only the static content (HTML, CSS, and JS) that makes up a single-page application.

  • The Single Page Application is an Angular application that runs in the customer's web browser and is a front end to the online banking functionality.

  • Customers can also use a cross-platform Xamarin mobile application to access online banking.

  • Both the single page application and the mobile application use a JSON+HTTPS API provided by another Java/Spring MVC application running on the server.

  • The API application fetches user information from a relational database.

  • The API application also uses a proprietary XML/HTTPS interface to communicate with existing mainframe banking systems to obtain information about bank accounts or to perform transactions.

  • If the API application needs to send emails to customers, it will also use the existing email system.

The legend of the container diagram is as follows, which mainly introduces the legend of database, APP and browser.

2.4 Component diagram

Zooming in on a single container reveals the components inside that container. The Component view shows how a container is made up of many "components", what each component is, their responsibilities and technical implementation details.

Function: It shows the internal composition and division of labor of the executable container, which can directly guide the development.

Scope: Single container.

Main elements: Components within the scope of the container, usually Dubbo interface, REST interface, Service, Dao, etc.

Supporting elements: People and external dependent systems directly connected to the container.

Target Audience: Software architects and developers.

Recommended for most teams: Components are used to guide development and created when needed.

Example:

legend:

2.5 Code diagram

Zoom in on the component view to get the Code view (code view) of the component.

Code view generally adopts UML class diagram, ER diagram, etc. The Code view is an optional level of detail that can usually be generated on-demand by tools such as IDEs. This level of detail is not recommended for anything but the most important or complex components.

Today, when focusing on agile development, it is generally not recommended to produce Code view.

Scope: Individual components.

Primary Elements: Code elements (such as classes, interfaces, objects, functions, database tables, etc.) within scoped components.

Target Audience: Software architects and developers.

Recommended for most teams: No, most IDEs can generate this level of detail on demand.

2.6 System Landscape diagram

The C4 model provides a static view of a single software system. Whether it is System Context, Container, or Component, they are all described for a single software system, but in reality the software system does not exist in isolation. To describe how all these software systems fit together with other systems in a given enterprise, organization, department, etc., C4 employs the extended view System Landscape.

The system landscape diagram is actually just a system context diagram (System Context diagram) of a software system without specific attention, and the software systems in the system landscape diagram can be analyzed in depth using C4.

Scope of application: enterprises/organizations/departments/etc.

Main elements: People and software systems relevant to the selected scope.

Target Audience: Technical and non-technical people both inside and outside of the software development team.

Example:

legend:

2.7 Dynamic diagram

Dynamic diagrams are used to show how elements in a static model work together at runtime. Dynamic diagrams allow free arrangement of diagram elements and indicate the order of execution through numbered arrows.

Scope: Specific features, stories, use cases, etc.

Main elements and supporting elements: According to actual needs, they can be software systems, containers or components.

Target Audience: Technical and non-technical people both inside and outside of the software development team.

Example:

legend:

2.8 Deployment diagram

A Deployment diagram is used to illustrate the deployment scenario of an instance of a software system (or container) in a static model in a given environment (such as production, test, staging, development, etc.).

C4's deployment diagram is based on the UML deployment diagram, but is slightly simplified to highlight the mapping between containers and deployment nodes.

A deployment node representation represents where a software system/container instance runs, similar to physical infrastructure (such as physical servers or appliances), virtualized infrastructure (such as IaaS, PaaS, virtual machines), containerized infrastructure (such as Docker containers), Execution environment (e.g. database server, Java EE web/application server, Microsoft IIS), etc. Deployment nodes can be nested or include infrastructure nodes such as DNS services, load balancers, firewalls, etc.

Feel free to use icons provided by Amazon Web Services, Azure, etc. in your deployment diagrams, just make sure that any icons used are included in the legend without ambiguity.

Scope: One or more software systems in a single deployment environment (such as production, staging, development, etc.).

Main elements: deployment nodes, software system instances, and container instances.
Supporting Elements: Infrastructure nodes used to deploy software systems.

Intended Audience: Technologists inside and outside of software development teams; includes software architects, developers, infrastructure architects, and operations/support staff.

Example:

Deployment diagram of the development environment of the online banking system:

legend

Production environment deployment diagram of online banking:

legend

2.9 C4 Model Specification and Review CheckList

In order to ensure the readability of the architecture diagram of the C4 model, the C4 model provides drawing specifications and a CheckList for self-checking.

2.9.1 C4 Model Specification

  • chart

Each diagram should have a title that describes the type and scope of the diagram (eg "System context diagram of my software system").
Every diagram should have a key/legend explaining the symbols used (e.g. shape, color, border style, linetype, arrow, etc.).
Acronyms and abbreviations (business/domain or technical) should be understood by all audiences or explained in diagram keys/legends.

  • element

The type of each element (eg, person, software system, container, or component) should be clearly specified.
Each element should have a short description to provide an "at-a-glance" view of key responsibilities.
Every container and component should have a clearly specified technology.

  • relation

Each line should represent a unidirectional relationship.
Each row should be labeled, with the labeling consistent with the direction and intent of the relationship (e.g. dependencies or data flow). Try to use tags as specific as possible, preferably avoiding single words like "use".
Relationships between containers (usually representing inter-process communication) should have clearly labeled technologies/protocols.

2.9.2 Review Checklist

After the drawing of the C4 model chart is completed, you can conduct a self-examination through the Review Checklist to check whether there are any irregularities. The Review Checklist is made into a web page and can be accessed at https://c4model.com/review/.

3. C4 model architecture diagram code drawing actual combat

3.1 Selection of text drawing tools

There are generally two ways to draw the architecture diagram of the C4 model:

The first is to use drawing tools, which can directly drag and drop elements and adjust styles to produce pictures, such as draw.io, PPT and other tools. The advantage of the drawing tool is that it is very flexible and can meet many detailed requirements; the disadvantage is that it is usually cumbersome to adjust the style of elements.

The second is to use a text-based drawing tool to describe the picture elements according to a certain grammar, and finally automatically render the picture according to the text, such as PlantUML. The advantage of a text-based drawing tool is that drawing is fast, as long as the description file is written according to the grammar, it can be rendered, and the style of the element has been debugged by default; the disadvantage is that the style does not necessarily conform to our aesthetics, and it is inconvenient to adjust.

This article focuses on the second, text-based drawing tools.

There are many text-based drawing tools, such as: structurizr, PlantUML, mermaid, each with its own syntax.

tool grammar How to use address
structurizr DSL Provide web interface rendering pictures, and can generate C4-PlantUML and mermaid code https://structurizr.com/
C4-PlantUML PlantUML VS Code plugin, IntelliJ Idea plugin https://github.com/plantuml-stdlib/C4-PlantUML
mermaid mermaid Markdown plugin, providing Live Editor https://mermaid.js.org/syntax/c4c.html ,Mermaid Live Editor

Since IntelliJ Idea and VS Code are currently very popular among developers, we choose to use C4-PlantUML, combined with VS Code and IntelliJ Idea to draw the C4 model respectively.

For the installation of VS Code environment, see 3.2.

For the installation of IntelliJ Idea environment, see 3.3

3.2 C4-PlantUML installation under VS Code

3.2.1 Install VS Code

Just download and install directly from the official website, and the process is omitted.

3.2.2 Install the PlantUML plugin

Search for PlantUML in the Extensions window of VS Code, and install the PlantUML plug-in.

3.2.3 Configuring VS Code snippets

After installing PlantUML, in order to improve efficiency, we'd better install PlantUML related code snippets.

Open the VS Code menu, the level is Code→Preferences→User Snippets, as shown below:

In the Select Snippets File Or Create Snippets pop-up window, select New Global Snippets file, as shown below:

In the next pop-up window, enter the file name of the Snippets file, as shown below:

Use a browser to open the following link, and paste the text returned by the browser into the VS Code editing area

https://github.com/plantuml-stdlib/C4-PlantUML/blob/master/.vscode/C4.code-snippets

As shown in the picture:

3.2.4 Install Graphviz

If there is a problem with graphics rendering, you will be prompted to install the graphviz library, just go to the graphviz official website to install it. The official website link is as follows:

https://graphviz.gitlab.io/download/

For Mac system, it is recommended to use MacPorts to install.

3.3 C4-PlantUML installation under IntelliJ Idea

3.3.1 Install Ideas

3.3.2 Install the PlantUML Integration plugin

3.3.3 Install code template

Download the IntelliJ live template from the link below.

https://github.com/plantuml-stdlib/C4-PlantUML/blob/master/intellij/c4_live_template.zip

Through the menu path  File | Manage IDE Settings | Import Settings , select the downloaded ZIP file,  c4_live_template.zip, import and restart Idea.

3.4 Case study and C4-PlantUML grammar introduction

The detailed syntax of C4-PlantUML can be found on the official website github project homepage (https://github.com/plantuml-stdlib/C4-PlantUML), and here is only a brief introduction.

3.4.1 Case

Taking the server architecture diagram (Container level) of a recruitment APP as an example to explain, the following is the rendered effect diagram.

The following is the complete plantuml code:

@startuml  
  
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Context.puml  
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml  
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Component.puml

!define SPRITESURL https://raw.githubusercontent.com/rabelenda/cicon-plantuml-sprites/master/sprites    
!define DEVICONS https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/devicons  
!define DEVICONS2 https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/devicons2  
!define FONTAWESOME https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/font-awesome-5  
!include DEVICONS/java.puml  
!include DEVICONS/mysql.puml  
!include DEVICONS2/spring.puml  
!include DEVICONS2/redis.puml  
!include DEVICONS2/android.puml  
!include DEVICONS2/apple_original.puml  
  
title 招聘APP架构图(Container)  
  
Person(P_User, "找工作的APP用户(应聘者)")  
  
System_Boundary(Boundary_APP, "招聘APP系统边界"){  
	Container(C_ANDROID, "安卓移动端", "android", "移动APP安卓端",$sprite="android")  
	Container(C_IOS, "iOS移动端", "iOS", "移动APP iOS端",$sprite="apple_original")  
	Container(C_GATEWAY, "HTTP网关", "Netty", "鉴权、协议转换",$sprite="java")  
	Container(C_GATEWAY_CACHE, "网关缓存", "Redis", "缓存认证凭据",$sprite="redis")  
	Container(C_BFF, "BFF网关", "Spring Boot","整合后端接口",$sprite="spring")  
	Container(C_CERT, "实名认证服务", "Spring Boot", "内部实名认证服务",$sprite="spring")  
	Container(C_BIZ_1, "职位服务", "Spring Boot", "发布、搜索职位",$sprite="spring")  
	Container(C_PAYMENT, "支付服务", "Spring Boot", "内部支付服务",$sprite="spring")  
	ContainerDb(CDB_MYSQL, "职位信息数据库", "MySQL", "持久化职位信息",$sprite="mysql")  
}  
  
System_Ext(OUT_S_CERT, "实名认证服务","对用户进行姓名身份证号实名认证")  
System_Ext(OUT_S_PAYMENT, "第三方支付服务","支持用户使用多种支付方式完成支付")  
  
Rel(P_User, C_ANDROID, "注册登陆投递简历")  
Rel(P_User, C_IOS, "注册登陆投递简历")  
  
Rel(C_ANDROID, C_GATEWAY, "请求服务端","HTTPS")  
Rel(C_IOS, C_GATEWAY, "请求服务端","HTTPS")  
  
Rel_L(C_GATEWAY, C_GATEWAY_CACHE, "读写缓存","jedis")  
Rel(C_GATEWAY, C_BFF, "将HTTP协议转为RPC协议","RPC")  
  
Rel(C_GATEWAY, C_BIZ_1, "将HTTP协议转为RPC协议","RPC")  
Rel(C_GATEWAY, C_PAYMENT, "将HTTP协议转为RPC协议","RPC")  
  
Rel(C_BFF, C_CERT, "通过BFF处理之后,对外暴露接口服务","RPC")  
  
Rel(C_BIZ_1, CDB_MYSQL, "读写数据","JDBC")  
  
Rel(C_CERT, OUT_S_CERT, "对接外部查询实名信息接口","HTTPS")  
Rel(C_PAYMENT, OUT_S_PAYMENT, "对接外部支付系统","HTTPS")  
  
left to right direction  
  
SHOW_LEGEND()  
  
@enduml

3.4.2 PlantUML files

PlantUML files have the puml file extension.

3.4.3 @startuml 和 @enduml

The entire document is wrapped by  @startuml and  @enduml , which is a fixed syntax.

@startuml

@enduml

3.4.4 Notes

Single quotes (i.e.) are used in PlantUML 'as annotation identifiers.

3.4.5 include statement

The first is the include statement of each view of C4. The following statement represents the introduction of Context, Container, and Component views of C4.

!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Context.puml  
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Container.puml  
!include https://raw.githubusercontent.com/plantuml-stdlib/C4-PlantUML/master/C4_Component.puml

Followed by the icon library:

!define SPRITESURL https://raw.githubusercontent.com/rabelenda/cicon-plantuml-sprites/master/sprites    
!define DEVICONS https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/devicons  
!define DEVICONS2 https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/devicons2  
!define FONTAWESOME https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/font-awesome-5  
!include DEVICONS/java.puml  
!include DEVICONS/mysql.puml  
!include DEVICONS2/spring.puml  
!include DEVICONS2/redis.puml  
!include DEVICONS2/android.puml  
!include DEVICONS2/apple_original.puml

Note that there is a define syntax here, first define a logo through **!define**, and then the place where the logo is used will be replaced

!define DEVICONS2 https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/devicons2
!include DEVICONS2/spring.puml
‘ 等价于 !include https://raw.githubusercontent.com/tupadr3/plantuml-icon-font-sprites/master/devicons2/spring.puml

When using icons, you only need to add them in the declaration statement of the element  $sprite="xxx" .

ContainerDb(CDB_MYSQL, "职位信息数据库", "MySQL", "持久化职位信息",$sprite="mysql")

3.4.6 C4 Model Static Elements

Person: The user of the system, which may be a person or another system

System: Represents the system to be built, usually rendered as a blue square.
System_Ext: Represents an existing system, usually rendered as a gray square.
System_Boundary: When a system is expanded into a container, change System to System_Boundary, which represents the boundary of the system, and container elements are placed inside, usually rendered as a dotted box.

Container: The container to be built, usually rendered as a blue square.
Container_Ext: A constructed container, usually rendered as a gray square.
Container_Boundary: After a container is expanded into a component, the Container is changed to Container_Boundary, which represents the boundary of the container, and component elements are placed inside, usually rendered as a dotted frame.

ContainerDb: The database to be built, usually rendered as a blue cylinder.
ContainerQueue: The message queue to be built, usually rendered as a horizontally placed blue cylinder.

Component: The component to be built, usually rendered as a blue square.
Component_Ext: Built components, usually rendered as gray squares.

The syntax for static elements is:

Container(alias, "label", "technology", "description")

alias: is the unique ID of the element in the diagram, and can be referenced by alias in other places, for example,  label: Rel represents
the display name of the element
technology: represents the core technology adopted by the element, including but not limited to development language, framework, communication protocol, etc.
description: represents a brief description of the element

For System_Boundary and Container_Boundary, only alias and label are required, and the curly braces are the child elements within the boundary of the element.

Container_Boundary(alias, "label"){

}

3.4.7 Relational elements of the C4 model

Rel represents the relationship between two elements, its syntax is:

Rel(from_alias, to_alias, "label", "technology")

from_alias is the alias of the start element, to_alias is the alias of the end element, label is used to describe the relationship, and technology represents the technology and communication protocol adopted. For example:

Rel(C_IOS, C_GATEWAY, "请求服务端","HTTPS")

Represents the iOS client to access server resources through the request gateway interface, using HTTPS communication.

Rel It is recommended to mark it out when  drawing  technology.

3.4.8 C4-PlantUML layout

C4-PlantUML provides a variety of automatic layout solutions, we can choose according to actual needs.

  • LAYOUT_TOP_DOWN (): Layout from top to bottom, this layout is adopted by default. As shown below:

  • LAYOUT_LEFT_RIGHT (): From left to right, that is, place elements horizontally. left to right direction It is the syntax of PlantUML, and it can also be used directly.

3.4.9 Legend

By  SHOW_LEGEND() adding a legend.


ChatGPT has been soaring for 160 days, and the world is no longer what it used to be.

A new artificial intelligence Chinese website https://ai.weoknow.com
updates the available chatGPT resources available in China every day

Guess you like

Origin blog.csdn.net/zyqytsoft/article/details/131075859
Recommended