terça-feira, 16 de agosto de 2016

Spring Cloud Netflix - How works Service Registration and Discovery


Spring Cloud has a full stack for micro services. The main objective of the spring cloud is to provide a complete integration between Spring Boot and Netflix OSS project, where simple annotation is possible have some components used by Netflix running in your environment

Some pattern provided by Netflix OSS that Spring Cloud provides: 
  • Service Discovery (Eureka)
  • Circuit Breaker (Hystrix)
  • Intelligent Routing (Zuul)
  • Client Side Load Balancing (Ribbon)

In this post will talk about service discovery, showing the concept and how it is possible with a few annotation have the default working on a project with Spring Boot.
Service Discovery is one of the key tenets of micro service based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.

Why Use Service Discovery?
Let's imagine we have many services dynamically distributed on the network. Where instances of services dynamically change because of auto-scaling, failures, upgrades, and we have no control of IP addresses, the name of the instance.
In this situation the simplest would be if the service tell the server or other services where it is and if it is available.

This is how the discovery service works, the service entered in the network and register on a server to make it available for the use of some other service.
The pattern that will be addressed in this post will be The Server-Side Pattern Discovery.
Where customers know where the server is and send to the server that is available.

Registering:

When a client registers with Eureka, it provides meta-data about itself such as host and port, health indicator URL, home page etc. Eureka receives heartbeat messages from each instance belonging to a service. If the heartbeat fails over a configurable timetable, the instance is normally removed from the registry.

Status Page and Health Indicator:

The network location of a service instance is registered with the service registry when it starts up. It is removed from the service registry when the instance terminates. The service instance’s registration is typically refreshed periodically using a heartbeat mechanism.
Eureka’s Health Checks:

By default, Eureka uses the client heartbeat to determine if a client is up. Unless specified otherwise the Discovery Client will not propagate the current health check status of the application per the Spring Boot Actuator. Which means that after successful registration Eureka will always announce that the application is in 'UP' state. Enabling Eureka health checks can alter this behavior, which results in propagating application status to Eureka. As a consequence every other application won’t be sending traffic to application in state other then 'UP'.

Server code:





Client 1 code:


                         defaultZone is the Eureka service address

Tomcat port to client 1







Client 2 code:

The same of the client 1 but in other port

        Tomcat port to client 2


STEPS TO RUN:

1.The first step is run server:

Will be available on http://localhost:8761 and will be showed some information’s and a screen with the instances available.
2.The second step is run client, this client will be registered in the server:

Now in the server is possible see the instance registered:
 

3.The third step is run the second client:

Now in the server is possible see the new instance registered:

all instances already registered:
 

In this links is possible see some information about instances:


Health information image:
 


With few lines of code and annotation, is possible have all benefits of service discovery with spring boot and eureka.

References:

quinta-feira, 4 de agosto de 2016

Ratpack - event-driven framework base on Netty

Ratpack is a set of Java libraries that facilitate fast, efficient, evolvable and well tested HTTP applications. It is built on the highly performant and efficient Netty event-driven networking engine.



Netty provides the infrastructure for non- blocking networking, but doesn’t help much in the way of web application structure.

Provides an asynchronous API for working with network data (including HTTP)

Some key points:
  • Ratpack provides applications with a Netty-based, non- blocking HTTP client
  • Can be used to integrate with external RESTful services
  • Utilizes the same event loop as the server, so resources are appropriately utilized
  • Provides a robust API for programmatically crafting requests
  • Environment-derivable configuration follows the principle of the Twelve Factor App Great Support for building MICROSERVICES!!
  • NetflixOSS Hystrix support, via the ratpack- hystrix module
  • Calls to remote services can be made fault tolerant
  • Ability to stream Hystrix metrics to the Hystrix Dashboard Great Support for building MICROSERVICES!!
  • Ratpack’s Promise API is an implementation of Reactive Streams Specification
  • The ratpack-rxjava module provides a bridge between a Ratpack Promise and an RxJava Observable
  • The ratpack-reactor module allows data to be processed using Project Reactor Great Support for REACTIVE PROGRAMMIN

Ratpack is purely a runtime.
To build Ratpack applications, you can use any JVM build tool. The Ratpack project provides specific support for Gradle through plugins, but any could be used.

