rpc_server.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env node
  2. const amqp = require('amqplib');
  3. const queue = 'rpc_queue';
  4. (async () => {
  5. try {
  6. const connection = await amqp.connect('amqp://localhost');
  7. const channel = await connection.createChannel();
  8. process.once('SIGINT', async () => {
  9. await channel.close();
  10. await connection.close();
  11. });
  12. await channel.assertQueue(queue, { durable: false });
  13. channel.prefetch(1);
  14. await channel.consume(queue, (message) => {
  15. const n = parseInt(message.content.toString(), 10);
  16. console.log(' [.] fib(%d)', n);
  17. const response = fib(n);
  18. channel.sendToQueue(message.properties.replyTo, Buffer.from(response.toString()), {
  19. correlationId: message.properties.correlationId
  20. });
  21. channel.ack(message);
  22. });
  23. console.log(' [x] Awaiting RPC requests. To exit press CTRL+C.');
  24. }
  25. catch (err) {
  26. console.warn(err);
  27. }
  28. })();
  29. function fib(n) {
  30. // Do it the ridiculous, but not most ridiculous, way. For better,
  31. // see http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms
  32. let a = 0, b = 1;
  33. for (let i=0; i < n; i++) {
  34. let c = a + b;
  35. a = b; b = c;
  36. }
  37. return a;
  38. }