Share
Embed
Java/Spring and Node.JS side by side
presentation from Thibault Weintraub on October 22
SingaSUG
October 22, 2015
Transcript
33 slides
-
1995 Sun Microsystems Cross-platform Applet dedicated to the Web 2009
Ryan Dahl, Joyent, Node.js Foundation Asynchronous event driven framework built on top of Google V8 JS engine 2002 Pivotal Software Inversion of control container with extensions to ease JEE development JAVA SPRING NODE.JS -
Rewrote account overview page • Using JavaScript on both the
front-end and the back-end removed an artificial boundary between the browser and server, allowing engineers to code both • Built almost twice as fast with fewer people • Written in 33% fewer lines of code • Constructed with 40% fewer files • Double the requests per second vs. the Java application • 35% decrease in the average response time -
Moved From Rails, 27 Servers Cut And Up To 20x
Faster • Much better performance and lower memory overhead than other tested options, running up to 20x faster in some scenarios • Programmers could leverage their JavaScript skills • Front-end and back-end mobile teams could be combined into a single unit • Servers were cut to 3 from 30. Enough headroom remains to handle 10x current levels of resource utilisation -
Open Source project www.walmartlabs.com Powers our highly available real time
push notifications Completely re-engineered the application to increase efficiency and improve the partner and customer experience -
“Node.js powers our web applications and has allowed our teams
to move much faster in bringing their designs to life” “On the server side, our entire mobile software stack is completely built in Node. One reason was scale. The second is Node showed us huge performance gains” “Node’s evented I/O model freed us from worrying about locking and concurrency issues that are common with multithreaded async I/O” -
library / module log4j spring-xyz libraryZ libraryY libraryX … …
Most of the Java containers use 1 Class Loader lib1.2 -
library / module archiver express moduleX m1 … … …
… m1 m1 m1 Modules work like JavaScript closure -
Spring framework an IoC container that eases maintaining configurations and
switching implementations -
public class MyComponent { @Autowired private PushService pushService; @PersistenceContext private
EntityManager entityManager; public Message process(Message msg) { … } } var config = require('config'); var push = require('./push'); var dao = require(config.dao); function process(message) { … } module.exports = { process: process }; www.npmjs.com/package/config a popular module to manage development to production configurations Node.js Spring IoC -
Spring is also a series of projects that helps you
build web and enterprise applications -
JavaScript / Node.js WEB app Hybrid app Server DB Push
You already know the language! -
<!DOCTYPE html> <html> <head> <script src="moment.js"></script> <script type="text/javascript"> function diff()
{ var start = document.forms[0].start.value; var end = document.forms[0].end.value; console.log(moment(end).diff(moment(start), 'days')); } </script> </head> <body> <form action="/api" method="POST"> <label for="start">Start</label> <input name="start" type="text"> <label for="end">End</label> <input name="end" type="text"> <input type="submit"> <input type="button" value="diff" onclick="diff()"> </form> </body> </html> @RequestMapping( path = "/api", method = RequestMethod.POST, produces = "application/json") public String api( @RequestBody String start, @RequestBody String end) { DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd"); LocalDate lStart = LocalDate.parse(start, dtf); LocalDate lEnd = LocalDate.parse(end, dtf); ObjectNode res = JsonNodeFactory.instance.objectNode(); int diff = Days.daysBetween(lStart, lEnd).getDays(); return res.put("diff", diff).toString(); } Web Server Web Page -
<!DOCTYPE html> <html> <head> <script src="moment.js"></script> <script type="text/javascript"> function diff()
{ var start = document.forms[0].start.value; var end = document.forms[0].end.value; console.log(moment(end).diff(moment(start), 'days')); } </script> </head> <body> <form action="/api" method="POST"> <label for="start">Start</label> <input name="start" type="text"> <label for="end">End</label> <input name="end" type="text"> <input type="submit"> <input type="button" value="diff" onclick="diff()"> </form> </body> </html> var express = require('express') , bodyParser = require('body-parser') , moment = require('moment'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(__dirname + '/public')); app.post('/api', (req, res) => { var start = req.body.start; var end = req.body.end; var diff = moment(end).diff(moment(start), 'days'); res.json({ diff:diff }); }); app.listen(3000); Web Server Web Page -
Run tests, package, minify, zip, manipulate files, git, generate manuals,
upload, … Building, Testing 25% of our time in dev. -
Building It's much more powerful to use a full language
than writing build scripts from a fixed set of directives -
Building gulp.task('scripts', function() { return gulp.src(findSources()) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('default')) .pipe(concat('main.js')) .pipe(gulp.dest('dist/assets/js'))
.pipe(rename({suffix: '.min'})) .pipe(uglify()) .pipe(gulp.dest('dist/assets/js')) .pipe(notify({ message: 'Task complete' })); }); -
Testing Java / Spring, HTTP Client + Thread sleep? Node.js,
request + setTimeout but will it be a callback hell? Write a test that invokes the /api 4 times, in sequence with 1 second delay -
Callback hell function test(body, callback) { // POST 127.0.0.1:3000/api }
test(body1, function(err, res) { test(body2, function(err, res) { test(body3, function(err, res) { … }); }); }); Move to Promises -
function test(start, end, diff) { return new Promise((resolve, reject) =>
{ request( { method: 'POST', uri: 'http://127.0.0.1:3000/api', form: { start, end } }, (error, res, body) => { if (error || JSON.parse(body).diff !== diff) { reject(error || 'diff do not match'); } else { resolve(); } }); }); } function wait1s() { return new Promise((resolve, reject) => setTimeout(() => resolve(), 1000)); } test('2015-01-01', '2015-01-10', 9) .then(() => wait1s()) .then(() => test('2015-01-01', '2015-01-11', 10)) .then(() => wait1s()) .then(() => test('2015-01-01', '2015-01-04', 3)) .then(() => wait1s()) .then(() => test('2015-01-01', '2015-01-06', 5)) .then(() => console.log('All tests passed')) .catch(err => console.error(err)); -
Food for thought Using the same language everywhere is a
huge value for us Does a strongly typed language help you? There is a trend shared by the community to publish Node.js modules easy to use Asynchronous code has never been so easy -
Food for thought Source code documentation is a key factor
when building an application with JavaScript The Node.js ecosystem does not compete yet with some sophisticated libraries It’s almost impossible to know what your Node.js program is doing at all times