Ratpack’s goals are:
  1. To be fast, scalable, and efficient
  2. To allow applications to evolve in complexity without compromise
  3. To leverage the benefits of non-blocking programming and reduce the costs
  4. To be flexible and unopinionated when it comes to integrating other tools and libraries
  5. To allow applications to be easily and thoroughly tested
Ratpacks’s goals are not:
  1. To be a fully integrated, “full stack” solution
  2. Provide every feature you might need in a neat box
  3. To provide an architecture or framework for “business logic”

When to use Ratpack?
  • Micro-services
  • High-througthput apps
  • Lightweight apps
  • Cloud Deployments

Architecture:

Ratpack is strongly typed. Beyond being implemented in Java, a strongly typed language, its API embraces types.

Ratpack at its core is an event based (i.e. non-blocking) HTTP IO engine, and an API that makes it easy to structure response logic. Being non blocking imposes a different style of API than “traditional” blocking Java APIs in that the API must be asynchronous.

Ratpack aims to significantly simplify this style of programming for HTTP applications. It provides support for structuring asynchronous code, and uses an innovative approach for structuring request processing into a self building, asynchronously traversed, graph of functions .

The RatpackServer type is the Ratpack entry point. You write your own main class that uses this API to launch the application.

The port method allows setting the port used to connect to the server. If not configured, the default value is 5050.

Ratpack is designed for “asynchronous” & “non blocking” request processing. Its internal IO (e.g. HTTP request and response transfer) is all performed in a non blocking fashion. This approach yields higher throughput, lower resource usage, and importantly, more predictable behaviour under load. 

This programming model has become increasingly popular of late due to the Node.js platform. Ratpack is built on the same non blocking, event driven, model as Node.js.


Ratpack is fundamentally asynchronous in two key ways:
  1. HTTP IO is event driven / non blocking
  2. Request handling is organised as a pipeline of asynchronous functions

The HTTP IO being event driven is largely transparent when using Ratpack. Netty just does its thing.


Embedding Ratpack in a Spring Boot application


The ratpack-spring-boot extension provides integration with Spring Boot. There are two main features in this library: one allows a Ratpack server registry to be created from a Spring ApplicationContext, and the other allows Ratpack itself to be embedded in a Spring Boot application (making the ApplicationContext automatically part of the server registry).

As an alternative to embedding Spring (as a Registry) in a Ratpack application, you can do the opposite: embed Ratpack as a server in Spring Boot, providing a nice alternative to the Servlet containers that Spring Boot supports. The core of the feature set is an annotation @EnableRatpack which you add to a Spring configuration class in order to start Ratpack. 

TIP: Ratpack will register handlers automatically for static content in the classpath under “/public” or “/static” (just like a regular Spring Boot application).

If Ratpack is embedded in a Spring application it can be helpful to re-use existing Guice modules, e.g. for template rendering. To do this just include a @Bean of type Module. For example with the ThymeleafModule for Thymeleaf support

Basic Sample:

Async Sample:


SpringBoot Sample:



SpringBoot with Thymeleaf Sample:




More details in my github: My Sandbox

What does Ratpack give you over that Vert.x? 

  1. Templating - fully async rendering, and statically compiled using Groovy 2.1 
  2. Error handling (i.e. 500 pages) 
  3. Not found handling (i.e. 404 pages)
  4. Routing - Vert.x already has this, but Ratpack’s is integrated with 404 and 500 handling (and runtime reloadable)
  5. Static file serving - Goes above what Vert.x gives you and support HTTP caching headers
  6. Session support
  7. Runtime reloading - for routes, and if you’re using the Gradle plugin for all of your application code
  8. Higher level abstractions - for example Request and Response
  9. Build tool (Gradle)


Good and Big Sample from ratpack.io 

References: 

quinta-feira, 21 de julho de 2016

Clean Code Summary and Key Points

A long time ago I used this summary of some key points that  I made to study about the book clean code. I hope it helps others.
This summary doesn't exclude the need to read the book Clean Code.


What is Clean Code?

The code can be measured with good or bad in the code review from how many WTF / or how many minutes you talk.
A clean code should be elegant, efficient, readable, simple, without duplications, well written, should be written carefully and must always have a responsibility.
You should add value to the business.
Clean code offers quality and understanding when we open a class.
It is necessary that your code is clean and readable for anyone to find it, can easily understand it avoiding waste of time and facilitating the work of all.

