Access Dubbo Services via Web Browser

Develop microservices running on browser pages using dubbo-js.

Based on the Triple protocol defined by Dubbo3, you can easily write browser and gRPC compatible RPC services that run on both HTTP/1 and HTTP/2. The Dubbo TypeScript SDK supports defining services using IDL or language-specific methods, and provides a lightweight API set to publish or invoke these services.

Dubbo-js released its first alpha version supporting the Dubbo3 protocol in September, which can fundamentally change the architecture and communication patterns of microservices’ front and back end, allowing you to directly access backend Dubbo RPC services from a browser page or web server.

dubbo-web.png

Browser Web Application Example

This example demonstrates how to use dubbo-js to develop a web application running in a browser, where the web page will call backend services developed in dubbo node.js to generate page content. This example shows both IDL and non-IDL coding modes.

dubbo-web.png

IDL Mode

Prerequisites

First, we will use Vite to generate our frontend project template, which has all the features we need later.

  1. npm create vite@latest -- dubbo-web-example --template react-ts
  2. cd dubbo-web-example
  3. npm install

Because we are using Protocol Buffer, we need to install related code generation tools: @bufbuild/protoc-gen-es, @bufbuild/protobuf, @apachedubbo/protoc-gen-apache-dubbo-es, @apachedubbo/dubbo.

  1. npm install @bufbuild/protoc-gen-es @bufbuild/protobuf @apachedubbo/protoc-gen-apache-dubbo-es @apachedubbo/dubbo

Defining Service with Proto

Now, use Protocol Buffer (IDL) to define a Dubbo service.

Create the util/proto directory under src and generate the file

  1. mkdir -p src/util/proto && touch src/util/proto/example.proto

Write the content

  1. syntax = "proto3";
  2. package apache.dubbo.demo.example.v1;
  3. message SayRequest {
  4. string sentence = 1;
  5. }
  6. message SayResponse {
  7. string sentence = 1;
  8. }
  9. service ExampleService {
  10. rpc Say(SayRequest) returns (SayResponse) {}
  11. }

This file declares a service called ExampleService, defining the Say method with its request parameter SayRequest and return value SayResponse.

Generate Code

Create the gen directory as the target directory for generated files

  1. mkdir -p src/util/gen

Run the following command to generate code files in the gen directory using protoc-gen-es, protoc-gen-apache-dubbo-es, and other plugins

  1. PATH=$PATH:$(pwd)/node_modules/.bin \
  2. protoc -I src/util/proto \
  3. --es_out src/util/gen \
  4. --es_opt target=ts \
  5. --apache-dubbo-es_out src/util/gen \
  6. --apache-dubbo-es_opt target=ts \
  7. example.proto

After running the command, you should see the following generated files in the target directory:

  1. ├── src
  2. ├── util
  3. ├── gen
  4. ├── example_dubbo.ts
  5. └── example_pb.ts
  6. └── proto
  7. └── example.proto

Create App

First, download @apachedubbo/dubbo-web

  1. npm install @apachedubbo/dubbo-web

Now we can import the service from the package and set a client. Add the following content in App.tsx:

  1. import { useState } from "react";
  2. import "./App.css";
  3. import { createPromiseClient } from "@apachedubbo/dubbo";
  4. import { createDubboTransport } from "@apachedubbo/dubbo-web";
  5. // Import service definition that you want to connect to.
  6. import { ExampleService } from "./util/gen/example_dubbo";
  7. // The transport defines what type of endpoint we're hitting.
  8. // In our example we'll be communicating with a Dubbo endpoint.
  9. const transport = createDubboTransport({
  10. baseUrl: "http://localhost:8080",
  11. });
  12. // Here we make the client itself, combining the service
  13. // definition with the transport.
  14. const client = createPromiseClient(ExampleService, transport, { serviceGroup: 'dubbo', serviceVersion: '1.0.0' });
  15. function App() {
  16. const [inputValue, setInputValue] = useState("");
  17. const [messages, setMessages] = useState<
  18. {
  19. fromMe: boolean;
  20. message: string;
  21. }[]
  22. >([]);
  23. return (
  24. <>
  25. <ol>
  26. {messages.map((msg, index) => (
  27. <li key={index}>{`${msg.fromMe ? "ME:" : "Dubbo Server:"} ${msg.message}`}</li>
  28. ))}
  29. </ol>
  30. <form
  31. onSubmit={async (e) => {
  32. e.preventDefault();
  33. // Clear inputValue since the user has submitted.
  34. setInputValue("");
  35. // Store the inputValue in the chain of messages and
  36. // mark this message as coming from "me"
  37. setMessages((prev) => [
  38. ...prev,
  39. {
  40. fromMe: true,
  41. message: inputValue,
  42. },
  43. ]);
  44. const response = await client.say({
  45. sentence: inputValue,
  46. });
  47. setMessages((prev) => [
  48. ...prev,
  49. {
  50. fromMe: false,
  51. message: response.sentence,
  52. },
  53. ]);
  54. }}
  55. >
  56. <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
  57. <button type="submit">Send</button>
  58. </form>
  59. </>
  60. );
  61. }
  62. export default App;

Run the following command to get the sample page:

  1. npm run dev

Start Server

Next, we need to start the Server, which can be developed in any language that Dubbo supports, such as Java, Go, or Node.js. Here, we take the Node.js server embedded with Dubbo service; see Developing Dubbo Backend Service with Node.js for specific steps.

Please note that we need to additionally modify the Node.js example: introduce @fastify/cors to solve the front-end request cross-origin issues

  1. npm install @fastify/cors

We need to modify the server.ts file

  1. ...
  2. import cors from "@fastify/cors";
  3. ...
  4. async function main() {
  5. const server = fastify();
  6. ...
  7. await server.register(cors, {
  8. origin: true,
  9. });
  10. ...
  11. await server.listen({ host: "localhost", port: 8080 });
  12. ...
  13. }
  14. void main();

Finally, run the code to start the service

  1. npx tsx server.ts

Non-IDL Mode

In upcoming versions, we will continue to provide support for communication without IDL mode, making it easier to access backend services without IDL. Here, we will quickly look at how to use the non-IDL mode.

You also need to install @apachedubbo/dubbo and @apachedubbo/dubbo-web first.

  1. npm install @apachedubbo/dubbo @apachedubbo/dubbo-web

Now, you can start a client and initiate a call. The code in App.tsx is basically the same as in IDL mode, with the difference in the following content:

  1. // ...
  2. // set backend server to connect
  3. const transport = createDubboTransport({
  4. baseUrl: "http://localhost:8080",
  5. });
  6. // init client
  7. const client = createPromiseClient(transport);
  8. function App() {
  9. // ...
  10. // call remote Dubbo service
  11. const response = await client.call(
  12. "apache.dubbo.demo.example.v1.ExampleService",
  13. "say",
  14. {
  15. sentence: inputValue,
  16. });
  17. }

Run the following command to get the sample page:

  1. npm run dev

Feedback

Was this page helpful?

Yes No

Last modified September 30, 2024: Update & Translate Overview Docs (#3040) (d37ebceaea7)