Home > Software engineering >  Java RabbitMQ storing a consumed message in local variable not working
Java RabbitMQ storing a consumed message in local variable not working

Time:01-17

The task i am trying to do consists of two classes, one class is Student and the other is University student service.The class Student is supposed to fill out the form and send a message through RabbitMQ queue towards the class University student service.Once the Student service checks if the form is valid they are supposed to send an answer to Student class so that it acts as some sort of RPC.

What i tried doing is, i tried storing the message that University student service received in a local variable type String and check validity of it so that i can send the message back to Student class letting it know what the answer is.

Problem is i am not able to store the message, i tried using setter but it does not work nor does the normal operator = storing work.

Code:

Class Student


    public static void main(String[] args) throws IOException, TimeoutException {
      
     String check = "";
     
     while(!check.equals("End")) {
        
      
      Scanner input = new Scanner(System.in);
      System.out.println("Input your name and surname:");
      String imePrezime = input.nextLine();
      
      System.out.println("\nInput your ordinal number:");
      String redniBr = input.nextLine();
      
      System.out.println("\nInput the year you applied:");
      String godinaUpisa = input.nextLine();
      
      System.out.println("\nInput the name of the subject:");
      String nazivPredmeta = input.nextLine();
      
      System.out.println("\nInput semester:");
      String semestar = input.nextLine();
      
      System.out.println("\nInput current year:");
      String studijskaGodina = input.nextLine();
      
      String finalnaPoruka = imePrezime   " "    redniBr   " "   godinaUpisa   " "   nazivPredmeta   " "   semestar   " "   studijskaGodina;
      
      
        
      ConnectionFactory factory = new ConnectionFactory();
       
      try (Connection connection = factory.newConnection()){
          Channel channel = connection.createChannel();
          channel.queueDeclare("Apply",false,false,false,null);
          
          String message = finalnaPoruka;
          channel.basicPublish("","Apply",false,null,message.getBytes());
          System.out.println("The message has been delivered.\n");
      }
      
      
       
    }
    }

}

As you can see above, in this class i just send a string.

Class University student service

import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Connection;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;

public class Sluzba {
    static String globalMessage = "";
    
    public static void setMsg(String arg) {
        globalMessage = arg;
    }
    
    public static void main(String[] args) throws IOException, TimeoutException {
          int check = 0;
          
          
          ConnectionFactory factory = new ConnectionFactory();
       
          Connection connection = factory.newConnection();
          Channel channel = connection.createChannel();
          channel.queueDeclare("Apply",false,false,false,null);
          
         
          DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                setMsg(message);
                System.out.println("New application has arrived '"   message   "'");
            };
            channel.basicConsume("Apply", true, deliverCallback, consumerTag -> { });
            
            
            
            System.out.println("Global message "   globalMessage   " stored");
            
      
            try (Connection connectionReply = factory.newConnection()){
                  Channel channelReply = connection.createChannel();
                  channelReply.queueDeclare("Answer",false,false,false,null);
                  
                  String messageReply = "Test";
                  channel.basicPublish("","Answer",false,null,messageReply.getBytes());
                  System.out.println("Answer has been delivered.\n");
              }
          
          
        
       
    }

}

In the class above i am trying to check if it works(I still did not finish the code), all in all i would like to save that received message, check the validity and try to send an answer back to Student so it can work with the result.

System.out.println("Global message " globalMessage " stored");

This was supposed to print that same message once i store it but it does not work, and it does not give any compile errors.

Side question:Is this the correct way to do this RPC simulation exchange or am i having a bad idea?

Thank you everyone for your time.

CodePudding user response:

It seems to be an issue of type pass by reference. You are passing message reference in setMsg method call and that reference points to memory location of message created in driverCallBack. That means globalMessage is just pointing to same message memory block.

Now as soon as driverCallBack block is executed, the message memory block is deallocated and now globalMessage is pointing to non-existent block, hence value is lost.

So you can initialize globalMessage with new String(arg) so that value is copied to a new memory block and is no longer dependent on message memory block.

public static void setMsg(String arg) {
        globalMessage = new String(arg);
}
  •  Tags:  
  • Related