Meaningful Names:

Names of the classes, variables, methods, must be meaningful, clearly indicating that a method does or what an attribute is.
Should create pronounceable names to facilitate communication.
We should avoid acronyms.
Avoid confusing names, which can take anyone who reads the code to wrong conclusions.
Use names that reflect the system domain, the context and the problems that must be solved.

Functions:

The method should be easy to read and understand.
The method should convey its intention.
The methods should be small, another rule for small methods is that they should be even lower.
They must have up to 20 lines. (I think should have up to 10 lines)
Methods should only do one thing, they should do it the right way and just do it.
You should use names with words that can say what he really does.
The optimal number of parameters of a method is zero, after one and two.
Three should be avoided, but if it should have a good justification.
Parameters of the Boolean type as a parameter already clearly states that it does more than one thing.
Methods must do something and returns something.
Avoid duplication.

Comments:

One of the most common reasons for the comments is because the code is bad.
When thinking about writing a comment it is because the code should be refactored.
Comments do not save a bad code.
Try to explain what the code causes the code.
Comments can be useful when placed in certain places.
Create method names and informative variables instead of explaining the code with comments.
Use a comments can be used to express the importance of certain points in the code.
The best comment is one that needs to be written, because your code already explained.
Do not write comments redundant, useless or false information.
It should not be used to indicate who changed or why, for that already exist versioning.
Don’t comment code that will not be used, remove, it just pollutes the code and leaves no doubt in anyone reading.

Formatting:

It should give importance formatting since it is a developer of communication form.
A messy code is hard to read
The readability of the code will take effect on all the changes that will be made.
Try to write class with a maximum of 500 lines, smaller classes are easier to understand.
Set a limit of characters per line of code.
A good character limit on a line is 120.
Try to keep more next related concepts vertically to create a code stream
Use spaces between operators, parameters and commas.

Objects and Data Structure:

Follow the Law of Demeter:
One 'M' method of an object 'O' can only consume services of the following types of objects:
  • The object itself 'O;
  • The 'M' parameters;
  • Any object created / instantiated 'M';
  • Direct Components 'O'.
Make good abstraction and encapsulation.
Do not make dumb objects.
Objects hide the data abstraction and exposes methods that operate the data.
Data structure, exposes your data and do not have significant methods

Error Handling:

Error handling should be planned carefully by all programmers.
When happen wrong things we have to get him to do the right things
Should give preference to launch an exception than treat it just to hide.
Create message of some kind of information.
Mention it failed where was this failure, if possible why it failed.
Look separate business rules for errors or error handling.
Avoid returning a NULL in methods, preferably to return an empty object.
Avoid passing null to the methods, it can generate NullPointerExceptions.

Boundary:

In third-party code to avoid passing objects API’s looking forward to keep it in the same class.
Performs tests on API's Third Party
Study the documentation and well test the third API before you start using it.
Check well the features you will use
These step can help increase yield when there are new updates API and you can only run your tests to check for this update
Create tests the functionality of the API.

Unit Tests:
Make sure each piece of code is doing what you expect it to do.
Follow the TDD’s law: 
  • Not Create code before you have a failing test.
  • Shouldn’t create more tests than necessary to fail. 
  • You cannot write more code than enough to pass the test that is failing
Keep your test clean
The tests must undergo changes in the same way that the code
The dirtier the more difficult test will be, to give maintenance.
Look create an assert for testing
Use the F.I.R.S.T rule for testing:
  • The test is FAST running
  • The test should be INDEPENDENT of other
  • REPEATABLE in various environments
  • SELF- VALIDATING
  • TIMELY 
The test is as important as the production code.

Classes:

By default java classes should start with the variables:
  • Static and constant public
  • Static and variable private
  • Instances and variables privates
  • Soon after come the functions
The class name should represent your responsibility
The class must have only one responsibility
To know the size of the class is ideal or we should not measure her responsibility
You should try to make a brief description of the class
The methods should be:
  • Small
  • And even lower
  • They must have only one responsibility 

Systems:

It is important to recognize and separate responsibilities of a system.
It should be separate and modularize the logic execution, allowing an independent strategy for solving application dependency
Is an element important to take care of dependency injection allowing objects only take care of the business of logic.
It is very difficult to create a system properly first, must be made available to the story, then refactor it and the expand system to continue implementing new stories.
To get to that point is necessary TDD, refactoring and clean code.
We must build POJOs-based logic through testing and evolve from simple to interconnect the various aspects necessary.

