Common Patterns in Distributed Systems

Sample application:

https://github.com/microservices-patterns/ftgo-application

http://eventuate.io/exampleapps.html

Microservices Patterns: https://microservices.io/patterns/index.html

Enterprise Integration Patterns: https://www.enterpriseintegrationpatterns.com/patterns/messaging/

Configuration Management

Centralizing configuration and secret values:

Service Discovery

Client make request to Service Registry or Load Balancer (Router):

Apache Consul – is a service discovery with a REST, Health Checking, Service Segmentation. Has own distributed key value store.

Netflix Eureka – service discovery tool, mostly AWS. As part of Netflixes load balancers and failover.

Circuit Breakers

Handle remote call fails – once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all.

Intelligent Routing

Zuul – routing external traffic, applying filters (authentication and security) preventing DDoS, static response handling

Micro-proxy

Routing request from outside between services

Control Bus

Control (send/read events asynchronously) distributed systems (message bus) in Spring Integration

One-time Tokens

Token – token is a simple string that represents a user that we have previously validated. Can be stored in database or use encryption on user data

Global Locks

Leadership Election

Service leadership

Distributed Sessions

Cluster State

PostgreSQL quick start

How to install PostgreSQL

with brew:

add to startup:

start:

or manually:

with ctl:

check status:

port:

logs:

How to setup PostgreSQL

quit psql:

create application user and database

setup password for user:

Enjoy!

Initialization List with values in one row in Java

Java 9:
List.of(“a”, “b”, “c”);
Set.of(“a”, “b”, “c”);

Java 8:
Stream.of(“a”, “b”, “c”).collect(Collectors.toList());
Stream.of(“a”, “b”, “c”).collect(Collectors.toCollection(ArrayList::new));

Older:
Collections.singletonList();
Arrays.asList();
new ArrayList() {{ add(“a”); add(“b”); add(“c”); }};

Mockito, Spy, PowerMock

Mockito

Mockito Mocks vs. Spies

Mock – bare-bones shell instance

Spy – wrap an existing instance

PowerMock

  • final classes without interfaces
  • static methods
  • privates

Test-driven development: JUnit

gradle:

maven:

Expected Exceptions Test

@RunWith

BlockJUnit4ClassRunner – default junit runner
SpringJUnit4ClassRunner allows you to use dependency injection in test classes or to create transactional test methods.
MockitoJUnitRunner for automatic mock initialization.
Suite
Parameterized

Parameters class

JUnit 5 – @ExtendWith

replace with

@Rule

or your custom rule:

hamcrest – how to test lists

check if single element is in a collection

check if multiple elements are in a collection

check all elements in a collection with strict order

check all elements in a collection with any order

check if collection is empty

check if array is empty

check if Map is empty

check if Iterable is empty

check size of a collection

checking size of an iterable

check condition on every item

 

Hibernate – OneToOne, OneToMany, ManyToOne, ManyToMany mappings

By specifying the @JoinColumn on both models you don’t have a two way relationship. mappedby

One to One

bidirectional One to One is EAGER

@MapsId (before jpa2 – @PrimaryKeyJoinColumn)

One To Many, Many To One

Unidirectional without @JoinColumn requires additional table for joining

Bidirectional

Is it possible to limit the size of a @OneToMany collection with Hibernate or JPA Annotations? – That’s not possible. Hibernate has two options for you:

  • you load the children collection upon fetching the parent entity
  • you load the children collection lazily on first access

@Where or @Filter are more useful in this situation

or query

Composit primary key

 

Many To Many

 

Hibernate – JPA

SessionFactory (jpa: EntityManagerFactory) – thread-safe (and immutable) representation of the mapping of the application domain model to a database
Session (jpa: EntityManager) – A single-threaded, short-lived object conceptually modeling a “Unit of Work”
StatelessSession – like JDBC
Transaction (jpa: EntityTransaction) – A single-threaded, short-lived object used by the application to demarcate individual physical transaction boundaries.
@PersistenceUnit injects an EntityManagerFactory
@PersistenceContext injects an EntityManager

