Node.js on the JVM

43
JavaScript Evented I/O & more JavaScript Evented I/O & more for the Java Enterprise Ecosystem for the Java Enterprise Ecosystem Niko Köbler ( ) @dasniko {JavaScript}Training Node.js on the JVM Node.js on the JVM

Transcript of Node.js on the JVM

Page 1: Node.js on the JVM

JavaScript Evented I/O & moreJavaScript Evented I/O & morefor the Java Enterprise Ecosystemfor the Java Enterprise Ecosystem

Niko Köbler ( )@dasniko{JavaScript}Training

Node.js on the JVMNode.js on the JVM

Page 3: Node.js on the JVM

I'm to hire!I'm to hire!

Page 4: Node.js on the JVM
Page 5: Node.js on the JVM

What is Node.js?What is Node.js?Server-side JavaScript platform built on Google V8engineWhat JavaScript has done for the webbrowser, Node.js is doing for the backend server

Asyncronous, non-blocking, evented I/O with JavaScript

http://nodejs.org

var http = require('http');http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n');}).listen(1337, '127.0.0.1');console.log('Server running at http://127.0.0.1:1337/');

Page 6: Node.js on the JVM

The Event LoopThe Event Loop

Page 7: Node.js on the JVM

The cost of I/OThe cost of I/OL1-cache 3 cyclesL2-cache 14 cyclesRAM 250 cyclesDisk 41 000 000 cyclesNetwork 240 000 000 cycles

Page 8: Node.js on the JVM

Why JavaScript?Why JavaScript?“ (undefined is not a function!)

Page 9: Node.js on the JVM

Why Java?Why Java?

Page 10: Node.js on the JVM

With Java, we have...With Java, we have...Longterm investmentsMature solutionsComplex and extensive business logicIntegration of heterogeneous environmentsacross platformsBlueprints and best-practices availableProven infrastructure and monitoring options

Page 11: Node.js on the JVM

And now,And now,you wanna tell us about thisyou wanna tell us about this"brave""brave" new (Node-)world? new (Node-)world?

Mostly new applicationsMostly No-SQL backedNew application approachesMore focused silo apps"Cool stuff"~ 120.000 NPM libraries available (01/2015)

No enterprise integration (yet)Infrastructure? Monitoring? Operations?

Page 12: Node.js on the JVM

Speaking JavaScriptSpeaking JavaScript“ Like it or not, JavaScript is everywhere these days - frombrowser to server to mobile - and now you, too, need to

learn the language or dive deeper than you have.Dr. Axel Rauschmayer

http://speakingjs.com

Page 13: Node.js on the JVM

“ In four years ... Node.js has experienced phenomenalgrowth. Node.js is the language of choice for high

performance, low latency applications and has beenpowering everything from robots to API engines to cloud

stacks to mobile web sites.Node.js Advisory Board - October 23, 2014

Page 14: Node.js on the JVM
Page 15: Node.js on the JVM

IntegrationIntegration

Page 16: Node.js on the JVM

IntegrationIntegration

Page 17: Node.js on the JVM

dynamicdynamicinvokeinvoke

Page 18: Node.js on the JVM

NashornNashornJavaScript Enginge on the JVMbased on invokedynamic featurecompetes with Google V8ECMAScript 5.1 compatible (ES6/ES2015 with Java 9)Seamless interoperability of Java and JavaScriptShell ScriptingWith Java 8u40 native execution of TypeScriptLanguage and API Extensions

http://openjdk.java.net/projects/nashorn/

closures, collections & for each, multi-line string literals, string interpolation, __noSuchProperty__,__noSuchMethod__, typed arrays, binding properties, error extensions, conditional catch clause,String functions, and many, many more...

Page 19: Node.js on the JVM

Java and JavaScriptJava and JavaScript“ ...are similar than car and carpet are similar.

Page 20: Node.js on the JVM
Page 21: Node.js on the JVM
Page 22: Node.js on the JVM

NashornNashornCommand Line Client

$ $JAVA_HOME/bin/jjsjjs> print('Hello Nashorn!');

Invoking JavaScript from JavaScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");engine.eval("print('Hello Nashorn!');");

engine.eval(new FileReader("scriptfile.js"));

Invocable invocable = (Invocable) engine;Object result = invocable.invokeFunction("jsSayHello", "Nashorn");

Page 23: Node.js on the JVM

NashornNashornInvoking Java from JavaScript

package my.package;public class MyJavaClass { static String sayHello(String name) { return String.format("Hello %s from Java!", name); }}

var MyJavaClass = Java.type('my.package.MyJavaClass');var result = MyJavaClass.sayHello('Nashorn');print(result); // Hello Nashorn from Java!

Page 24: Node.js on the JVM

NashornNashornListing Docker Containers via REST-Call

#!/usr/bin/jjs -fvvar host = "DOCKER_HOST"var dockerUri="http://${host}:5555/containers/json";var command = "curl ${dockerUri}";$EXEC(command);var containers = JSON.parse($OUT);for each(container in containers){ print("${container.Image} / ${container.Names[0]} / ${container.Status}");}

(by )Adam Bien

Page 25: Node.js on the JVM

AvatarAvatarThe Oracle solutionThe Oracle solution

