SlideShare una empresa de Scribd logo
1 de 53
Descargar para leer sin conexión
@crichardson
Building microservices with
Scala, functional domain
models and Spring Boot
Chris Richardson
Author of POJOs in Action
Founder of the original CloudFoundry.com
@crichardson
chris@chrisrichardson.net
http://plainoldobjects.com
@crichardson
Presentation goal
Share my experiences with building an
application using Scala, functional domain
models, microservices, event sourcing,
CQRS, and Spring Boot
@crichardson
About Chris
@crichardson
About Chris
Founder of a buzzword compliant (stealthy, social, mobile,
big data, machine learning, ...) startup
Consultant helping organizations improve how they
architect and deploy applications using cloud, micro
services, polyglot applications, NoSQL, ...
@crichardson
Agenda
Why build event-driven microservices?
Overview of event sourcing
Designing microservices with event sourcing
Implementing queries in an event sourced application
Building and deploying microservices
@crichardson
Let’s imagine that you are
building a banking app...
@crichardson
Domain model
Account
balance
open(initialBalance)
debit(amount)
credit(amount)
TransferTransaction
fromAccountId
toAccountId
amount
@crichardson
Tomcat
Traditional application
architecture
Browser/
Client
WAR/EAR
RDBMS
Customers
Accounts
Transactions
BankingBanking UI
develop
test
deploy
Simple to
Load
balancer
scale
Spring MVC
Spring
Hibernate
...
HTML
REST/JSON
@crichardson
Problem #1: monolithic
architecture
Intimidates developers
Obstacle to frequent deployments
Overloads your IDE and container
Obstacle to scaling development
Requires long-term commitment to a technology stack
@crichardson
Solution #1: use a microservice
architecture
Banking UI
Account
Management Service
Transaction
Management Service
Account
Database
Transaction
Database
Standalone
services
@crichardson
Problem #2: relational
databases
Scalability
Distribution
Schema updates
O/R impedance mismatch
Handling semi-structured data
@crichardson
Solution #2: use NoSQL
databases
Avoids the limitations of RDBMS
For example,
text search Solr/Cloud Search
social (graph) data Neo4J
highly distributed/available database Cassandra
...
@crichardson
But now we have problems
with data consistency!
@crichardson
Problem #3: Microservices =
distributed data management
Each microservice has it’s own database
Some data is replicated and must be kept in sync
Business transactions must update data owned by
multiple services
Tricky to implement reliably without 2PC
@crichardson
Problem #4: NoSQL =
ACID-free, denormalized databases
Limited transactions, i.e. no ACID transactions
Tricky to implement business transactions that update
multiple rows, e.g. http://bit.ly/mongo2pc
Limited querying capabilities
Requires denormalized/materialized views that must be
synchronized
Multiple datastores (e.g. DynamoDB + Cloud Search )
that need to be kept in sync
@crichardson
Solution to #3/#4: Event-based
architecture to the rescue
Microservices publish events when state changes
Microservices subscribe to events
Synchronize replicated data
Maintains eventual consistency across multiple
aggregates (in multiple datastores)
@crichardson
Eventually consistent money transfer
Message Bus
Transaction management
service
Account
management
service
transferMoney()
Publishes:
Subscribes to:
Subscribes to:
publishes:
TransferTransactionCreatedEvent
AccountDebitedEvent
DebitRecordedEvent
AccountCreditedEvent
TransferTransactionCreatedEvent
DebitRecordedEvent
AccountDebitedEvent
AccountCreditedEvent
@crichardson
But reliably generating events
is difficult
Must atomically update datastore and publish event(s)
Non-option: datastore and message broker use 2PC
Use datastore as message queue
Local transaction updates state and publishes message
See BASE: An Acid Alternative, http://bit.ly/ebaybase
But
Business logic and event publishing code intertwined
Tricky to implement with aggregate-oriented NoSQL database
@crichardson
Agenda
Why build event-driven microservices?
Overview of event sourcing
Designing microservices with event sourcing
Implementing queries in an event sourced application
Building and deploying microservices
@crichardson
Event sourcing
For each aggregate:
Identify (state-changing) domain events
Define Event classes
For example,
Account: AccountOpenedEvent, AccountDebitedEvent,
AccountCreditedEvent
ShoppingCart: ItemAddedEvent, ItemRemovedEvent,
OrderPlacedEvent
@crichardson
Persists events
NOT current state
Account
balance
open(initial)
debit(amount)
credit(amount)
AccountOpened
Event table
AccountCredited
AccountDebited
101 450
Account table
X
101
101
101
901
902
903
500
250
300
@crichardson
Replay events to recreate
state
Account
balance
AccountOpenedEvent(balance)
AccountDebitedEvent(amount)
AccountCreditedEvent(amount)
Events
@crichardson
Aggregate traits
Map Command to Events
Apply event returning
updated Aggregate
@crichardson
Account - command processing
Prevent
overdraft
@crichardson
Account - applying events
Immutable
@crichardson
Request handling in an event-sourced application
HTTP
Handler
Event
Store
pastEvents = findEvents(entityId)
Account
new()
applyEvents(pastEvents)
newEvents = processCmd(SomeCmd)
saveEvents(newEvents)
Microservice A
@crichardson
Event Store publishes events -
consumed by other services
Event
Store
Event
Subscriber
subscribe(EventTypes)
publish(event)
publish(event)
Aggregate
NoSQL
materialized
view
update()
update()
Microservice B
@crichardson
Event Store API
trait EventStore {
def save[T <: Aggregate[T]](entity: T, events: Seq[Event],
assignedId : Option[EntityId] = None): Future[EntityWithIdAndVersion[T]]
def update[T <: Aggregate[T]](entityIdAndVersion : EntityIdAndVersion,
entity: T, events: Seq[Event]): Future[EntityWithIdAndVersion[T]]
def find[T <: Aggregate[T] : ClassTag](entityId: EntityId) :
Future[EntityWithIdAndVersion[T]]
def findOptional[T <: Aggregate[T] : ClassTag](entityId: EntityId)
Future[Option[EntityWithIdAndVersion[T]]]
def subscribe(subscriptionId: SubscriptionId):
Future[AcknowledgableEventStream]
}
In case you are wondering:
Akka Persistence is too Akka-centric
@crichardson
Benefits of event sourcing
Business:
Built in audit log
Enables temporal queries
Technical:
Solves data consistency issues in a Microservice/NoSQL-based architecture:
Atomically save and publish events
Event subscribers update other aggregates ensuring eventual consistency
Event subscribers update materialized views in SQL and NoSQL databases
Eliminates O/R mapping problem
@crichardson
Drawbacks of event sourcing
Weird and unfamiliar
Events = a historical record of your bad design decisions
Handling duplicate events can be tricky
Idempotent commands
Duplicate detection, e.g. track most recently seen event
@crichardson
Agenda
Why build event-driven microservices?
Overview of event sourcing
Designing microservices with event sourcing
Implementing queries in an event sourced application
Building and deploying microservices
@crichardson
The anatomy of a microservice
Event Store
HTTP Request
HTTP Adapter
Aggregate
Event Adapter
Cmd
Cmd
Events
Events
Xyz Adapter
Xyz Request
microservice
@crichardson
Asynchronous Spring MVC
controller
@crichardson
AccountTransactionService
DSL concisely specifies:
1.Creates new TransferTransaction
2.Processes command
3.Applies events
4.Persists events
@crichardson
TransferTransaction
Aggregate
@crichardson
Handling events published
by Accounts
1.Load TransferTransaction
2.Processes command
3.Applies events
4.Persists events
@crichardson
Agenda
Why build event-driven microservices?
Overview of event sourcing
Designing microservices with event sourcing
Implementing queries in an event sourced application
Building and deploying microservices
@crichardson
Let’s imagine that you want
to display an account and it’s
recent transactions...
@crichardson
Displaying balance + recent
transactions
We need to do a “join: between the Account and the corresponding
TransferTransactions
(Assuming Debit/Credit events don’t include other account, ...)
BUT
Event Store = primary key lookup of individual aggregates, ...
Use Command Query Responsibility Separation
Define separate “materialized” query-side views that implement
those queries
@crichardson
Query-side microservices
Event Store
Updater - microservice
View Updater
Service
Events
Reader - microservice
HTTP GET
Request
View Query
Service
View
Store
e.g.
MongoDB
Neo4J
CloudSearch
update query
@crichardson
Persisting account balance and
recent transactions in MongoDB
{
id: "298993498",
balance: 100000,
transactions : [
{"transactionId" : "4552840948484",
"fromAccountId" : 298993498,
"toAccountId" : 3483948934,
"amount" : 5000}, ...
],
changes: [
{"changeId" : "93843948934",
"transactionId" : "4552840948484",
"transactionType" : "AccountDebited",
"amount" : 5000}, ...
]
}
Denormalized = efficient lookup
Transactions that
update the account
The sequence of
debits and credits
@crichardson
Updating MongoDB using
Spring Data
class AccountInfoUpdateService
(mongoTemplate : MongoTemplate, ...)
extends CompoundEventHandler {
@EventHandler
def recordDebit(de: DispatchedEvent[AccountDebitedEvent]) = {
...
val ci = AccountChangeInfo(...)
mongoTemplate.updateMulti(
new Query(where("id").is(de.entityId.id).and("version").lt(changeId)),
new Update().
dec("balance", amount).
push("changes", ci).
set("version", changeId),
classOf[AccountInfo])
}
@EventHandler
def recordTransfer(de: DispatchedEvent[TransferTransactionCreatedEvent]) = ...
}
insert/In-place update
duplicate event detection
updates to and from accounts
@crichardson
Retrieving account info from
MongoDB using Spring Data
class AccountInfoQueryService(accountInfoRepository : AccountInfoRepository)
{
def findByAccountId(accountId : EntityId) : AccountInfo =
accountInfoRepository.findOne(accountId.id)
}
case class AccountInfo(id : String, balance : Long,
transactions : List[AccountTransactionInfo],
changes : List[ChangeInfo],
version : String)
case class AccountTransactionInfo(changeId : String,
transactionId : String,
transactionType : String,
amount : Long, balanceDelta : Long)
trait AccountInfoRepository extends MongoRepository[AccountInfo, String]
Implementation generated by Spring Data
@crichardson
Agenda
Why build event-driven microservices?
Overview of event sourcing
Designing microservices with event sourcing
Implementing queries in an event sourced application
Building and deploying microservices
@crichardson
Building microservices with
Spring Boot
Makes it easy to create stand-alone, production ready
Spring Applications
Automatically configures Spring using Convention over
Configuration
Externalizes configuration
Generates standalone executable JARs with embedded
web server
@crichardson
Spring Boot simplifies configuration
Spring
Container
Application
components
Fully
configured
application
Configuration
Metadata
•Typesafe JavaConfig
•Annotations
•Legacy XML
Default
Configuration
Metadata
Spring
Boot
You write less
of this
Inferred from
CLASSPATH
@crichardson
Tiny Spring configuration for
Account microservice
@Configuration
@EnableAutoConfiguration
@Import(classOf[JdbcEventStoreConfiguration]))
@ComponentScan
class AccountConfiguration {
@Bean
def accountService(eventStore : EventStore) =
new AccountService(eventStore)
@Bean
def accountEventHandlers(eventStore : EventStore) =
EventHandlerRegistrar.makeFromCompoundEventHandler(
eventStore, "accountEventHandlers",
new TransferWorkflowAccountHandlers(eventStore))
@Bean
@Primary
def scalaObjectMapper() = ScalaObjectMapper
}
Service
Event handlers
Scan for controllers
Customize JSON serialization
@crichardson
The Main program
object BankingMain extends App {
SpringApplication.run(classOf[AccountConfiguration], args :_ *)
}
@crichardson
Building with Gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.0.RELEASE")
}
}
apply plugin: 'scala'
apply plugin: 'spring-boot'
...
@crichardson
Running the microservice
$ java -jar build/libs/banking-main-1.0-SNAPSHOT.jar --server.port=8081
...
11:38:04.633 INFO n.c.e.e.bank.web.main.BankingMain$ - Started
BankingMain. in 8.811 seconds (JVM running for 9.884)
$ curl localhost:8081/health
{"status":"UP",
"mongo":{"status":"UP","version":"2.4.10"},
"db":{"status":"UP","database":"H2","hello":1}
}
Built in health checks
Command line arg processing
@crichardson
Jenkins-based deployment
pipeline
Build & Test
micro-
service
Build & Test
Docker
image
Deploy
Docker
image
to
Repository
One pipeline per micro-service
@crichardson
Summary
Event Sourcing solves key data consistency issues with:
Microservices
Partitioned/NoSQL databases
Spring and Scala play nicely together
Spring Boot makes it very easily to build production ready
microservices
@crichardson
Questions?
@crichardson chris@chrisrichardson.net
http://plainoldobjects.com

