RPC with Delphi server and Java client using RabbitMQ (part 2 of 2)

This article shows the code for a Delphi server which receives a RPC call message from the inbound RabbitMQ request queue, and sends the response message back to the Java client. It is the mirror code for the previous article.

Delphi source code:

program RPCServer;

{$APPTYPE CONSOLE}

uses
  BTCommAdapterIndy, BTJMSConnection, BTJMSInterfaces,
  SysUtils;

procedure FibServer;
var
  Conn: IConnection;
  Session: ISession;
  RequestQueue: IDestination;
  ResponseQueue: IDestination;
  Producer: IMessageProducer;
  Consumer: IMessageConsumer;
  Request, Response: IMessage;
  Input, Output: Integer;

  function fib(n: Integer): Integer;
  begin
    if n=0 then begin Result := 0; Exit; end;
    if n=1 then begin Result := 1; Exit; end;
    Result := fib(n-1) + fib(n-2);
  end;
begin
  Conn := TBTJMSConnection.MakeConnection;
  try
    try
      Conn.Start;

      // create the session
      Session := Conn.CreateSession(False, amAutoAcknowledge);

      // prepare the reply queue
      RequestQueue := Session.CreateQueue('/amq/queue/rpc_queue');

      // wait for messages
      Consumer := Session.CreateConsumer(RequestQueue);
      while True do
      begin
        Request := Consumer.Receive;

        Input := StrToInt((Request as ITextMessage).Text);

        Output := fib(Input);

        WriteLn(' [.] fib(' + IntToStr(Input) + ')');

        // prepare and send the response
        Response := Session.CreateTextMessage(IntToStr(Output));
        Response.JMSCorrelationID := Request.JMSCorrelationID;
        Producer := Session.CreateProducer(Request.JMSReplyTo);
        Producer.Send(Response);
      end;

    except
      on E: Exception do
      begin
        WriteLn(E.Message);
        ReadLn;
      end;
    end;
  finally
    Conn.Close;
  end;
end;

begin
  ReportMemoryLeaksOnShutdown := True;

  Writeln('[*] Awaiting RPC requests');
  FibServer;
end.

A small change is needed in the Java client to support STOMP text messages:

        BasicProperties props = new BasicProperties.Builder()
                .correlationId(corrId)
                .replyTo(replyQueueName)
                .contentType("text/plain")
                .build();
Advertisements