††

Page 26: Node.js on the JVM

Avatar 2.0Avatar 2.0

Inter-thread communicationMessage BusShared State (Map API: Key-Value-Store)

Model-Store-APIJPA (Eclipselink) / JDBC based

https://avatar.java.net

Page 27: Node.js on the JVM

Avatar 2.0Avatar 2.0

Page 28: Node.js on the JVM

The RedHat counter The RedHat counter

Page 29: Node.js on the JVM

developed by project:odd at RedHatbased on DynJS (Nashorn is on its way!)"more JavaScript than Node.js"Netty for async I/OVert.x integration/interaction

http://nodyn.io

Page 30: Node.js on the JVM

also based on invokedynamicREPL / command lineJava interaction / embedding

http://dynjs.org

Page 31: Node.js on the JVM

“ Netty is an asynchronous event-driven networkapplication framework for rapid development of

maintainable high performance protocol servers & clients.

http://netty.io

NettyNetty

Page 32: Node.js on the JVM

Node.js ArchitectureNode.js Architecture

Page 33: Node.js on the JVM

Nodyn ArchitectureNodyn Architecture

Page 34: Node.js on the JVM

Embed in Java programsEmbed in Java programspublic class EmbedExample {

private static final String SCRIPT = "" + "var main = require('./project/main.js');" + "main.run();";

public void runMain(String... args) throws InterruptedException { // Use DynJS runtime RuntimeFactory factory = RuntimeFactory.init( EmbedExample.class.getClassLoader(), RuntimeFactory.RuntimeType.DYNJS);

// Set config to run main.js NodynConfig config = new NodynConfig( new String[] { "-e", SCRIPT } );

// Create a new Nodyn and run it Nodyn nodyn = factory.newRuntime(config); nodyn.setExitHandler( new NoOpExitHandler() ); try { int exitCode = nodyn.run(); if (exitCode != 0) { throw new TestFailureException(); } } catch (Throwable t) { throw new TestFailureException( t ); } }}

Page 35: Node.js on the JVM

“ Vert.x is a lightweight, high performance applicationplatform for the JVM that's designed for modern mobile,

web, and enterprise applications.

Polyglott*SimplicityScalabilityConcurrencyDistributed Event Bus**

http://vertx.io

*) Java, JavaScript, Ruby, Groovy, Python, Scala, Clojure, Ceylon**) using Hazelcast In-Memory Data Grid ( )hazelcast.org

Page 36: Node.js on the JVM

vertx2-corevertx2-coreThis module exposes the vert.x 2.x eventbus to node.js clients.

https://github.com/nodyn/vertx2-core

mod-nodynmod-nodynThis supports running Node.js workloads inside of Vert.x.

https://github.com/nodyn/mod-nodyn

Page 37: Node.js on the JVM

Beer-as-a-ServiceBeer-as-a-Servicehttps://github.com/dasniko/beer-as-a-service

Page 38: Node.js on the JVM

var http = require("http");var vertx = require("vertx2-core");

var registration = vertx.eventbus.register("bar", function(message) { var amount = message.body.amount; console.log("BAR: Someone ordered " + amount + " beer(s)."); message.reply({wait_time: amount * 1.75});});

var server = http.createServer(function(request, response) { var parts = request.url.split("/"); var amount = parts[1];

vertx.eventbus.send("bar", {amount: amount}, function(message) { response.write(amount + " beer(s) will be ready in " + message.body.wait_time + " minutes"); response.end(); });});

server.listen(9000, function() { console.log( "Beer-Server is listening on port 9000" );});

beer-as-a-service.js

run with nodyn

Page 39: Node.js on the JVM

var http = require("http");var vertx = require("vertx2-core");

var server = http.createServer(function(request, response) { var parts = request.url.split("/"); var amount = parts[1];

vertx.eventbus.send("bar", {amount: amount}, function(message) { response.write(amount + " beer(s) will be ready in " + message.body.wait_time + " minutes"); response.end(); });});

server.listen(9000, function() { console.log( "Beer-Server is listening on port 9000" );});

beer-web.js

beer-bar.jsvar eventBus = require("vertx/event_bus");

eventBus.registerHandler("bar", function(message, replier) { java.lang.System.err.println("BAR: Someone ordered " + message.amount + " beer(s)"); replier({wait_time: message.amount * 1.75});});

java.lang.System.err.println("The BAR is open!");

run with vertx in cluster mode

Page 40: Node.js on the JVM
Page 41: Node.js on the JVM
Page 42: Node.js on the JVM

ConclusionConclusionJavaScript is an emerging language and widely adoptedNode.js / IO.js is very popularOperations, monitoring and integration lacksJVM is Enterprise environment of choice(and all the above lacks are already solved)Run JavaScript on the JVM thanks to invokedynamic(Nashorn, DynJS)Re-use your infrastructures and libraries with NodeNodyn from Red Hat

Re-use of Node API module, integration of Netty and Vert.xProcess-bindings in Java/JavaScriptEmbed Node.js apps into your Java applications

Page 43: Node.js on the JVM

Thank you!Thank you!

Questions?Questions?

Contact:

@[email protected]

http://slides.com/dasniko/nodejs-jvm