Más contenido relacionado

La actualidad más candente

A microservice approach for legacy modernisation
A microservice approach for legacy modernisationA microservice approach for legacy modernisation
A microservice approach for legacy modernisation
luisw19
 

La actualidad más candente (20)

Microservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native AppsMicroservices Architecture - Cloud Native Apps
Microservices Architecture - Cloud Native Apps
 
Saturn 2018: Managing data consistency in a microservice architecture using S...
Saturn 2018: Managing data consistency in a microservice architecture using S...Saturn 2018: Managing data consistency in a microservice architecture using S...
Saturn 2018: Managing data consistency in a microservice architecture using S...
 
Social network with microservices
Social network with microservicesSocial network with microservices
Social network with microservices
 
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
Building and deploying microservices with event sourcing, CQRS and Docker (Be...Building and deploying microservices with event sourcing, CQRS and Docker (Be...
Building and deploying microservices with event sourcing, CQRS and Docker (Be...
 
NIWeek 2017 - Automated Test of LabVIEW FPGA Code: CI and Jenkins 2 Pipelines
NIWeek 2017 - Automated Test of LabVIEW FPGA Code: CI and Jenkins 2 PipelinesNIWeek 2017 - Automated Test of LabVIEW FPGA Code: CI and Jenkins 2 Pipelines
NIWeek 2017 - Automated Test of LabVIEW FPGA Code: CI and Jenkins 2 Pipelines
 
CQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDDCQRS and Event Sourcing, An Alternative Architecture for DDD
CQRS and Event Sourcing, An Alternative Architecture for DDD
 
A Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation SlidesA Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation Slides
 
Microservices Architecture - Bangkok 2018
Microservices Architecture - Bangkok 2018Microservices Architecture - Bangkok 2018
Microservices Architecture - Bangkok 2018
 
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
Scenarios_and_Architecture_SkillsMatter_April_2022.pdfScenarios_and_Architecture_SkillsMatter_April_2022.pdf
Scenarios_and_Architecture_SkillsMatter_April_2022.pdf
 
CQRS and Event Sourcing
CQRS and Event Sourcing CQRS and Event Sourcing
CQRS and Event Sourcing
 
Understanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring BootUnderstanding MicroSERVICE Architecture with Java & Spring Boot
Understanding MicroSERVICE Architecture with Java & Spring Boot
 
[Devil's camp 2019] 혹시 Elixir 아십니까? 정.말.갓.언.어.입.니.다
[Devil's camp 2019] 혹시 Elixir 아십니까? 정.말.갓.언.어.입.니.다[Devil's camp 2019] 혹시 Elixir 아십니까? 정.말.갓.언.어.입.니.다
[Devil's camp 2019] 혹시 Elixir 아십니까? 정.말.갓.언.어.입.니.다
 
A microservice approach for legacy modernisation
A microservice approach for legacy modernisationA microservice approach for legacy modernisation
A microservice approach for legacy modernisation
 
QlikView Architecture Overview
QlikView Architecture OverviewQlikView Architecture Overview
QlikView Architecture Overview
 
Microservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, KanbanMicroservices, Containers, Kubernetes, Kafka, Kanban
Microservices, Containers, Kubernetes, Kafka, Kanban
 
Spring batch overivew
Spring batch overivewSpring batch overivew
Spring batch overivew
 
Solution Architecture US healthcare
Solution Architecture US healthcare Solution Architecture US healthcare
Solution Architecture US healthcare
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Micro services Architecture
Micro services ArchitectureMicro services Architecture
Micro services Architecture
 
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
 

Destacado

Micro Service Architecture
Micro Service ArchitectureMicro Service Architecture
Micro Service Architecture
Eduards Sizovs
 
Principles of microservices velocity
Principles of microservices   velocityPrinciples of microservices   velocity
Principles of microservices velocity
Sam Newman
 

Destacado (20)

Micro Service Architecture
Micro Service ArchitectureMicro Service Architecture
Micro Service Architecture
 
Building and deploying microservices with event sourcing, CQRS and Docker (Ha...
Building and deploying microservices with event sourcing, CQRS and Docker (Ha...Building and deploying microservices with event sourcing, CQRS and Docker (Ha...
Building and deploying microservices with event sourcing, CQRS and Docker (Ha...
 
MicroService Architecture
MicroService ArchitectureMicroService Architecture
MicroService Architecture
 
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
Building and deploying microservices with event sourcing, CQRS and Docker (QC...Building and deploying microservices with event sourcing, CQRS and Docker (QC...
Building and deploying microservices with event sourcing, CQRS and Docker (QC...
 
Building Micro-Services with Scala
Building Micro-Services with ScalaBuilding Micro-Services with Scala
Building Micro-Services with Scala
 
Principles of microservices velocity
Principles of microservices   velocityPrinciples of microservices   velocity
Principles of microservices velocity
 
Events on the outside, on the inside and at the core (jfokus jfokus2016)
Events on the outside, on the inside and at the core (jfokus jfokus2016)Events on the outside, on the inside and at the core (jfokus jfokus2016)
Events on the outside, on the inside and at the core (jfokus jfokus2016)
 
Microservices pattern language (microxchg microxchg2016)
Microservices pattern language (microxchg microxchg2016)Microservices pattern language (microxchg microxchg2016)
Microservices pattern language (microxchg microxchg2016)
 
Microservices: Where do they fit within a rapidly evolving integration archit...
Microservices: Where do they fit within a rapidly evolving integration archit...Microservices: Where do they fit within a rapidly evolving integration archit...
Microservices: Where do they fit within a rapidly evolving integration archit...
 
Microservice vs. Monolithic Architecture
Microservice vs. Monolithic ArchitectureMicroservice vs. Monolithic Architecture
Microservice vs. Monolithic Architecture
 
#JaxLondon keynote: Developing applications with a microservice architecture
#JaxLondon keynote: Developing applications with a microservice architecture#JaxLondon keynote: Developing applications with a microservice architecture
#JaxLondon keynote: Developing applications with a microservice architecture
 
Decomposing applications for deployability and scalability #springone2gx #s12gx
Decomposing applications for deployability and scalability #springone2gx #s12gxDecomposing applications for deployability and scalability #springone2gx #s12gx
Decomposing applications for deployability and scalability #springone2gx #s12gx
 
A pattern language for microservices (#gluecon #gluecon2016)
A pattern language for microservices (#gluecon #gluecon2016)A pattern language for microservices (#gluecon #gluecon2016)
A pattern language for microservices (#gluecon #gluecon2016)
 
Developing functional domain models with event sourcing (sbtb, sbtb2015)
Developing functional domain models with event sourcing (sbtb, sbtb2015)Developing functional domain models with event sourcing (sbtb, sbtb2015)
Developing functional domain models with event sourcing (sbtb, sbtb2015)
 
Microservices + Events + Docker = A Perfect Trio (dockercon)
Microservices + Events + Docker = A Perfect Trio (dockercon)Microservices + Events + Docker = A Perfect Trio (dockercon)
Microservices + Events + Docker = A Perfect Trio (dockercon)
 
Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)
 
Developing microservices with aggregates (SpringOne platform, #s1p)
Developing microservices with aggregates (SpringOne platform, #s1p)Developing microservices with aggregates (SpringOne platform, #s1p)
Developing microservices with aggregates (SpringOne platform, #s1p)
 
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
Handling Eventual Consistency in JVM Microservices with Event Sourcing (javao...
 
Deploying Spring Boot applications with Docker (east bay cloud meetup dec 2014)
Deploying Spring Boot applications with Docker (east bay cloud meetup dec 2014)Deploying Spring Boot applications with Docker (east bay cloud meetup dec 2014)
Deploying Spring Boot applications with Docker (east bay cloud meetup dec 2014)
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 

Similar a Building microservices with Scala, functional domain models and Spring Boot

Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...
JAXLondon2014
 

Similar a Building microservices with Scala, functional domain models and Spring Boot (20)

Building microservices with Scala, functional domain models and Spring Boot (...
Building microservices with Scala, functional domain models and Spring Boot (...Building microservices with Scala, functional domain models and Spring Boot (...
Building microservices with Scala, functional domain models and Spring Boot (...
 
Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...Building Microservices with Scala, functional domain models and Spring Boot -...
Building Microservices with Scala, functional domain models and Spring Boot -...
 
#JaxLondon: Building microservices with Scala, functional domain models and S...
#JaxLondon: Building microservices with Scala, functional domain models and S...#JaxLondon: Building microservices with Scala, functional domain models and S...
#JaxLondon: Building microservices with Scala, functional domain models and S...
 
Developing Event-driven Microservices with Event Sourcing & CQRS (gotoams)
Developing Event-driven Microservices with Event Sourcing & CQRS (gotoams)Developing Event-driven Microservices with Event Sourcing & CQRS (gotoams)
Developing Event-driven Microservices with Event Sourcing & CQRS (gotoams)
 
Building and deploying microservices with event sourcing, CQRS and Docker (Me...
Building and deploying microservices with event sourcing, CQRS and Docker (Me...Building and deploying microservices with event sourcing, CQRS and Docker (Me...
Building and deploying microservices with event sourcing, CQRS and Docker (Me...
 
OReilly SACON2018 - Events on the outside, on the inside, and at the core
OReilly SACON2018 - Events on the outside, on the inside, and at the coreOReilly SACON2018 - Events on the outside, on the inside, and at the core
OReilly SACON2018 - Events on the outside, on the inside, and at the core
 
Microservices + Events + Docker = A Perfect Trio by Docker Captain Chris Rich...
Microservices + Events + Docker = A Perfect Trio by Docker Captain Chris Rich...Microservices + Events + Docker = A Perfect Trio by Docker Captain Chris Rich...
Microservices + Events + Docker = A Perfect Trio by Docker Captain Chris Rich...
 
Microservices in Java and Scala (sfscala)
Microservices in Java and Scala (sfscala)Microservices in Java and Scala (sfscala)
Microservices in Java and Scala (sfscala)
 
Developing event-driven microservices with event sourcing and CQRS (Shanghai)
Developing event-driven microservices with event sourcing and CQRS (Shanghai)Developing event-driven microservices with event sourcing and CQRS (Shanghai)
Developing event-driven microservices with event sourcing and CQRS (Shanghai)
 
Developing event-driven microservices with event sourcing and CQRS (london Ja...
Developing event-driven microservices with event sourcing and CQRS (london Ja...Developing event-driven microservices with event sourcing and CQRS (london Ja...
Developing event-driven microservices with event sourcing and CQRS (london Ja...
 
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...Developing event-driven microservices with event sourcing and CQRS  (svcc, sv...
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
 
YOW2018 - Events and Commands: Developing Asynchronous Microservices
YOW2018 - Events and Commands: Developing Asynchronous MicroservicesYOW2018 - Events and Commands: Developing Asynchronous Microservices
YOW2018 - Events and Commands: Developing Asynchronous Microservices
 
Events on the outside, on the inside and at the core (jaxlondon)
Events on the outside, on the inside and at the core (jaxlondon)Events on the outside, on the inside and at the core (jaxlondon)
Events on the outside, on the inside and at the core (jaxlondon)
 
Events on the outside, on the inside and at the core - Chris Richardson
Events on the outside, on the inside and at the core - Chris RichardsonEvents on the outside, on the inside and at the core - Chris Richardson
Events on the outside, on the inside and at the core - Chris Richardson
 
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
#hacksummit 2016 - event-driven microservices – Events on the outside, on the...
 
SVCC Developing Asynchronous, Message-Driven Microservices
SVCC Developing Asynchronous, Message-Driven Microservices  SVCC Developing Asynchronous, Message-Driven Microservices
SVCC Developing Asynchronous, Message-Driven Microservices
 
Building and Deploying Microservices with Event Sourcing, CQRS and Docker
Building and Deploying Microservices with Event Sourcing, CQRS and DockerBuilding and Deploying Microservices with Event Sourcing, CQRS and Docker
Building and Deploying Microservices with Event Sourcing, CQRS and Docker
 
Mucon: Not Just Events: Developing Asynchronous Microservices
Mucon: Not Just Events: Developing Asynchronous MicroservicesMucon: Not Just Events: Developing Asynchronous Microservices
Mucon: Not Just Events: Developing Asynchronous Microservices
 
Solving distributed data management problems in a microservice architecture (...
Solving distributed data management problems in a microservice architecture (...Solving distributed data management problems in a microservice architecture (...
Solving distributed data management problems in a microservice architecture (...
 
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
GotoChgo 2019: Not Just Events: Developing Asynchronous MicroservicesGotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
GotoChgo 2019: Not Just Events: Developing Asynchronous Microservices
 

Más de Chris Richardson

Más de Chris Richardson (20)

The microservice architecture: what, why, when and how?
The microservice architecture: what, why, when and how?The microservice architecture: what, why, when and how?
The microservice architecture: what, why, when and how?
 
More the merrier: a microservices anti-pattern
More the merrier: a microservices anti-patternMore the merrier: a microservices anti-pattern
More the merrier: a microservices anti-pattern
 
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...
 
Dark Energy, Dark Matter and the Microservices Patterns?!
Dark Energy, Dark Matter and the Microservices Patterns?!Dark Energy, Dark Matter and the Microservices Patterns?!
Dark Energy, Dark Matter and the Microservices Patterns?!
 
Dark energy, dark matter and microservice architecture collaboration patterns
Dark energy, dark matter and microservice architecture collaboration patternsDark energy, dark matter and microservice architecture collaboration patterns
Dark energy, dark matter and microservice architecture collaboration patterns
 
Using patterns and pattern languages to make better architectural decisions
Using patterns and pattern languages to make better architectural decisions Using patterns and pattern languages to make better architectural decisions
Using patterns and pattern languages to make better architectural decisions
 
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
iSAQB gathering 2021 keynote - Architectural patterns for rapid, reliable, fr...
 
Events to the rescue: solving distributed data problems in a microservice arc...
Events to the rescue: solving distributed data problems in a microservice arc...Events to the rescue: solving distributed data problems in a microservice arc...
Events to the rescue: solving distributed data problems in a microservice arc...
 
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
QConPlus 2021: Minimizing Design Time Coupling in a Microservice ArchitectureQConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
QConPlus 2021: Minimizing Design Time Coupling in a Microservice Architecture
 
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...
 
Designing loosely coupled services
Designing loosely coupled servicesDesigning loosely coupled services
Designing loosely coupled services
 
Microservices - an architecture that enables DevOps (T Systems DevOps day)
Microservices - an architecture that enables DevOps (T Systems DevOps day)Microservices - an architecture that enables DevOps (T Systems DevOps day)
Microservices - an architecture that enables DevOps (T Systems DevOps day)
 
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...
 
Decompose your monolith: Six principles for refactoring a monolith to microse...
Decompose your monolith: Six principles for refactoring a monolith to microse...Decompose your monolith: Six principles for refactoring a monolith to microse...
Decompose your monolith: Six principles for refactoring a monolith to microse...
 
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
TDC2020 - The microservice architecture: enabling rapid, reliable, frequent a...
 
Overview of the Eventuate Tram Customers and Orders application
Overview of the Eventuate Tram Customers and Orders applicationOverview of the Eventuate Tram Customers and Orders application
Overview of the Eventuate Tram Customers and Orders application
 
An overview of the Eventuate Platform
An overview of the Eventuate PlatformAn overview of the Eventuate Platform
An overview of the Eventuate Platform
 
#DevNexus202 Decompose your monolith
#DevNexus202 Decompose your monolith#DevNexus202 Decompose your monolith
#DevNexus202 Decompose your monolith
 
JFokus: Cubes, Hexagons, Triangles, and More: Understanding Microservices
JFokus: Cubes, Hexagons, Triangles, and More: Understanding MicroservicesJFokus: Cubes, Hexagons, Triangles, and More: Understanding Microservices
JFokus: Cubes, Hexagons, Triangles, and More: Understanding Microservices
 
Decompose your monolith: strategies for migrating to microservices (Tide)
Decompose your monolith: strategies for migrating to microservices (Tide)Decompose your monolith: strategies for migrating to microservices (Tide)
Decompose your monolith: strategies for migrating to microservices (Tide)
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 

Building microservices with Scala, functional domain models and Spring Boot

  • 1. @crichardson Building microservices with Scala, functional domain models and Spring Boot Chris Richardson Author of POJOs in Action Founder of the original CloudFoundry.com @crichardson chris@chrisrichardson.net http://plainoldobjects.com
  • 2. @crichardson Presentation goal Share my experiences with building an application using Scala, functional domain models, microservices, event sourcing, CQRS, and Spring Boot
  • 4. @crichardson About Chris Founder of a buzzword compliant (stealthy, social, mobile, big data, machine learning, ...) startup Consultant helping organizations improve how they architect and deploy applications using cloud, micro services, polyglot applications, NoSQL, ...
  • 5. @crichardson Agenda Why build event-driven microservices? Overview of event sourcing Designing microservices with event sourcing Implementing queries in an event sourced application Building and deploying microservices
  • 6. @crichardson Let’s imagine that you are building a banking app...
  • 9. @crichardson Problem #1: monolithic architecture Intimidates developers Obstacle to frequent deployments Overloads your IDE and container Obstacle to scaling development Requires long-term commitment to a technology stack
  • 10. @crichardson Solution #1: use a microservice architecture Banking UI Account Management Service Transaction Management Service Account Database Transaction Database Standalone services
  • 11. @crichardson Problem #2: relational databases Scalability Distribution Schema updates O/R impedance mismatch Handling semi-structured data
  • 12. @crichardson Solution #2: use NoSQL databases Avoids the limitations of RDBMS For example, text search Solr/Cloud Search social (graph) data Neo4J highly distributed/available database Cassandra ...
  • 13. @crichardson But now we have problems with data consistency!
  • 14. @crichardson Problem #3: Microservices = distributed data management Each microservice has it’s own database Some data is replicated and must be kept in sync Business transactions must update data owned by multiple services Tricky to implement reliably without 2PC
  • 15. @crichardson Problem #4: NoSQL = ACID-free, denormalized databases Limited transactions, i.e. no ACID transactions Tricky to implement business transactions that update multiple rows, e.g. http://bit.ly/mongo2pc Limited querying capabilities Requires denormalized/materialized views that must be synchronized Multiple datastores (e.g. DynamoDB + Cloud Search ) that need to be kept in sync
  • 16. @crichardson Solution to #3/#4: Event-based architecture to the rescue Microservices publish events when state changes Microservices subscribe to events Synchronize replicated data Maintains eventual consistency across multiple aggregates (in multiple datastores)
  • 17. @crichardson Eventually consistent money transfer Message Bus Transaction management service Account management service transferMoney() Publishes: Subscribes to: Subscribes to: publishes: TransferTransactionCreatedEvent AccountDebitedEvent DebitRecordedEvent AccountCreditedEvent TransferTransactionCreatedEvent DebitRecordedEvent AccountDebitedEvent AccountCreditedEvent
  • 18. @crichardson But reliably generating events is difficult Must atomically update datastore and publish event(s) Non-option: datastore and message broker use 2PC Use datastore as message queue Local transaction updates state and publishes message See BASE: An Acid Alternative, http://bit.ly/ebaybase But Business logic and event publishing code intertwined Tricky to implement with aggregate-oriented NoSQL database
  • 19. @crichardson Agenda Why build event-driven microservices? Overview of event sourcing Designing microservices with event sourcing Implementing queries in an event sourced application Building and deploying microservices
  • 20. @crichardson Event sourcing For each aggregate: Identify (state-changing) domain events Define Event classes For example, Account: AccountOpenedEvent, AccountDebitedEvent, AccountCreditedEvent ShoppingCart: ItemAddedEvent, ItemRemovedEvent, OrderPlacedEvent
  • 21. @crichardson Persists events NOT current state Account balance open(initial) debit(amount) credit(amount) AccountOpened Event table AccountCredited AccountDebited 101 450 Account table X 101 101 101 901 902 903 500 250 300
  • 22. @crichardson Replay events to recreate state Account balance AccountOpenedEvent(balance) AccountDebitedEvent(amount) AccountCreditedEvent(amount) Events
  • 23. @crichardson Aggregate traits Map Command to Events Apply event returning updated Aggregate
  • 24. @crichardson Account - command processing Prevent overdraft
  • 26. @crichardson Request handling in an event-sourced application HTTP Handler Event Store pastEvents = findEvents(entityId) Account new() applyEvents(pastEvents) newEvents = processCmd(SomeCmd) saveEvents(newEvents) Microservice A
  • 27. @crichardson Event Store publishes events - consumed by other services Event Store Event Subscriber subscribe(EventTypes) publish(event) publish(event) Aggregate NoSQL materialized view update() update() Microservice B
  • 28. @crichardson Event Store API trait EventStore { def save[T <: Aggregate[T]](entity: T, events: Seq[Event], assignedId : Option[EntityId] = None): Future[EntityWithIdAndVersion[T]] def update[T <: Aggregate[T]](entityIdAndVersion : EntityIdAndVersion, entity: T, events: Seq[Event]): Future[EntityWithIdAndVersion[T]] def find[T <: Aggregate[T] : ClassTag](entityId: EntityId) : Future[EntityWithIdAndVersion[T]] def findOptional[T <: Aggregate[T] : ClassTag](entityId: EntityId) Future[Option[EntityWithIdAndVersion[T]]] def subscribe(subscriptionId: SubscriptionId): Future[AcknowledgableEventStream] } In case you are wondering: Akka Persistence is too Akka-centric
  • 29. @crichardson Benefits of event sourcing Business: Built in audit log Enables temporal queries Technical: Solves data consistency issues in a Microservice/NoSQL-based architecture: Atomically save and publish events Event subscribers update other aggregates ensuring eventual consistency Event subscribers update materialized views in SQL and NoSQL databases Eliminates O/R mapping problem
  • 30. @crichardson Drawbacks of event sourcing Weird and unfamiliar Events = a historical record of your bad design decisions Handling duplicate events can be tricky Idempotent commands Duplicate detection, e.g. track most recently seen event
  • 31. @crichardson Agenda Why build event-driven microservices? Overview of event sourcing Designing microservices with event sourcing Implementing queries in an event sourced application Building and deploying microservices
  • 32. @crichardson The anatomy of a microservice Event Store HTTP Request HTTP Adapter Aggregate Event Adapter Cmd Cmd Events Events Xyz Adapter Xyz Request microservice
  • 34. @crichardson AccountTransactionService DSL concisely specifies: 1.Creates new TransferTransaction 2.Processes command 3.Applies events 4.Persists events
  • 36. @crichardson Handling events published by Accounts 1.Load TransferTransaction 2.Processes command 3.Applies events 4.Persists events
  • 37. @crichardson Agenda Why build event-driven microservices? Overview of event sourcing Designing microservices with event sourcing Implementing queries in an event sourced application Building and deploying microservices
  • 38. @crichardson Let’s imagine that you want to display an account and it’s recent transactions...
  • 39. @crichardson Displaying balance + recent transactions We need to do a “join: between the Account and the corresponding TransferTransactions (Assuming Debit/Credit events don’t include other account, ...) BUT Event Store = primary key lookup of individual aggregates, ... Use Command Query Responsibility Separation Define separate “materialized” query-side views that implement those queries
  • 40. @crichardson Query-side microservices Event Store Updater - microservice View Updater Service Events Reader - microservice HTTP GET Request View Query Service View Store e.g. MongoDB Neo4J CloudSearch update query
  • 41. @crichardson Persisting account balance and recent transactions in MongoDB { id: "298993498", balance: 100000, transactions : [ {"transactionId" : "4552840948484", "fromAccountId" : 298993498, "toAccountId" : 3483948934, "amount" : 5000}, ... ], changes: [ {"changeId" : "93843948934", "transactionId" : "4552840948484", "transactionType" : "AccountDebited", "amount" : 5000}, ... ] } Denormalized = efficient lookup Transactions that update the account The sequence of debits and credits
  • 42. @crichardson Updating MongoDB using Spring Data class AccountInfoUpdateService (mongoTemplate : MongoTemplate, ...) extends CompoundEventHandler { @EventHandler def recordDebit(de: DispatchedEvent[AccountDebitedEvent]) = { ... val ci = AccountChangeInfo(...) mongoTemplate.updateMulti( new Query(where("id").is(de.entityId.id).and("version").lt(changeId)), new Update(). dec("balance", amount). push("changes", ci). set("version", changeId), classOf[AccountInfo]) } @EventHandler def recordTransfer(de: DispatchedEvent[TransferTransactionCreatedEvent]) = ... } insert/In-place update duplicate event detection updates to and from accounts
  • 43. @crichardson Retrieving account info from MongoDB using Spring Data class AccountInfoQueryService(accountInfoRepository : AccountInfoRepository) { def findByAccountId(accountId : EntityId) : AccountInfo = accountInfoRepository.findOne(accountId.id) } case class AccountInfo(id : String, balance : Long, transactions : List[AccountTransactionInfo], changes : List[ChangeInfo], version : String) case class AccountTransactionInfo(changeId : String, transactionId : String, transactionType : String, amount : Long, balanceDelta : Long) trait AccountInfoRepository extends MongoRepository[AccountInfo, String] Implementation generated by Spring Data
  • 44. @crichardson Agenda Why build event-driven microservices? Overview of event sourcing Designing microservices with event sourcing Implementing queries in an event sourced application Building and deploying microservices
  • 45. @crichardson Building microservices with Spring Boot Makes it easy to create stand-alone, production ready Spring Applications Automatically configures Spring using Convention over Configuration Externalizes configuration Generates standalone executable JARs with embedded web server
  • 46. @crichardson Spring Boot simplifies configuration Spring Container Application components Fully configured application Configuration Metadata •Typesafe JavaConfig •Annotations •Legacy XML Default Configuration Metadata Spring Boot You write less of this Inferred from CLASSPATH
  • 47. @crichardson Tiny Spring configuration for Account microservice @Configuration @EnableAutoConfiguration @Import(classOf[JdbcEventStoreConfiguration])) @ComponentScan class AccountConfiguration { @Bean def accountService(eventStore : EventStore) = new AccountService(eventStore) @Bean def accountEventHandlers(eventStore : EventStore) = EventHandlerRegistrar.makeFromCompoundEventHandler( eventStore, "accountEventHandlers", new TransferWorkflowAccountHandlers(eventStore)) @Bean @Primary def scalaObjectMapper() = ScalaObjectMapper } Service Event handlers Scan for controllers Customize JSON serialization
  • 48. @crichardson The Main program object BankingMain extends App { SpringApplication.run(classOf[AccountConfiguration], args :_ *) }
  • 49. @crichardson Building with Gradle buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.0.RELEASE") } } apply plugin: 'scala' apply plugin: 'spring-boot' ...
  • 50. @crichardson Running the microservice $ java -jar build/libs/banking-main-1.0-SNAPSHOT.jar --server.port=8081 ... 11:38:04.633 INFO n.c.e.e.bank.web.main.BankingMain$ - Started BankingMain. in 8.811 seconds (JVM running for 9.884) $ curl localhost:8081/health {"status":"UP", "mongo":{"status":"UP","version":"2.4.10"}, "db":{"status":"UP","database":"H2","hello":1} } Built in health checks Command line arg processing
  • 51. @crichardson Jenkins-based deployment pipeline Build & Test micro- service Build & Test Docker image Deploy Docker image to Repository One pipeline per micro-service
  • 52. @crichardson Summary Event Sourcing solves key data consistency issues with: Microservices Partitioned/NoSQL databases Spring and Scala play nicely together Spring Boot makes it very easily to build production ready microservices