077-5719519פקס. 03-7100780 טל. :נוספיםלפרטים www.oracleweek.com
6777129 , מיקודתל אביב 29חומה ומגדל , הדרכה ג'ון ברייס
תוכנית יומית לכנס:
התכנסות וארוחת בוקר – 08:00-09:00
הרצאה – 09:00-10:30
הפסקה קצרה של קפה – 10:30-10:45
הרצאה – 10:45-12:30
ארוחת צהרים – 12:30-13:30
הרצאה – 13:30-15:00
הפסקה מתוקה – 15:00-15:15
הרצאה – 15:15-16:30
שפות התכנות וכלי הפיתוח מתחדשים ומתעדכנים בקצב חסר תקדים ושולטים בכל תעשייה אשר נדרשת להתחרות יובילו אשר ושירותים כלים של נכונה בחירה תבטיח שוטפת טכנולוגית התעדכנות והמקושר. המודרני בעולם לפיתוח קוד מהיר, יעיל ואיכותי, תוך שמירה על גמישות והתאמה לחידושים טכנולוגיים עתידיים. ג'ון ברייס הדרכה
מציעה מגוון עצום של קורסים מבוקשים וייחודיים לקהל הרחב ולקהל המקצוענים.
זמן לפתח >זמן להתפתח... <
קורסי הפיתוח של ג'ון ברייס הדרכה
Java Programming JavaEE 6Programming the .NET Framework 4.0/4.5 with C#Java Web Services, REST & Microservices Extreme JavaReal-time web applications with Node.js and Express.jsExtreme .NET 4/4.5 with C#Implementing DevOps with Java Front End Development with HTML5, CSS3 & jQueryBuilding Web Applications using AngularJSProgramming Embedded LinuxDeveloping Solutions with SharePoint 2013Developing Web/Mobile Applications using ASP.NET MVC 4/5 and jQueryLinux InternalsPython 2 ProgrammingJava Full Stack Programming Developing Android applicationsAngular 4.0 Java Script Full Stack Experts
694769417024069284359337641516969425843357911005885137359134083069675105033774579
שם הקורסמק”ט
לפרטים והרשמה צרו קשר:[email protected] | 03-7100791 - לידיה
www.jbh.co.il | !תהיו חברים
לפרטים נוספים ושליחת קו"ח פנו אל:Talent Recuitment Manager ,מאיה הוף
054-4601413 | [email protected]
אנחנו מרחיבים את סגל המרצים שלנוונשמח לקלוט אותך לשורותינו
אפשרויות תעסוקה מגוונות | משרה גמישה בוקר/ערב | אפשרות לעבודה כפרילאנס
Big Data Cyber DevOps
בואו לגדול איתנויש לנו נבחרת מרצים מנצחת!
ולהעביר הלאה את הידע המקצועי שלכם!
ג’ון ברייס מחפשת את הטאלנט הבא
AWS Cloud Dev Full StackBig Data Cyber AndroidDevOps
למגוון המשרות חפשו בגוגל "מרצים בג'ון ברייס"
Java REST Web Services, Microservices and fullstack
developmentRony Keren
Internet Team
John-Bryce
1
Topics
• Architecture• Tier model
• RPC
• SPA
• REST based Web Services
• Microservices
• Full-stack Development• AngularJS
• Spring Boot
2
Architecture
3
Architecture
• Classic MVC
Designed to separate client flow and interaction from business model that serves the client request and from the final output.
• Traditional MVC as used in web modules – MVC Model 2
MVC Model 2
Model•Represents underlying data and business logic
View•User interface / UI generator•Presents model data
Controller•Connects the model and the view and used to communicate between them
notify
4
Architecture
• In JEE :
Controller – Servlet (automated in JSF)
View – JSP
Model – EJB
J2EE Presentation Tier patterns
• Service To Work – MVC Model 2
• Dispatcher View– MVC Model 1
MVC Model 2
5
Architecture
• Service To Work - MVC Model 2
• Better since:• View and model communicated through value objects
• Trivial server side code is embedded in views
• But, views are still a mix of server & client code...
controllershow data model
view 1
view 2
view 3
get data
dispatch
client
6
Architecture
• Dispatcher View model
• Here, views are used also for ‘controlling’.
• Tightly coupling between views and model
• Can be considered for very simple modules
controllershow data model
view 1
view 2
view 3
set data
dispatch
client
get data
7
Architecture
• Mixing server side code in view causes some serious problems:
Value objects embedded in HTML
It is never just HTML…(CSS, Jscript…)
What if client requires something else than HTML ??
The problem with views
8
Architecture
• List of web frameworks that should help:
• So many… means that:
none is really good enough…
maybe problems can’t be solved with MVC model 2
The problem with views
Echo, Cocoon, Millstone, OXF, Struts, SOFIA, Tapestry, WebWork, RIFE, Spring MVC,
Canyamo, Maverick, Jpublish, JATO, Folium, Jucas, Verge, Niggle, Bishop, Barracuda, Action
Framework, Shocks, TeaServlet, wingS, Expresso, Bento, jStatemachine, jZonic, OpenEmcee,
Turbine, Scope, Warfare, JWAA, Jaffa, Jacquard, Macaw, Smile, MyFaces, Chiba, Jbanana,
Jeenius, Jwarp, Genie, Melati, Dovetail, Cameleon, Jformular, Xoplon, Japple, Helma,
Dinamica, WebOnSwing, Nacho, Cassandra, Baritus, Stripes, Click, GWT, Apache Wicket
9
Architecture
• AJAX – bigger than it seems…
• AJAX technology encourages web modules to ‘talk’ using XML / JSON rather than HTML
The problem with views
10
Architecture
• View of classic architecture
Introduction to AJAX
HTML 2
HTML 1
CGI Engine
Web ServerBrowser
HTTP Request
HTTP Response
11
Architecture
• View of AJAX architecture
Introduction to AJAX
HTML
CGI Engine
Web ServerBrowser
HTTP Request
HTTP Response
12
Architecture
• Using AJAX, web modules can focus on transferring data rather than view
Client receives a single HTML loaded with Jscript functions & callbacks
Jscript caller functions sends request data
Jscript callback processes response and renders it to page
Finally !• web modules input & output can be based on structured, self descriptive text formats
• Future non-HTML clients may use the same modules & data
Moving to single page applications
13
Architecture
• MVC Model 2
Views are generated on server side
• The ‘new’ MVC
Views are handled by the client
Communication between client and server is based on data
Moving to single page applications
controllershow data model
view 1
view 2
view 3
get data
dispatch
client
SERVER
controllerrequest model
get dataClient
SERVER
view data
14
Architecture
• Why is it so important to ‘talk’ via XML/JSON and not ‘draw’ HTMLs ?
• Internet is much more than visiting web-sites…
• Future client of the internet are not going to use keyboards and screens… HTML might be irrelevant
Future internet clients
15
Architecture
• Phones & voice over IP networks
• Smart cards
• Chips
• Nanotechnology
Future internet clients
16
Architecture
But the new ultimate client is US
• No hardware, no UI – just us
• Ability to share data directly from & to our brains
Future internet clients
17
Architecture
• The ‘new’ MVC
Future internet clients
controllermodel
get data
SERVER
view
request
data
18
Architecture
What is JSON ?
• Java Script Object Notation
• Also self-descriptive text based protocol
• Used for marshalling and un-marshalling Jscript objects
XML vs. JSON
{
“people”: [
{ “name": “David“, “age": “20“},
{ “name": “Dana“, “age": “25“},
{ “name": “Eve“, age": “30“},
]
}
19
Architecture
Why is it an alternative for XML ?
• Better for small applications (like client side apps)
No parsers are needed
Contracts are less critical
Light integration
• Jscript and Android developers prefers it
Got popular APIs for binding, handling & presenting JSON based data
XML vs. JSON
20
Architecture
JAXB supports JSON as well
• Root class is denoted with @XMLRootElement
• No schema is needed – all adjustments are done with JAXB annotations
JSON has no strong standards as XML (yet..)
XML vs. JSON
21
RPC
• Architecture & terms
• RPC in Java & JEE
• RPC Framework requirements
• XML for RPC – Web services
22
RPC
Remote Procedure Call
• Client invokes method on a Remote Object over a network
• Client obeys a contract which is the Remote Interface
• Remote object is a resource
• Remote method is a service
• In order to communicate both client & server uses sockets
Socket communication is determined according to the remote interface
Stub - Client side socket
Skeleton – server side socket that is used as a proxy to the remote object
Architecture & Terms
23
RPC
Architecture & Terms
skeleton
RemoteObject
get data
SERVERRemoteInterface
CLIENT
stub
public int sum (int x, int y);
public int sum (int x, int y){return x+y;
}
String action=in.readUTF();int x=in.readInt();int y=in.readInt();out.write(ro.invoke(action,x,y));
out.writeUTF(“sum”);out x=out.writeInt(5);out y=out.writeInt(6);int result=in.readInt();
User input is : 5, + , 6
Result is : 11
24
RPC
• RMI – Remote Method Invocation
provides a 2-tier infrastructure for Java clients
rmic – is a compiler that generates stubs & skels
• IDLJ
provides a 2-tier infrastructure for IIOP based clients
idlj – generates Java stubs & skels out of IDL files
• EJB – Enterprise Java Beans
provides a full 3-tier infrastructure
supports all protocols
RPC in JEE
25
RPC
• EJB – Remote Objects
Synchronous• Stateless Beans (pooled)
• Stateful Beans (passivated)
• Supports HTTP, Java IO, IIOP
A-synchronous• Message Driven Beans (JMS)
• Both P2P & Publisher-Subscriber methods are supported
RPC in JEE
26
RPC
• 2-tier vs. 3-tier RPC
• Stateless EJBs are pooled and served on-demand
RPC in JEE
skeleton
RemoteObject
get data
RMI Containerstub
skeletonstub
skeletonstub
skeletonstub
skeleton
EJB Container
stub
skeletonstub
skeletonstub
skeletonstub
Manager
RO Pool
RO
RORO
RO
27
RPC
• For server development
Map services to generate a contract
Expose the contract
Instantiate & publish the resource (or resource pool)
Create skeleton when requested
• For client development
Generate stub according to a given contract
RPC Framework Requirements
28
RPC
• Main goal of XML is for application integration
• If the contract is in XML format it can be:
describing services written in any language
used by any client
• If the stubs & skels will ‘talk’ via XML:
each may be written in a different language
xsd types can be used to describe primitives & objects
XML for RPC – Web Services
29
RPC
XML for RPC – Web Services
skeleton
RemoteObject
get data
SERVERXMLCLIENT
stubXML Request
XML Response
30
REST based Web Services
• Parallel computing
• NoSQL DBs
• Saving bandwidth & faster response
Introduction to REST
HTTP for RPC
JAX-RS - RESTful
• Creating a Java service
• Publishing & testing
• Using Jersey client API for generating clients
• Tokens & session management
• WADL
• JEE support
Big data – the challenge
31
REST based Web Services
• From single & concurrent to parallel & cloud computing
• Using NoSQL DB in addition to the classic relational DB
• Saving bandwidth & performance
XML is a very inefficient protocol uses tags to wrap data
XML forces the use of parsers
SOAP is an additional protocol on top of HTTP
Big data – the challenge
SOAP Message
SOAP Envelope
SOAP Attachments
SOAP Header
SOAP Body
SOAP Elements
HTTP Message
HTTP headers
HTTP body
32
REST based Web Services
REST – REpresentational State Transfer
• is an HTTP ‘enrichment’ that provides advanced RPC
passing data in any format including XML, JSON and binary data
REST can be counted as part of HTTP unlike SOAP which is a separate protocol
Introduction to REST
33
REST based Web Services
Client may use the following HTTP features in order to invoke a service:
• URI – path can determine the endpoint class and even method
• ACCEPT header – used by the client to specify response MIME type
service methods may result in different MIME types
client call can be delegated to method that produces the MIME type it expects
• METHOD – GET, POST, DELETE, PUT, HEAD
each method can be mapped to several HTTP-methods
client call is delegated to the method matches client HTTP request method
HTTP for RPC
34
REST based Web Services
• Suggested way to implement business according to HTTP method
HTTP for RPC
CollectionSingle elementHTTP Method
Fetch the whole collectionFetch an element from a collection
GET
Override one collection with a new one
Replace or create new element in a collection
PUT
Add new value to a collectionAssign a value to an objectPOST
Delete the entire collectionDelete a specific element from a collection
DELETE
35
REST based Web Services
• Java API for creating RESTful based web-services
Uses Jersey implementation as RI
• Uses annotations much like JAX-WS
• 4 principles to make it fast and simple:
Identify – tracking endpoints is based on URI
Unified interface – using HTTP methods (GET,POST,DELETE,PUT…)
Self descriptive content – XML , JSON…
Stateful interaction – by attaching session data or using tokens
• JAXB used for XML and JSON
JAX – RS - RESTful
36
REST based Web Services
• Acts as a REST server
Provides a servlet to proxy REST activity
Provides basic client capabilities for testing
Default scope for services is ‘request’
Jersey Client API is not part of the standard
Java RI is called Jersey
37
REST based Web Services
• @Path
Class & method level
Sets the URI pattern that points to the underlying resource
May take path parameters to use later
When used in both class & method:
JAX – RS Annotations
@Path("/helloworld/{userName}")
@Path("/helloworld") public class HelloWorldService { …
@Path("/helloworld") public class HelloWorldService {
@Path("/doIt") public void doSomething(){…
38
REST based Web Services
• @GET/ @POST/ @PUT/ @DELETE
Method level or class level (for all methods)
Define the HTTP request type that the method replies to
JAX – RS Annotations
@Path("/helloworld") public class HelloWorldService {
@POSTpublic void doSomething(){…
39
REST based Web Services
• @PathParam
Method level
Maps a @Path parameter to a method parameter
JAX – RS Annotations
@Path("/helloworld/{userName}")public class HelloWorldService {
@GETpublic String getUser(@PathParam("userName") String user){ …
40
REST based Web Services
• @Produces / @Consumes
Method level
Specifies the MIME type the operation produces / consumes
• @QueryParam & @DefaultValue
Parameter level
Specifies HTTP request value & default values
JAX – RS Annotations
@GET@Produces(“text/plain") public String getTextData(){ …
@DefaultValue("2") @QueryParam(“num") int num;…
41
REST based Web Services
• Step 1 - Create web project with some business logic
Building and publishing RESTful module:
package hello.in.different.formats;@Path("/hello")public class Hello {
@GET@Produces(MediaType.TEXT_PLAIN)public String sayTextHello() { return "Hello JAX-RS !"; }
@GET@Produces(MediaType.TEXT_XML)public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello JAX-RS" + "</hello>"; }
@GET@Produces(MediaType.TEXT_HTML)public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello JAX-RS" + "</title>" + "<body><h1>" + "Hello JAX-RS " + "</body></h1>" + "</html> "; }
}
This format can be shown in browsers
42
REST based Web Services
• Step 2 – Configure Jersey servlet and register “hello” WS
Building and publishing RESTful module:
<?xml version="1.0" encoding="UTF-8"?> WEB-INF\web.xml<web-app …>
<display-name>Hello In Different Formats</display-name> <servlet>
<servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param>
<param-name>com.sun.jersey.config.property.packages</param-name> <param-value>hello.in.different.formats</param-value>
</init-param> </servlet><servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name><url-pattern>/rest/*</url-pattern>
</servlet-mapping> </web-app>
43
REST based Web Services
• Client may choose format byspecifyingmedia-type:
Combining with JAXBpackage hello.in.different.formats.jaxb;@Path("/phoneBook")public class Hello {
@GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public Entry getEntry(String client name) {
Entry e = new Entry(); //load data into entry by the given namereturn e;
}
}
These format involves application format pre-processing - JAXB
package hello.in.different.formats.jaxb;
@XMLRootElementpublic class Entry{
private String name;private String phone;private String cellPhone;
//public getters and setters…}
System.out.println(service.path("rest").path(“phoneBook").accept(MediaType.APPLICATION_JSON).get(String.class));
JAXB annotationto enable
marshalling & un-marshalling Entry
44
REST based Web Services
• When assigning structured data (XML/JSON)
Make sure your class has default constructor
JAXB uses set() methods when un-marshaling
Clients may assign JSON/XML
Combining with JAXB
package hello.in.different.formats.jaxb;@Path("/phoneBook")public class Hello {
@GET@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})public Entry editEntry(Entry toEdit) {
// edit entry…return e;
}
}
package hello.in.different.formats.jaxb;
@XMLRootElementpublic class Entry{
private String name;private String phone;private String cellPhone;
public Entry(){}…
}
45
REST based Web Services
• Step 3 – Deploy, run and test the service
Use this URL to invoke the service:
Note that the Jersey client is seeking for HTML formats
Building and publishing RESTful module:
http://ip:port/root-context/rest/hello
Root Context, usually your project name
The URL pattern to call Jersey servlet
The name of the resource (service)
46
REST based Web Services
• Jersey offers simple client API
Creating RESTful client
public class Test { public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); URI baseUri = UriBuilder.fromUri("http://ip:port/hello.in.different.formats").build();WebResource service = client.resource(baseUri ); // Get plain textSystem.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class)); // Get XMLSystem.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class)); // The HTMLSystem.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));
}
get(..) / post(..) / put(..) / delete(..)
47
REST based Web Services
• It is very easy to use Servlets API in your services
• Why would we do it?
Scope management request, session, application
Do some custom request / response processing
• How do we use it?
Simply inject anything needed from Servlets API• Request, response, context…
• Use @Context
Working with CGI
@Path("/phoneBook") public class Hello {
@Context private HttpServletRequest req;@Context private ServletContext ctx;…
}
48
REST based Web Services
• On server side – simply inject HttpServletRequest
Use req.getSession(..) in order to• obtain HttpSession instance
• embed a session cookie
• Use session’s attributes to hold user session state
• On client side – you need to plant the session cookie on each request
To do that we obtain all response cookies
Then we place all cookies (including session cookie) on your request via builders
Builder is held in a WebResource object
Since WebResource are immutable – the only way to load cookies on it is via builder
Session management
49
REST based Web Services
• Server side
• Client side
Session management
@Path("/shop") public class StoreCart {
@Context private HttpServletRequest req;…public void startSession(){
HttpSession session = req.getSession(true); }
ClientResponse resp = service.path(“somePath").accept(…).get(ClientResponse.class);
WebResource wr=service.path(“someOtherPath");WebResource.Builder builder=wr.getRequestBuilder();for(Cookie c:resp.getCookies()){
builder.cookie(c);}…builder.accept(…);
• get response with session cookie• build a request (WebResource)• obtain Builder in order to update request• load all cookies from response onto builder• submit request via builder
50
REST based Web Services
• In web.xml:
1-Define roles
2- Set authentication method (also in web.xml)
Applying declarative security
<security-role><role-name>admin</role-name>
</security-role>
<login-config><auth-method>BASIC</auth-method>
</login-config >
51
REST based Web Services
• In web.xml:
3-Map roles to url patterns of your RESTful servlet
Applying declarative security
<security-constraint><web-resource-collection>
<url-pattern>/rest/*</url-pattern><http-method>POST</http-method>
</web-resource-collection><auth-constraint>
<role-name>admin</role-name></auth-constraint>
</security-constraint>
52
REST based Web Services
• 4- Use security annotations to declare roles access on your service
Applying declarative security
package hello.in.different.formats;@Path("/hello")@RolesAllowed({“admin”,”guest”})public class Hello {
@RolesAllowed(“admin”)@GET@Produces(MediaType.TEXT_XML)public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello JAX-RS" + "</hello>"; }
@PermitAll@GET@Produces(MediaType.TEXT_HTML)public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello JAX-RS" + "</title>" + "<body><h1>" + "Hello JAX-RS " + "</body></h1>" + "</html> "; }
}
Security annotations: • @RolesAllowed – lists permitted roles• @DenyAll – allows non-logged users• @PermitAll – permits all declared roles• None – available to anyone
53
REST based Web Services
• Add ‘HTTP Basic Authentication’ header to the HTTP
• May use Jersey HttpBasicAuthFilter to do that
Adds the header only if doesn’t exist
Accepts username and password
Username and password are for creating user Principal
Principals are then mapped to application roles
Performing BASIC authentication
54
REST based Web Services
• Performing BASIC authentication – example: public class Test { public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.addFilter(new HTTPBasicAuthFilter("username", "password“ ));URI baseUri = UriBuilder.fromUri("http://ip:port/hello.in.different.formats").build();WebResource service = client.resource(baseUri ); …
}
55
REST based Web Services
• XML format
• Describes how to use a web resource
Path
Request method
Request parameters
Response format
• Target – REST client stub auto-generation
• Status
WADL was promoted by SUN to become a W3C standard - not yet
Java support for WADL • By open source tools (like AXIS for XML based WS)
• Wadl2java utility…
• Not included in JAX-RS & JEE6
Web Application Description Language - WADL
56
REST based Web Services
Main elements
• <application> - the root element
• <grammars> - includes *.xsd which may describe response content (if it
is XML based) – optional
• <resources> - contains all the resources described in the document
• <resource> - describe the resource itself, holds the path to it
<method> - describes a method for the invocation (GET/POST….)• <request> - describes the request and response structure
• <param> <option> - describe a parameter name, type (xsd:) and optional values
• <representation> - specifies request body MIME-TYPE
• <response> - describes the response status code and its MIME type
• <representation> - specifies response body MIME-TYPE
WADL
57
REST based Web Services
• WADL – simple example
<application xmlns="http://wadl.dev.java.net/2009/02"> <resources base="http://example.co.il/rest">
<resource path="employees"> <method name="GET"/> <method name="POST"/>
</resource></resources>
</application> Calling to http://example.co.il/rest/employeesis available via POST & GETPOST – probably add a new employeeGET – fetch employee list
58
REST based Web Services
WADL - placeholder for path-param
<application xmlns="http://wadl.dev.java.net/2009/02"> <resources base="http://example.co.il/rest">
<resource path="employees"> <resource path="{empId}">
<param required="true" name="empID"/> <method name="GET"/>
</resource></resource>
</resources></application>
Calling to http://example.co.il/rest/employees/1234is available via GETempId will get the value 1234 and delegates it to the empID method parameter
59
REST based Web Services
WADL - placeholder for query-param
<application xmlns="http://wadl.dev.java.net/2009/02"> <resources base="http://example.co.il/rest">
<resource path="employees"> <method name="GET">
<request> <param required="false" default="1" name="empID"/>
</request></method></resource>
</resources></application>
Calling to http://example.co.il/rest/employees?1234is available via GETempId will get the value 1234 and delegates it to the empID method parameter
60
Microservices
61
Introduction
• Microservices – Architectural style of composing application out of loosely coupled services.
• Services are mostly fine-grained
• Protocols are common and lightweight
• “Microservices is a variant of the service-oriented architecture (SOA) architectural style that structures an application as a collection of loosely
coupled services” (wiki)
62
• History
• Web-Services (XML based)
• EAI – Enterprise Application Integration
• Web-Services (REST based)
• SOA – Service Oriented Architecture (both XML & REST)
• Microservices (mainly REST)
Introduction
63
Introduction
• Monolithic Architecture pattern
• Classic pattern
• In use for most applications
• Structure: Single application with multiple modules & tiers All modules are part of the application
All modules are somehow depends on others
Deployed as one unit to a domain
Domain
DB
Server(s)
Application
web services logic DAO
64
Introduction
• Microservice Architecture pattern
• New approach
• Structure: Application is actually a flow between services
All modules are broken down to fine-grained standalone services
Services may interact with others and use different types of storages
Each service is separately : maintained, deployed, monitored
Domain
DB
Server(s)
service
Server(s)
service
Server(s)
service
Server(s)
serviceServer(s)
service
Server(s)
service
65
Hotel Domain
members
customers
roomAv.warRoomAvailabilityService
members.warMembershipService
payment.warPaymentService
Hotel System & Storage
Introduction
66
Introduction
• Each services may have:• its contract (interface)
• its own deployment settings
• Its own container / server instance(s)
For new developments - design for service
For existing application - decompose
67
Introduction
• Pros• Improved modularity • Easier to maintain • Easier to replace• Strong version control – rollbacks can be non-issue • Better unit testing • Parallel development • Continuous refactoring • Continuous deployment• Service may count on multiple alternative services for failover • Easily automated • Focused & independent administration
68
Introduction
• Cons• Intensive HTTP communication (still text based…)
• Going stateless? Not always… and then what?
• 2-phase commit is not supported in any Microservice – so can’t be used…
• Higher costs – each Microservice comes with its infrastructure….
• When Microservices span over different systems or divisions few challenges emerges: Team communication
Need in good documentation
Testing is hard when more than single service is involved
• Not exactly the rapid way to develop smart tiny engines or prototypes for Startups
69
Introduction
• Some additional points:
• Being standalone doesn’t mean you can’t use shared memory & resources
• HTTP is mostly used but other protocols can perform intra-service-
communication
• Independent deployment is very important for automation
70
Introduction
• Some additional points:
• Pack services according to roles:
Web integration (Front-end, REST WS)
Services – business facades & logic (billing, learning, reporting, notifications,
logistics…)
Repositories – DAOs, DBs & 3rd parties
• Different Microservices of the same ‘application’ can
• be written in different languages
• use different DB implementations
• run on different platforms and require a different deployment configuration
71
Introduction
• Scale cube & Microservices• Y – scale by running different parts of the application
• X – scale by running copies of the application
• Z – scale by splitting storage
• Microservices corresponds to the Y axis of the cube
Y axisfunction
decomposition
X axisfunction cloning
Z axisdata partitioning
72
Relevance
• Microservices are relevant for 3 trendy fields:
1. Fullstack development
2. BigData
3. DevOps
73
Relevance
• Fullstack development
• Fullstack developers have the following skills:
• Create some business logic
• Create API
• Provide SPA
• Deploy to a server
• Configure DB & other 3’rd parties
• Fullstack is very important as software development
• becomes more services-oriented
• requires intensive updates and new feature releases
74
Relevance
• BigData
• BigData forces:
• Parallel computing
• Dynamic domains (auto-scale)
• Effective resource management (especially for when using public clouds)
• In order to gain such capabilities it is better for application to
• use simple deployment schemes with minimal dependencies
• split pieces of software for optimal resource usage
75
Relevance
•DevOps
• Project development phases automation• One again…intensive releases & new features• Things must get automated, and when comes to
software in means: Test automation Version control Continuous deployment Continuous integration Automated monitoring and feedback system
• Automating all these aspects with monolithic architecture is mostly impossible
• When things a fine-grained they can be automated in most easy and sophisticated ways
76
Relevance
• DevOps – Microservices• Every Docker host is an active Image
• Kubernetes orchestrates Docker images
Ku
ber
net
es A
PI
DockerHost
DockerHost
Hardware
Hosting OS
Docker Engine
server
service
Hardware
Hosting OS
Docker Engine
server
service
DockerHost
Hardware
Hosting OS
Docker Engine
server
service
Kubernetes
ControllerHost
Network
77
Microservices Patterns
We may understand the meaning of implementing Microservices just scanning Microservices Patterns
78
Decomposing Patterns
• Relevant for existing monolithic systems
• Related patterns:
• 1 - Decompose by business capability
• 2 - Decompose by subdomains
79
Deployment Patterns
• How Microservices are deployed?
• Related patterns:
• 1 - Multiple service instances per host
• 2 - Service instance per host
• 3 - Service instance per VM
• 4 - Service instance per Container
• 5 - Server-less deployment
• 6- Service deployment platform
80
Application Infra Patterns
• Configuration is a major concern when decomposing into multiple services
• Assumes each service requires different configuration
• Related patterns
• 1 – Microservices Chassis (logs, health-checks, performance metrics.. )
• 2 – Externalized Configuration
81
Communication Patterns
• How does services communicate with each other?
• How does remote clients communicate with services?
• Related patterns
• 1 – RPC
• 2 – Messaging
• 3 – Domain Specific Protocol
• 4 – Local Communication / Referencing
82
External API Patterns
• How should Microservices façade be implemented?
• Related patterns
• 1 – API Gateway – single facade
• 2 – Backend for Frontend – multiple facades
83
Service Discovery Patterns
• Related patterns
• 1 – Service Registry
• 2 – Client-Side Discovery
• 3 – Server-Side Discovery
• 4 – Self Registration
• 5 – 3rd Party Registration
84
Intra Invocation Patterns
• Related patterns• 1 – Circuit Breaker – track invocations, respond to failures
85
Data Related Patterns
• Related patterns
• 1 – Database per Service
• 2 – Shared Database
• 3 – Saga Transactions
• 4 – Data Composition
• 5 – Command Query Separation
• 6 – Event Sourcing
86
Application Security Patterns
• Related patterns
• 1 – Access Tokens
• 2 – Token-Role Map
87
Monitoring Patterns
• These patterns relates to logging, exception handling and monitoring aspects and they should be applied to Microservice based systems
• Related patterns
• 1 – Log aggregation
• 2 – Application Metrics
• 3 – Audit Login
• 4 – Exception Tracking
• 5 – Health Check API
• 6 – Deployments & Changes Logging
88
Microservices Testing
• Microservice testing
• Like unit-tests Isolated
Simple
Cheep
Fast
• Will not provide application level QA
• Service Integration Contract testing
• Gateway test suites
• Each suite tests specific façade operation
• All involved underlying services must pass the test
89
Microservices Versioning
• Create new services every-time there is a significant change
• When meaningful upgrade is made or major logic fix is applied
Do not perform fix / upgrade on existing services
Create new one instead (!)
Keeping old versions allows you to
• Rollback back fixes & releases
• Provide multi-version support
• Each gateway proxies to its relevant versioned services
90
The Big Picture
91
SpringBoot
92
Topics
• Introduction to SpringBoot
• Relevance
• Maven projects - overview
• Downloading SpringBoot configuration with SpringMVC
• Configuring Eclipse Maven project
• Creating REST Microservice
• Running as stand-alone configuration with Tomcat instance
• Exporting as executable jar & launching
• Microservices communication with Spring restTemplate
93
Introduction to SpringBoot
• SpringBoot is a spring based repository which provides:
• Ready-to-use stand alone Spring application configurations
• Embedded Tomcat & Jetty as hosting containers
• Support for dependency customizations (WEB, JPA, JMS….)
• Configuration code or XMLs elimination
94
Introduction to SpringBoot
• SpringBoot uses @Conditional behind the scene • @Conditional allow different configuration to be applied
• The decision making is implemented in conditional factory classes
• @SpringBootApplication extends @EnableAutoConfiguration• @CompoonentScan is used to automatically scan @Beans
• Scan is done on current and sub directories
SpringSpringBoot
user
95
Relevance
• DevOps & Automation
• Project become more & more agile
• Development moves into service-oriented integration
• Automated configurations and instances is easy when services are stand-alone units
• Microservices are fine-grained services with embedded web servers
• SpringBoot
• provides rapid mechanism to create stand-alone configurations
• great solution for Java based Microservice – just add WEB dependency
96
Relevance
• Full-stack Java Development
• Full-stack developer must be able to create and configure web services and Microservices
• Full-stack developers must have easy configuration and administration tools in order to focus on business logic, but mostly- ClientMVC
• SpringBoot
• Encapsulated complex configurations
• Supports rapid development with SpringMVC and other extensions
97
Projects
• Maven build automation tool• Uses pon.xml to define package and dependencies
• Code is downloaded from Maven Central Repository
• The code is stored in C:\Users\{your_user_name}\.m2
• Maven with IDEs• Maven projects are bounded to the .m2 directory
• Projects can be updated at any time, usually after editing pom.xml
• Project can be exported with all Maven dependencies as stand-alone jar
98
Maven Projects
• SpringBoot configuration pom.xml example: <?xml version="1.0" encoding="UTF-8"?>…
<groupId>com.example</groupId><artifactId>boot</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging>
<name>boot</name><description>Demo project for Spring Boot</description>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.4.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent>…
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>…
99
Maven Projects
• Eclipse Maven Projects
• Base Structure• src\package.name – where you add packages and classes
• src directory – where java source copies are automatically stored
• target directory – where classes automatically generated from source copies
• pom.xml
• When editing pom.xml• right click your project and choose Maven->Update Project
• Notice that Eclipse is downloading libraries and update builds
100
Maven Projects
• Eclipse Maven Projects
• Exporting Maven projects as stand-alone jars• right click your project and choose ->Run As>Maven Install
• jar file is default location is: workspace\{your_project}\target
• If exported as executable jar – use java –jar {your_jar_name}.jar to launch
101
Maven Projects
• Maven build automation tool• Uses pom.xml to define package and dependencies
• Code is downloaded from Maven Central Repository
• The code is stored in C:\Users\{your_user_name}\.m2
• Maven with IDEs• Maven projects are bounded to the .m2 directory
• Projects can be updated at any time, usually after editing pom.xml
• Project can be exported with all Maven dependencies as stand-alone jar
102
Downloading SpringBoot configuration
• Visit: https://start.spring.io
• Spring Initialzr builds SpringBoot configurations with• Maven / Gradle• Java / Kotlin / Groovy• Various SpringBoot versions
• Default is Maven / Java / SpringBoot 1.5.*
• Dependencies can be added
• The only requirement for stand-alone Microservice is WEB dependency• Adds SpringMVC & Embedded default web server (Tomcat)
• Press ‘Generate Project’ to download a complete Maven project plus basic code example & test packed in ZIP format
103
Downloading SpringBoot configuration
104
Downloading SpringBoot configuration
• Basically, any spring extension can be added later by editing pom.xml but,
• Here’s a list of keywords to search for getting a ready to use pom.xml
• Main dependencies• DB
• JDBC • MySQL• PostrgeSQL• SQL Server• AWS JDBC• JPA
• NoSQL & In memory• REDIS• MongoDB & Embedded MongoDB• Cassandra
105
Downloading SpringBoot configuration
• More dependencies
• Web• SpringMVC• Jersey JAX-RS• Web Services JAX-WS• Vaadin (Java web framework)• ApacheCXF• WebSocket
• Others• Security – Spring Security• Elasticsearch• Mobile – Spring Mobile for Mobile web apps• Messaging
• KAFKA• JMS – Active MQ
• Spring Cloud
106
Configuring Eclipse Maven project
• Importing Maven project to Eclipse workspace• Simplest way is to generate a new Maven Project
• When generating new project make sure the following fields:
• groupID
• artifactId
• Version
has the same values as in pom.xml (located at your downloaded project ZIP file)
• Now, simply override your eclipse project pom.xml with the project ZIP pom.xml
• Update project from Maven menu in order to download all dependencies
• You may import the examples included in the ZIP file as well by placing it under:
your project -> src/main/java & src/test/java
107
Configuring Eclipse Maven project
• Changing to Jetty• Edit pom.xml
• Update project
…<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId><exclusions>
<exclusion> <groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-
tomcat</artifactId> </exclusion>
</exclusions> </dependency>
<dependency><groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId>
</dependency> …
108
Creating REST Microservice
• Create new class under srv/main/java• Make sure to use package(s) declaration
• You may edit sample controller which was auto generated
• Spring Boot • @SpringBootApplication
• General class level annotations• @Controller
• @EnableAutoConfiguration
• When using Dependency Injections make sure to:• Put @ComponentScan on class level
• Make sure all DI classes are at the same or sub packages
109
Creating REST Microservice
• Main Spring & Spring MVC annotations• @Autowired
• @Component
• @Scope("singleton") / “request” / “session”
• Main SpringMVC REST annotations• @RequestMapping value="" method=""
• @PathVariable
• @QueryParam
• @ResponseBody
110
Creating REST Microservice
• Main method• In order for the service to be executable – a main method is implemented
• Main() will launch all configurations including Tomcat
…@Controller@SpringBootApplicationpublic class SampleController{…
public static void main(String[] args) throws Exception {SpringApplication.run(SampleController.class, args);
{{
111
Creating REST Microservice
• Adding clients
• After launching service, there 2 common client options:• Java REST API used to test or invoke other Microservices
• Client API – static pages based on HTML & JavaScript
• Later we’ll discuss using Spring restTemplate as Java REST client API
112
Creating REST Microservice
• Adding static content• Using static web content (SPA, Client MVC frameworks)
• SpringBoot automatically scans and deploy static web content from:• /META-INF/resources/
• /resources/
• /static/
• /public/
• None is included in the plain web template - so create one• Place all HTMLs, CSSs & JS in directories inside
Calling: http://localhost:8080/hello.html
113
Running as stand-alone with Tomcat instance
• Launching from Eclipse is easy• Simply run your controller as a Java Application
• Controller is automatically deployed and available by default at:
http://localhost:8080/
114
Running as stand-alone with Tomcat instance
• Change default port• Port can be set with system properties
• Spring loads system properties from src/main/resources/application.properties file
• Since default configuration comes with no configuration files – you need to create it
src/main/resource/application.properties
server.port = 8090
115
Exporting as executable jar & launching
• SpringBoot comes with a Maven plugin
• Maven is capable if downloading and including dependencies when exporting projects – repackaging
• In order to generate a stand-alone jar with all Maven dependencies:• Right click your project and choose ->Run As ->Maven Install
• jar file is default location is: workspace\{your_project}\target
• To launch jar use the following command:
java –jar { jar_name }.jar
116
Microservices communication with RestTemplate
• We can use SpringBoot to create, export and launch Microservices
• Since Microservices are stand-alone units• In many cases one Microservice invokes another
• We need REST client API in our SpringBoot configuration
• Configuring Spring restTemplate client • Add this to pom.xml
• Update project
…<dependency>
<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency></dependencies>…
117
Microservices communication with RestTemplate
• Example: Getting Quote from StockMicroservice
• StockMicroservice getQuote() :
• Quote Bean:
…@RequestMapping("/quote/{symbol}")@ResponseBodypublic Quote getQuote( @PathVariable(“symbol”) String symbol
){Quote q=new Quote();q.setSymbol(symbol);q.setValue(db.loadCurrValue(symbol));return q;
}…
@JsonIgnoreProperties(ignoreUnknown = true) public class Quote{
private String symbol;private double value;
getXXX()/setXXX() {
Calling: http://localhost:8080/quote/ABC
Output example: {“symbol":“ABC",“value":333.33}
118
Microservices communication with RestTemplate
• Example: Getting Quote from StockMicroservice
• Another Microservice that uses restTemplate to get Quote:
…public void callStockMicroservice(){
RestTemplate restTemplate = new RestTemplate();Quote quote = restTemplate.getForObject("http://localhost:8080/quote/ABC",
Quote.class);System.out.println(quote.getSymbol()+”-”+quote.getValue());
{
…
119
120
Top Related