The deed simple Nodejs microservice communication  (json-rpc protocol)

The deed simple Nodejs microservice communication (json-rpc protocol)

Microservices are a popular architectural pattern for building large-scale distributed systems. They offer benefits such as modularity, scalability, and resilience by breaking down a monolithic application into smaller, independent services that can be developed and deployed independently.

In this article, we will explore how to build a simple microservices architecture using Node.js and demonstrate how to implement inter-service communication between two services.

Overview

We will create two Node.js applications, each with an Express.js API and a JSON-RPC2 server/client. The first service will call a method on the second service via JSON-RPC2 to perform a multiplication operation, and the second service will call an endpoint on the first service to perform an addition operation.

Prerequisites

To follow along with this tutorial, you will need to have Node.js and npm installed on your system.

Creating the Services

We will start by creating two separate directories for each service.mkdir service-a mkdir service-b

Then, we will navigate to the service-a directory and initialize a new Node.js project with the following command:

cd service-a npm init -y 

We will do the same for the service-b directory.

cd ../service-b npm init -y 

Next, we will install the required dependencies for each service:

# For Service A 
cd ../service-a 
npm install express json-rpc2 

# For Service B 
cd ../service-b 
npm install express json-rpc2 

Implementing Service A

We will start by implementing Service A, which will call a method on Service B to perform a multiplication operation.

Create a new file named index.js in the service-a directory and add the following code:


const express = require("express")
const rpc = require("json-rpc2");

const app = express();


// Set up an RPC client to call methods on Service B
const client = rpc.Client.$create(8002, "localhost");


// Define an Express API endpoint that calls the 'multiply' method on Service B via RPC
app.get("/multiply", async (req, res) => {
  try {
    const { a, b } = req.query;


    if (!a || !b) {
      throw new Error("Invalid input: a and b are required");
    }


    await client.call(
      "multiply",
      {
        a: parseInt(a),
        b: parseInt(b),
      },
      (error, result) => {
        // result or error from rpc call
        res.json({ result });
      }
    );
  } catch (error) {
    console.error("API call to Service B failed:", error);


    res.status(500).json({ error: "API call to Service B failed" });
  }
});


app.listen(8000, "localhost", () => {
  console.log("Express APP Service A listening on port 8000");
});

Here, we set up an RPC client to call the multiply method on Service B via JSON-RPC2. We define an Express API endpoint that calls this method with the given input parameters a and b. The result of the operation is returned as a JSON response to the client.

Implementing Service B

We will now implement Service B, which will expose a multiply method to perform multiplication operations and will call an endpoint on Service A to perform an addition operation.

Create a new file named index.js in the service-b directory and add the following code:

const express = require("express");
const rpc = require("json-rpc2");


const app = express();


// Set up an RPC server to listen for calls from Service A
var server = rpc.Server.$create({
  websocket: true, // is true by default
  headers: {
    // allow custom headers is empty by default
    "Access-Control-Allow-Origin": "*",
  },
});


function multiply(args, opt, callback) {
  try {
    callback(null, args.a * args.b);
  } catch (e) {
    callback(e);
  }
}
server.expose("multiply", multiply);


server.listen(8002, "localhost", () => {
  console.log("RPC Service A listening on port 8011");
});


app.listen(8001, "localhost", () => {
  console.log("Express APP Service A listening on port 8010");
});


Running the Services

With both services implemented, let's run them and see how they interact with each other.

Open up two terminal windows and navigate to the root directory of the project. In the first terminal window, start Service B by running the following command:

node service-b.js 

This will start Service B on localhost:8002 and set up an RPC server to listen for incoming requests.

Next, in the second terminal window, start Service A by running the following command:

node service-a.js 

This will start Service A on localhost:8000 and set up an Express server to listen for incoming HTTP requests.

With both services up and running, we can now hit the /multiply endpoint on Service A via a web browser or an HTTP client like curl:

bash

Copy code
https://localhost:8000/multiply?a=5&b=10 

This should return a JSON response containing the result of multiplying a and b:

{ "result": 50 } 

Success! We have successfully implemented a simple microservices architecture using Node.js and demonstrated inter-service communication via JSON-RPC.

Conclusion

In conclusion, microservices architecture is a powerful tool for building scalable, resilient, and maintainable systems. In this article, we explored the basics of microservices and demonstrated how to implement a simple microservices architecture using Node.js and JSON-RPC2.

We created two Node.js files, each with an Express.js app, an RPC server, and an RPC client. We showed how the two services can communicate with each other by making RPC calls over a network. We also demonstrated how to handle errors and ensure fault-tolerance by implementing error handling mechanisms and retry logic.

This simple example only scratches the surface of what can be accomplished with microservices architecture. But hopefully, it serves as a useful starting point for anyone interested in learning more about this powerful software design pattern.

As with any architectural pattern, there are trade-offs and considerations to keep in mind when implementing microservices. It's important to carefully weigh the benefits and drawbacks of this approach and consider whether it's the right choice for your specific use case.

Overall, microservices architecture offers a highly flexible and modular way to build complex systems that can be scaled and maintained with ease. With the right tools and techniques, it's possible to create robust and fault-tolerant microservices that can handle virtually any workload.

Gowrav Vishwakarma ( ???? ?????????? )

Entrepreneur/Leader, CTO, Nutricheck France; Ex Co-Founder/CTO Frendy, Founder: Xavoc. Track record in scaling tech. Expertise in Solution Architecting, ERP, e-commerce, SaaS. 10+ Yrs in AI/ML

2 年
回复

要查看或添加评论,请登录

Gowrav Vishwakarma ( ???? ?????????? )的更多文章

社区洞察

其他会员也浏览了