Practical Serverless and Microservices with C# / Практичные бессерверные и микросервисные решения с C#
Год издания: 2025
Автор: Baptista G., Abbruzzese F. / Баптиста Г., Аббруццезе Ф.
Издательство: Packt Publishing
ISBN: 978-1-83664-201-5
Серия: Expert Insight
Язык: Английский
Формат: PDF/EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 472
Описание: Take a realistic look at microservices and distributed systems with the .NET stack to understand the limitations of microservices development through a practical lens
Key Features
Work through common scenarios encountered when developing distributed microservices applications
Understand cost considerations, traffic limits, and time limits surrounding serverless environments
Take full advantage of the synergy between Azure services (Container Apps, Functions, and Aspire) and .NET code
Book Description
From the authors of the Software Architecture with C# and .NET series comes this practical and grounded showcase of microservices using the .NET stack.
Written for .NET developers entering the world of modern cloud and distributed applications, it shows you when microservices and serverless architectures are the right choice for building scalable enterprise solutions and when they’re not. You’ll gain a realistic understanding of their use cases and limitations. Rather than promoting microservices as a one-size-fits-all solution, it encourages thoughtful adoption based on real-world needs.
Following a brief introduction and important setup, the book helps you prepare for practical application through examples such as a ride-sharing website. You’ll work with Docker, Kubernetes, Azure Container Apps, and the new .NET Aspire with considerations for security, observability, and cost management. The book culminates in a complete event-driven application that brings together everything you've covered.
By the end of the book, you’ll have a well-rounded understanding of cloud and distributed .NET—viewed through the lens of two industry veterans.
What you will learn
Set up serverless environments in Azure for developing and debugging
Design reliable communication and computation across microservices
Explore Azure Functions in depth and use triggers for IoT and background tasks
Use Azure Container Apps to simplify the creation and management of containers
Apply best practices to secure a microservices application
Accurately assess and calculate costs and usage limits in serverless solutions
Who this book is for
This book is for engineers and senior software developers looking to advance into modern cloud and distributed applications. It helps professionals evolve their knowledge of microservices and serverless architecture to get the best of both architectural models. Prior experience with C#/.NET and the Microsoft Stack (Entity Framework and ASP.NET Core) is required to get the most out of this book.
Реалистично взгляните на микросервисы и распределенные системы со стеком .NET, чтобы понять ограничения разработки микросервисов через практическую призму.
Основные характеристики
Проработайте распространенные сценарии, возникающие при разработке приложений для распределенных микросервисов
Разберитесь с затратами, ограничениями трафика и сроками, связанными с бессерверными средами
Воспользуйтесь всеми преимуществами взаимодействия между сервисами Azure (контейнерными приложениями, функциями и Aspire) и кодом .NET
Описание книги
Эта практичная и обоснованная демонстрация микросервисов, использующих стек .NET, подготовлена авторами серии "Архитектура программного обеспечения с использованием C# и .NET".
Написанная для .NET-разработчиков, начинающих осваивать мир современных облачных и распределенных приложений, она показывает, когда микросервисы и бессерверные архитектуры являются правильным выбором для создания масштабируемых корпоративных решений, а когда - нет. Вы получите реалистичное представление об их вариантах использования и ограничениях. Вместо того чтобы продвигать микросервисы как универсальное решение, оно поощряет продуманное внедрение, основанное на реальных потребностях.
После краткого введения и важных настроек книга поможет вам подготовиться к практическому применению на примерах, таких как веб-сайт для совместного использования поездок. Вы будете работать с Docker, Kubernetes, Azure Container Apps и новым .NET Aspire, уделяя особое внимание безопасности, наблюдаемости и управлению затратами. Завершает книгу полноценное приложение, управляемое событиями, в котором собрано воедино все, о чем вы рассказывали.
К концу книги у вас будет полное представление об облачных технологиях и распределенной .NET, рассмотренных глазами двух ветеранов отрасли.
Что вы узнаете
Настройте бессерверные среды в Azure для разработки и отладки
Спроектируйте надежную связь и вычисления между микросервисами
Подробно изучите функции Azure и используйте триггеры для IoT и фоновых задач
Используйте контейнерные приложения Azure для упрощения создания контейнеров и управления ими
Применяйте рекомендации по обеспечению безопасности приложения для микросервисов
Точно оценивайте и рассчитывайте затраты и ограничения на использование в бессерверных решениях
Для кого предназначена эта книга
Эта книга предназначена для инженеров и ведущих разработчиков программного обеспечения, стремящихся освоить современные облачные технологии и распределенные приложения. Она помогает профессионалам расширить свои знания о микросервисах и бессерверной архитектуре, чтобы использовать лучшее из обеих архитектурных моделей. Чтобы извлечь максимальную пользу из этой книги, необходим предварительный опыт работы с C#/.NET и Microsoft Stack (Entity Framework и ASP.NET Core).
Примеры страниц (скриншоты)
Оглавление
Preface xvii
Chapter 1:
Demystifying Serverless Applications 1
Technical requirements ...................................................................................................... 2
What is serverless? .............................................................................................................. 2
Is serverless a way to deliver microservices? ....................................................................... 3
How does Microsoft Azure present serverless? .................................................................... 3
Creating your first serverless app in Azure .......................................................................... 5
Understanding the triggers available in Azure Functions ................................................... 9
Coding with Azure Functions ............................................................................................ 10
Coding Azure functions using VS Code .............................................................................. 10
Coding Azure functions using Visual Studio ..................................................................... 18
Summary .......................................................................................................................... 22
Questions .......................................................................................................................... 22
Further reading ................................................................................................................. 23
Chapter 2:
Demystifying Microservices Applications 25
The rise of Service-Oriented Architectures (SOAs) and microservices .............................. 26
The rise of SOA • 26
Toward microservices architectures • 27
The definition and organization of microservices architectures ....................................... 30
A definition of microservices architectures • 30
Domain of expertise and microservices • 31
Replicable microservices • 32
Splitting microservices development among different teams • 32
Microservices, interfaces, and communication protocols • 32
Just the interfaces of the logical microservices are public • 33
Microservices organization • 33
Car-sharing example • 39
When is it worth adopting microservices architectures? ................................................... 40
Microservices common patterns ....................................................................................... 42
Resilient task execution • 42
Efficacious handling of asynchronous communication • 44
Event-based communications • 46
Interfacing the external world • 47
Summary .......................................................................................................................... 49
Questions .......................................................................................................................... 49
Further reading ................................................................................................................. 50
Chapter 3:
Setup and Theory: Docker and Onion Architecture 53
Technical requirements .................................................................................................... 54
The Onion Architecture ..................................................................................................... 55
The Domain layer • 57
Application services • 63
Queries • 63
Commands • 64
Domain events • 67
A solution template based on the Onion Architecture ....................................................... 70
Matching aggregates and ORM entities • 77
A complete solution based on the Onion Architecture • 80
Containers and Docker ..................................................................................................... 84
Docker Desktop: a simple example • 89
A few more Docker commands and options • 92
Visual Studio support for Docker • 94
Summary .......................................................................................................................... 97
Questions .......................................................................................................................... 97
Further reading ................................................................................................................. 98
Chapter 4:
Azure Functions and Triggers Available 99
Technical requirements .................................................................................................... 99
HTTP trigger ................................................................................................................... 100
Advantages, disadvantages, and when to use the HTTP trigger ...................................... 100
Car-sharing HTTP trigger example • 102
Advantages, disadvantages, and when to use the Azure SQL trigger ............................... 103
Car-sharing SQL trigger example • 103
Advantages, disadvantages, and when to use the Cosmos DB trigger .............................. 106
Car-sharing Cosmos DB trigger example • 107
Azure Service Bus trigger .................................................................................................. 111
Comparison with the Kafka trigger and the RabbitMQ trigger • 112
Car-sharing example with the Azure Service Bus trigger • 112
Summary ......................................................................................................................... 114
Questions ......................................................................................................................... 115
Further reading ................................................................................................................ 117
Chapter 5:
Background Functions in Practice 119
Technical requirements ................................................................................................... 119
Timer trigger .................................................................................................................. 120
Publishing your functions ................................................................................................ 122
Monitoring your functions .............................................................................................. 127
Advantages, disadvantages, and when to use Azure timer triggers • 129
Car-sharing timer trigger example • 129
Blob trigger ...................................................................................................................... 131
Advantages, disadvantages, and when to use Blob storage triggers • 132
Blob trigger implementation using Event Grid ................................................................ 133
Car-sharing Blob storage trigger example • 138
Queue storage trigger ..................................................................................................... 140
Advantages, disadvantages, and when to use queue storage triggers • 140
Car-sharing queue storage trigger example • 141
Summary ......................................................................................................................... 143
Questions ......................................................................................................................... 143
Further reading ................................................................................................................ 145
Chapter 6:
IoT Functions in Practice 147
Technical requirements ................................................................................................... 147
Enabling IoT in Azure ...................................................................................................... 147
Connecting IoT Hub with Azure Functions ...................................................................... 153
Car-sharing IoT example ................................................................................................. 156
Summary ......................................................................................................................... 163
Questions ........................................................................................................................ 164
Further reading ............................................................................................................... 166
Chapter 7:
Microservices in Practice 167
Technical requirements .................................................................................................. 168
The route-planning microservice of the car-sharing application ................................... 168
Microservice specifications • 169
Handling security and authorization • 170
Creating the Visual Studio solution • 172
Microservice basic design ................................................................................................ 174
The message broker: RabbitMQ • 174
Input communication • 177
Output communication • 182
Ensuring that messages are processed in the proper order • 184
Designing Docker image environment parameters • 186
The microservice main service • 189
EasyNetQ’s RPC facilities • 195
Other required hosted services • 196
Ensuring resilient task execution with Polly .................................................................. 201
The Polly library • 201
Adding Polly to our project • 203
From abstraction to implementation details .................................................................. 204
The domain layer • 204
The route request aggregate • 206
The route offer aggregate • 208
The output queue item aggregate • 211
The database driver • 212
The IOutputQueueRepository implementation • 214
The IRouteRequestRepositoryimplementation • 216
The IRouteOfferRepository implementation • 219
Creating migrations and databases • 220
The application services: Defining all command and event handlers • 222
Coding all event handlers • 229
Summary ......................................................................................................................... 231
Questions ...................................................................................................................... 232
Further reading ............................................................................................................... 233
Chapter 8:
Practical Microservices Organization with Kubernetes 235
Technical requirements .................................................................................................. 236
Introduction to orchestrators and their configuration .................................................... 237
.yaml files • 238
Kubernetes basics ........................................................................................................... 240
Interacting with Kubernetes: Kubectl, Minikube, and AKS ............................................. 243
Creating an Azure Kubernetes cluster • 246
Configuring your application in Kubernetes ................................................................... 249
Dynamic provisioning of permanent disk space • 257
ReplicaSets, Deployments, and their services • 261
StatefulSets and Headless Services • 268
Scaling and autoscaling • 272
Resource metrics • 274
Pod metrics • 275
Object metrics • 275
Running your microservices on Kubernetes .................................................................... 276
Organizing all deployment environments • 277
Database engine and database installation • 278
Container registries • 279
Message broker installation • 281
Debugging techniques • 283
Testing the route-matching worker microservice • 286
Advanced Kubernetes configuration ............................................................................... 297
Secrets • 297
Readiness, liveness, and startup probes • 300
Ingresses • 302
Testing Ingresses with Minikube • 306
Using an NGNIX-based Ingress in AKS • 308
Summary ........................................................................................................................ 310
Questions ....................................................................................................................... 310
Further reading ................................................................................................................ 311
Chapter 9:
Simplifying Containers and Kubernetes: Azure Container Apps,
and Othert Tools 313
Technical requirements ................................................................................................... 314
Tools for simplifying Kubernetes clusters usage and administration ............................... 315
Helm and Helm charts • 315
Kubernetes graphic UIs • 318
Kubernetes administrative tools • 321
Development environments based on Kubernetes • 326
Azure Container Apps basics and plans ........................................................................... 326
Consumption-only and workload profiles • 329
Application versioning • 330
Interacting with Azure Container Apps • 332
Deploying your microservice application with Azure Container Apps ............................ 332
Basic commands and operativity • 332
Application configuration options and the .yaml format • 338
Container configuration • 341
The ingress configuration • 342
Volume definition and allocation • 345
Associating an Azure identity to your application • 347
Summary ........................................................................................................................ 349
Questions ........................................................................................................................ 349
Further reading ............................................................................................................... 350
Chapter 10:
Security and Observability for Serverless and Microservices Applications 353
Application Security Best Practices ................................................................................. 354
Network Security • 354
Data Security • 355
Authentication and Authorization • 357
JSON Web Tokens • 357
OAuth 2.0 and OpenID Connect (OIDC) • 361
Securing Dependencies • 365
Kubernetes and Azure Container Apps Security .............................................................. 366
Kubernetes network security • 366
Azure Container Apps Network Security • 372
Kubernetes User Security • 372
Azure Container Apps User Security • 378
Threat Detection and Mitigation .................................................................................... 378
Threats • 378
Event Injection • 378
Privilege Escalation • 379
Denial of Service (DoS) Attacks • 379
Man-in-the-Middle (MitM) Attacks • 379
Code Injection • 380
Detection and Mitigation with Web Application Firewalls • 380
Observability for Serverless and Microservices ............................................................... 382
Logging • 382
Metrics • 383
Tracing • 384
Centralized Observability with Azure Monitor • 385
Summary ....................................................................................................................... 387
Questions ........................................................................................................................ 388
Further reading ............................................................................................................... 392
Chapter 11:
The Car Sharing App 395
General architecture description .................................................................................... 395
Microservices involved • 396
Authorization microservice • 397
CarSharer microservice • 397
CarRequests microservice • 398
RoutesPlanning microservice • 398
Email microservice • 398
The demonstration code ................................................................................................. 399
Summary ........................................................................................................................ 401
Further reading ............................................................................................................... 401
Chapter 12:
Simplifying Microservices with .NET Aspire 403
Technical requirements ................................................................................................. 404
.NET Aspire features and services ................................................................................... 404
Service discovery and its role in .NET Aspire. • 408
Resource integration and automatic resource configuration • 412
Application telemetry • 415
Configuring microservices and resources ........................................................................ 416
Azure Functions integration • 419
Using .NET Aspire in practice ........................................................................................... 421
RabbitMQ integration • 427
Deploying a .NET Aspire project ..................................................................................... 428
Summary ........................................................................................................................ 430
Questions ........................................................................................................................ 430
Further reading ................................................................................................................ 431
Other Books You May Enjoy 435
Index 439