Hibernate – hibernate.cfg.xml

JPA – persistence.xml

save or persist

save() – for transient save to db, return object(id), for detached create new one row
persist() – for transient save to db and return void, for detached object – PersistentObjectException. For transient doesn’t guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time
saveOrUpdate() – (only hibernate) doesn’t throw Exception on transient object.

merge or update

merge() – for transient and detached the same behavior: update a persistent entity instance with new field values from a detached entity instance, return new attached object.
update() – original hibernate method, return type is void, act on passed object (re-attach). Throws exception on transient entity.

Flush and Refresh

session.refresh() – reload object from database

Flush –

  1. before some query executions
  2. from org.hibernate.Transaction.commit()
  3. from Session.flush()

Flush ordering –

  1. all entity insertions in the same order the corresponding objects were saved using Session.save()
  2. all entity updates
  3. all collection deletions
  4. all collection element deletions, updates and insertions
  5. all collection insertions
  6. all entity deletions in the same order the corresponding objects were deleted using Session.delete()

Flush mode –

  1. only flush at commit time when the Hibernate Transaction API is used
  2. flush automatically using the explained routine,
  3. never flush unless flush() is called explicitly.

get or load

get(class, id) (jpa: find )- hit the database, return object or null if it not exists.
load(class, id) (jpa: getReference) – return proxy, hit the database when object requested, throws exception (jpa:EntityNotFoundException) when object not exists.

sort or ordered

sort – sorting in jvm with Comparator or native
order – use database order by

Inheritance mapping

MappedSuperclass – the parent classes, can’t be entities – super class doesn’t have own table. Superclass no longer has an @Entity annotation. @AttributeOverride – for renaming database column that different from super class column name.

Table-Per-Class – all the properties of a class, are in its table, so no join is required. The same as previous, super class also has a table.

Single Table – the entities from different classes with a common ancestor are placed in a single table. @DiscriminatorValue (@DiscriminatorFormula) –  for this specific entity class so that your persistence provider can map each database record to a concrete entity class.

Joined Table – each class has its table and querying a subclass entity requires joining the tables. @PrimaryKeyJoinColumn – the primary key of the Subclass entity also has a foreign key constraint to the primary key of its parent entity.

https://habr.com/post/337488/

Native query

Named queries

FetchType: N+1 SELECT’s Problem

FetchType.SELECT – N+1 problem is where one query is executed to fetch N records and N queries to fetch some relational records
can be resolved by using fetch join or using a Criteria
but fetch join doesn’t work with pagination

Lazy Loading

@Basic, @OneToMany, @ManyToOne, @OneToOne, and @ManyToMany annotations have an optional parameter called fetch. If this parameter is set to FetchType.LAZY
Build-time bytecode instrumentation (jpa)
Run-time bytecode instrumentation (jpa)
Run-time proxies (hibernate)

Bytecode enhancement

Custom user types

public class MoneyType implements BasicType
public class MoneyType implements UserType
public class MoneyType implements CompositeUserType

Collection types (hibernate)

Debug mode

hibernate.show_sql=true
hibernate.format_sql=true
hibernate.use_sql_comments=true

Annotations

@Transient – not store to database
@Temporal – time, date or timestamp in datadase
@Table – name of mapped table
@Version – for optimistic locking
@ElementCollection (hibernate: @CollectionOfElements) like OneToMany but belongs to entity – Embeddable, cannot select, merge, update without main entity

JPA 2.1

Named Stored Procedures

Spring Bean Life Cycle

By implementing InitializingBean and DisposableBean interfaces
Providing init-method and destroy-method in xml configuration or @PostConstruct and @PreDestroy annotations for methods

For activating post processor annotation annotations use

or by

used to activate applied annotations in already registered beans in application context (context:component-scan does what context:annotation-config does, but additionally it scan the packages and register the beans)

ApplicationContextAware
BeanFactoryAware
BeanNameAware
ResourceLoaderAware
ServletContextAware
ServletConfigAware