The Java side acts as a service provider, implements services based on Dubbo and exposes services through Dubbo Hessian extension; the Node side acts as a service consumer, calling Java side services through node-hessian. This article mainly introduces you to the sample code of Node calling Java. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Java side
Service interface
package com.yuanxin.paas.ssb; public interface TestService { /** * 测试:无参,无返回值。 */ void test(); /** * 测试:原生类型参数与返回值。 * * @param i * @return */ String test0(int i); /** * 测试:无参,自定义类型返回值。 * * @return */ Result test1(); /** * 测试:自定义类型参数,无返回值。 * * @param arg */ void test2(Arg arg); /** * 测试:自定义参数,自定义返回值。 * * @param arg * @return */ Result test3(final Arg arg); }
Custom parameter class
package com.yuanxin.paas.ssb; import java.io.Serializable; public class Arg implements Serializable { private int i; public int getI() { return i; } public void setI(int i) { this.i = i; } }
Custom return value class
package com.yuanxin.paas.ssb; import java.io.Serializable; public class Result implements Serializable { private int i; private String string; public int getI() { return i; } public void setI(int i) { this.i = i; } public String getString() { return string; } public void setString(String string) { this.string = string; } }
Dubbo configuration is omitted.
Node side
node-hessian
Install node-hessian:
npm install hessian-proxy
Calling service interface
var Proxy = require('hessian-proxy').Proxy; var proxy = new Proxy('http://127.0.0.1:9098/test-provider/provider/com.yuanxin.paas.ssb.TestService', '', '', proxy); proxy.invoke('test', null, function (err, reply) { console.log('test: ' + reply); }); proxy.invoke('test0', [25], function (err, reply) { console.log('test0: ' + JSON.stringify(reply)); }) proxy.invoke('test1', null, function (err, reply) { if (err) { console.log('test1: ' + err); } console.log('test1: ' + JSON.stringify(reply)); }) var argForTest2 = { i: 2 }; argForTest2.__type__ = 'com.yuanxin.paas.ssb.Arg'; proxy.invoke('test2', [argForTest2], function (err, reply) { if (err) { console.log('test2: ' + err); } console.log('test2: ' + JSON.stringify(reply)); }) var argForTest3 = { i: 3 }; argForTest3.__type__ = 'com.yuanxin.paas.ssb.Arg'; proxy.invoke('test3', [argForTest3], function (err, reply) { if (err) { console.log('test3: ' + err); } console.log('test3: ' + JSON.stringify(reply)); })
Run result
Java side
Node side
Related recommendations:
The case of Java being called by Node
The above is the detailed content of Sample code sharing of Node calling Java. For more information, please follow other related articles on the PHP Chinese website!