El término Microservicios se pone de moda en 2014 y desde entonces está calando mucho en la industria de desarrollo de software. Con la salida al mercado de NET Core 2.0 y su facilidad de despliegue a diferentes sistemas operativos como Linux y Windows; se está popularizando su adopción en diferentes plataformas Cloud.
En esta presentación mostramos aspectos puntuales de Microservicios con NET Core y cuán sencillo es crear microservicios con Azure Service Fabric.
4. Agenda
• La importancia de DDD.
• Introducción a Microservicios.
• Monolito vs Microservicios.
• Azure Service Fabric.
• Conclusiones y recomendaciones.
¿QUESTIONS?
#MicroserviciosBelatrix
5. La importancia de DDD ¿QUESTIONS?
#MicroserviciosBelatrix
Domain-Driven Design es una metodología y un proceso de diseño de Sistemas Complejos.
Domain
Bounded
Context
Single
Responsability
Principle
Ubiquitous
Language
6. La importancia de DDD ¿QUESTIONS?
#MicroserviciosBelatrix
• Código alineado con el negocio.
• Favorece la reutilización de código.
• Mínimamente acoplado.
7. Introducción a Microservicios ¿QUESTIONS?
#MicroserviciosBelatrix
"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
Fuente: http://martinfowler.com/microservices/
8. Introducción a Microservicios ¿QUESTIONS?
#MicroserviciosBelatrix
Los microservicios, también conocidos como la arquitectura de microservicios, son un estilo
arquitectónico que estructura una aplicación como una colección de servicios que son:
• Altamente mantenible y comprobable
• Débilmente acoplado
• Independientemente desplegable
• Organizado en torno a capacidades empresariales.
La arquitectura de microservicio permite la entrega / implementación continua de aplicaciones
grandes y complejas. También permite a una organización evolucionar su stack tecnológico.
Fuente: https://microservices.io/
9. Monolito vs Microservicios ¿QUESTIONS?
#MicroserviciosBelatrix
Docker
Monolith App
Presentation Layer
Business Layer
Data Layer
What’s the Ubiquitous Language?
In short, DDD is primarily about modeling a Ubiquitous Language in an explicitly Bounded Context.
While true, that probably wasn’t the most helpful description that I could provide. Let me break this down for you.
First, a Bounded Context is a semantic contextual boundary. This means that within the boundary each component of the software model has a specific meaning and does specific things. The components inside a Bounded Context are context specific and semantically motivated. That’s simple enough.
the Ubiquitous Language reflects the mental model of the experts of the business domain you are working in.
The heart of software is its ability to solve domain-related problems for its user.
Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software
Cual es el foco de DDD?
El foco para DDD son los dominios complejos que cuentan con dificultades de comunicación entre los expertos técnicos y los expertos del negocio, haciendo que los conceptos o ideas de la aplicación sean confusas.
============
Entity
An object that is not defined by its attributes, but rather by a thread of continuity and its identity.
Example: Most airlines distinguish each seat uniquely on every flight. Each seat is an entity in this context. However, Southwest Airlines, EasyJet and Ryanair do not distinguish between every seat; all seats are the same. In this context, a seat is actually a value object.
Value object
An object that contains attributes but has no conceptual identity. They should be treated as immutable.
Example: When people exchange business cards, they generally do not distinguish between each unique card; they are only concerned about the information printed on the card. In this context, business cards are value objects.
Aggregate
A collection of objects that are bound together by a root entity, otherwise known as an aggregate root. The aggregate root guarantees the consistency of changes being made within the aggregate by forbidding external objects from holding references to its members.
Example: When you drive a car, you do not have to worry about moving the wheels forward, making the engine combust with spark and fuel, etc.; you are simply driving the car. In this context, the car is an aggregate of several other objects and serves as the aggregate root to all of the other systems.
Domain Event
A domain object that defines an event (something that happens). A domain event is an event that domain experts care about.
Service
When an operation does not conceptually belong to any object. Following the natural contours of the problem, you can implement these operations in services. See also Service (systems architecture).
Repository
Methods for retrieving domain objects should delegate to a specialized Repository object such that alternative storage implementations may be easily interchanged.
Factory
Methods for creating domain objects should delegate to a specialized Factory object such that alternative implementations may be easily interchanged.
Evans's book is divided into four parts:- Putting the domain model to work- Model building blocks-driven design- Refactoring to deeply understand the model- Strategic designAll the preceding parts can be applied to microservices. Model building blocks-driven design and refactoring to deeply understand the model internally applies to microservices,that is, the code itself. The others can be applied either internally in the software, but can also be used to design microservices and their signatures.The first part is emphatic about the need to use ubiquitous language for communication between those responsible for the business, and the engineering team responsible for thedevelopment. This language consists of terms that are part of everyday conversations between business experts and development teams. Everyone should use the same terms inspoken language, the source code, and the signing of microservices. This means that when the business specialist says, The home page should seek breaking news with the title anddescription the ubiquitous language applied in the code will be represented as follows:- Microservice news- Endpoint recent news- Payload with attribute title and descriptionThis type of communication will mitigate errors in understanding requirements and maintain the general knowledge about application unison. Another important point is that,with the ubiquitous language, identifying areas is simpler because, as interactions have standardized terms, a word may indicate something new.The fourth part will clarify the boundaries of a microservice and ease of management between the parties. Besides having a ubiquitous language used in the development of aconsistent and adequate microservice, some strategies are necessary for dealing with complex systems, where multiple pieces of software (developed by several teams) interact.Delimit the context in which each team works and what is the degree of interaction between these teams and these contexts? Of the many tools that the DDD provides us, three are moreprominent for efficient microservices:Context maps: These are the communication paths between microservices with appropriate interactions between microservices teams. After the analysis of theareas are already defined, the team can choose to be dependent on another team for domain language.Anti-corruption layer (ACL): This is the function that translates foreign concepts for an internal model to provide loose coupling between the domains.Interchange context: This provides an environment for both teams and discusses the meaning of each foreign term and translates the languages of microservices.
The term microservices was used for the first time in mid-2011 at a workshop on software architects. In March 2012, James Lewis presented some of his ideas about microservices. Bythe end of 2013, various groups from the IT industry started having discussions about microservices, and by 2014, they had become popular enough to be considered a serious contender for large enterprises.
"El estilo arquitectónico de microservicio es un enfoque para desarrollar una aplicación única como un conjunto de pequeños servicios, cada uno ejecutándose en su propio proceso y comunicándose con mecanismos ligeros, a menudo una API de recursos HTTP. Estos servicios se basan en capacidades empresariales y se implementan de forma independiente. Maquinaria de despliegue automatizado.
Hay un mínimo de administración centralizada de estos servicios, que puede escribirse en diferentes lenguajes de programación y utilizar diferentes tecnologías de almacenamiento de datos ".
The term microservices was used for the first time in mid-2011 at a workshop on software architects. In March 2012, James Lewis presented some of his ideas about microservices. Bythe end of 2013, various groups from the IT industry started having discussions about microservices, and by 2014, they had become popular enough to be considered a serious contender for large enterprises.
Articulo de Zhamak Dehghani, en el sitio de Martin Fowler
The Journey Guide
Warm Up with a Simple and Fairly Decoupled Capability
Minimize Dependency Back to the Monolith
Split Sticky Capabilities Early
Decouple Vertically and Release the Data Early
Decouple What is Important to the Business and Changes Frequently
Decouple Capability and not Code
Go Macro First, then Micro
Migrate in Atomic Evolutionary Steps
Calentamiento con una capacidad simple y bastante desacoplada
Minimiza la dependencia de regreso al monolito
Dividir las capacidades adhesivas temprano
Desacoplar verticalmente y liberar los datos temprano
Desacople lo que es importante para el negocio y los cambios con frecuencia
Capacidad de desacoplamiento y no código
Primero macro, luego micro
Migrar en pasos evolutivos atómicos
Azure Service Fabric es una plataforma de sistemas distribuidos que facilita el empaquetado, la implementación y la administración de microservicios y contenedores escalables y confiables.
Service Fabric también aborda los desafíos importantes en el desarrollo y la administración de aplicaciones nativas en la nube.
Los desarrolladores y administradores pueden evitar problemas complejos de infraestructura y centrarse en su lugar en las cargas de trabajo más exigentes y críticas que son escalables, confiables y fáciles de administrar. Service Fabric representa la plataforma de próxima generación para crear y administrar estas aplicaciones de clase empresarial, escala de nube y nivel 1 que se ejecutan en contenedores.
Principales capacidades
Usando Service Fabric, puede:
Implementar en Azure o en centros de datos locales que ejecutan Windows o Linux con cero cambios de código. Crear una vez e implementar en cualquier clúster de Service Fabric.
Desarrollar aplicaciones escalables que están compuestas por microservicios mediante los modelos de programación de Service Fabric, contenedores o cualquier código.
Desarrollar microservicios con estado y sin estado que desean de alta confianza. Simplificar el diseño de su aplicación, mediante microservicios con estado.
Usar el novedoso modelo de programación Reliable Actors para crear objetos de nube con estado y código autónomo.
Implementar y orquestar contenedores que incluyen contenedores de Windows y de Linux.Service Fabric es un orquestador de contenedores, con estado y reconocimiento de datos.
Implementar aplicaciones en segundos, con una elevada densidad de cientos o miles de aplicaciones o contenedores por máquina.
Implementar versiones diferentes de la misma aplicación en paralelo, y actualizar cada una por separado.
Administrar el ciclo de vida de sus aplicaciones sin tiempo de inactividad, incluidas las actualizaciones de última hora y las que no lo son.
Escalar o reducir horizontalmente el número de nodos en un clúster. Según se escalan los nodos, las aplicaciones se escalan automáticamente.
Supervisar y diagnosticar el estado de sus aplicaciones y establecer directivas para realizar reparaciones automáticas.
Observar al equilibrador de recursos orquestar la redistribución de aplicaciones en todo el clúster. Service Fabric se recupera de los errores y optimiza la distribución de la carga según los recursos disponibles.
Que es un Reliable Service? Se pueden pensar como aplicaciones de Windows o aplicaciones de consola.
* Stateful Service: Transactional Replicate the storage.
* Stateless Service:
* Actors:
Reliable Actors: Implementa el modelo de Diseño de Actores.
Guest Executable:
Reliable Service vs Normal App:
Ambos de Facil escritura.
Con muchas librerias de opciones (en el caso de Reliable Service solo de 64 bits)
No hay curva de aprendizaje (Reliable Service: Pequeña curva de aprendizaje)
Reliable Service:
Acceso Azure Service Frabic API
Azure Service Frabic Plugable communication model (HTTP, TCP, Websockets o lo que decidas usar)
Acceso a Reliable Storage