Emergence:

Rules given by Kent Beck to create good designs:
  • Run all tests: they verify that the system behaves as expected.
  • Eliminate duplication: for with duplicate code has additional work.
  • To express the intention of the programmer: use more expressive code can to Facilitate maintenance. Choose good names for functions, classes and tests shouldn’t be small and well written. 
  •  Minimize the number of classes and methods: following this pattern can ignore it if the classes are very small.
  • Apply all knowledge to improve the design during refactoring: greater cohesion, reducing coupling, separate responsibilities, reducing classes and methods, choose the best names.
Even applying it once you will not be able to have good software you need to do this for over and over again, to achieve continuous improvement.

Concurrence:

The concurrency is an aspect that may be present in the codes.
For uncoupling allows improving the yield and structure of an application.
The concurrency can improve response times and application efficiency.
You should consider the following ideas about the concurrence:
  • It injects a certain overload.
  • It can be complex to operate.
  • Errors caused by it can be difficult to reproduce
  • Usually requires design changes.
The concurrence problem is that different segments of an application may be following tangled multi-threading, which can cause unexpected problems in normal situations.
For concurrence reasons it is important that each class has a unique responsibility. 
Create Sections synchronized minimized. Run tests are often the best way to find any errors in the code.
However, it is difficult to do when there are concurrence tests 
A good way to test is to insert codes for testing in the middle of the implemented code.

Successive Refinement:

The code only work is not enough to have a good code.
Professionals who care only about the code that works cannot be considered professional.
We can not consider that we have no time to refactor to one code, since this code that was not taken care of today can become a problem after becoming a problem for the team, because no one will want to mess with it.
Try not to let the rot code, it is much cheaper to create a clean code than cleaning a rotten code as move in a tangle can be an arduous task.
The solution then comes down to maintain the cleanest code possible and as simple as possible without ever leaving the rot started.

JUnit: 

Look to cover tests each not every method but each code line.
No code is immune improvement, and each of us has a responsibility to make the code a little better than we found it.
Refactoring is an iterative process full of trial and error inevitably converging to something that we feel is worthy of a professional.

Refactoring:

Before making any kind of refactoring is important to have good coverage tests.
After increase or create test coverage can begin to leave the clearest code and fix some bugs.
Now after leaving the code clearer probably someone else can clean even more.

Smells and Heuristics:

What you should not do about comments:
  • Inappropriate information
  • Obsolete Comment
  • Redundant Comment
  • Review misspelled
  • Commented Code
Environment:
  • Build requires more than one step
  • Tests require more than one step
 Functions/Methods:
  • Many arguments
  • Flags with Boolean
  • Methods unused
General
  • Multiple Languages to a file.
  • Overridden Insurance
  • Code Duplication
  • Code on the wrong level of abstraction
  • Class basis depending on derivatives
  • Lots of information in a method
  • Dead Code (Unused)
  • Vertical Separation
  • Inconsistency
  • Disorder
  • Responsibility BLEND
  • Static inappropriate
  • Use explanatory variables
  • Function names should say what they do
  • Understand the Algorithm
  • Make logical dependencies
  • Make Polymorphism to instead of If / Else or Switch / Case
  • Follow standard conventions
  • Be precise
  • Encapsulating conditionals
  • Avoid negative conditionals
  • Functions should do something
  • Functions should come down only one level of abstraction
  • Maintain configurable data at high levels
Java
  • Avoid long lists of import using *
  • Not Inherit Constants
  • Prefer to instead of Enums Constants
Names
  • Choose descriptive names
  • Choose names at the appropriate level of abstraction
  • Use standard nomenclature where possible
  • Clear names
  • Use long names for long Scopes
  • Avoid encodings
  • Names should describe side effects
Tests
  • Lack of testing
  • Use a cover tool!
  • Make Trivial tests
  • A test is ignored a question about an ambiguity
  • Test coverage patterns can be revealing
  • Tests should be fast 
Clean Code is not written following a set of rules.
You do not become a software professional learning just a list of what you do and what n is done.

Professionalism and craftsmanship comes from values and discipline in lists of what you should and should not do when creating a code.