JAVA multi-threaded test MQ performance steps and code

1. Installing RabbitMQ under Windows requires the following steps

   (1): Download erlang, the reason is that the RabbitMQ server code is written in the concurrent language erlang, download address: http://www.erlang.org/downloads, double-click the .exe file to install it, and create it after the installation is complete An environment variable named ERLANG_HOME, whose value points to the erlang installation directory, at the same time add %ERLANG_HOME%\bin to Path, and finally open the command line and enter erl, if the erlang version information appears, it means that the erlang language environment is installed successfully;

   (2): Download RabbitMQ, download address: http://www.rabbitmq.com/, and double-click .exe to install it (it needs to be noted here that the default installation directory is C:/Program Files/.... , there are spaces in this directory, we need to change the installation directory, it seems that spaces are not allowed in the RabbitMQ installation directory, I have stepped on this pit before);

   (3): Install RabbitMQ-Plugins, which is equivalent to a management interface, which is convenient for us to view the working conditions of each message queue and exchange of RabbitMQ in the browser interface. The installation method is: open the command line cd and enter the sbin directory of rabbitmq (my directory). Yes: E:\software\rabbitmq\rabbitmq_server-3.6.5\sbin), enter: rabbitmq-plugins enable rabbitmq_management command, you will find a prompt that the plugins are installed successfully after a while, the default is to install 6 plugins, if you are installing The following error occurred during the plugin process:        

   The solution is: first enter: rabbitmq-service stop on the command line, then enter rabbitmq-service remove, then enter rabbitmq-service install, then enter rabbitmq-service start, and finally re-enter rabbitmq-plugins enable rabbitmq_management to try, I am solved in this way;

   (4): After the plugin is installed, enter http://localhost:15672 in the browser for verification, you will see the following interface, enter the username: guest, password: guest, you can enter the management interface, of course, the username and password you can change

2. After installing RabbitMQ, let's briefly understand the concepts involved in RabbitMQ

    producer: message producer

    consumer: message consumer

     virtual host: virtual host. In RabbitMQ, users can only set some permissions at the virtual host level, such as which queues I can access, which requests I can process, etc.;

     broker: The message forwarder, which is the function of our RabbitMQ server, so what rules are the messages forwarded according to? The following concepts need to be used;

     exchange: switch, it deals directly with the producer, which is similar to the function of a router, mainly for forwarding operations, so which exchange does the producer use for routing? This depends on the routing key (routing key), each message has this key, we can also set it ourselves, it is actually a string;

     Queue: message queue, used to store messages. It receives messages routed by exchange. We can persist the content of the queue. Then, does the queue receive messages routed by exchange? At this time, the binding key (binding key) will be used. The binding key will bind the queue and exchange. As for the binding method, RabbitMQ provides a variety of methods. You can see the RabbitMQ blog series of Hongyang God ( click to view );

     The above are some of the concepts involved in RabbitMQ. A diagram to represent the relationship between these concepts is:

3. RabbitMQ is simple to use

   Producer side steps:

    (1): Create a ConnectionFactory and set some parameters, such as hostname, portNumber, etc.

    (2): Use ConnectionFactory to create a Connection connection

    (3): Use Connection to create a Channel channel

    (4): Create queue and bind to Channel

    (5): Create a message and send it to the queue

     Note that in our current example, the exchange switch is not used. RabbitMQ will create an exchange with an empty string name by default. If we do not create our own exchange, the default is to use this exchange;

     Producer side code:

 

 

package com.mq;
import java.io.IOException;

import com.rabbitmq.client.Channel;  
import com.rabbitmq.client.Connection;  
import com.rabbitmq.client.ConnectionFactory;  
import com.rabbitmq.client.MessageProperties;  

public class Sender {
    
    private static String queueName = "rabbit";
    private static int k=0;
    private static double startTime=0.0;
    static ConnectionFactory factory = new ConnectionFactory();  
    static Channel channel=null ;
    static  Connection connection=null;
    
    
    static{
          factory.setHost(" ");  
          factory.setVirtualHost(" ");
            factory.setUsername(" ");  
            factory.setPassword(" ");  
            factory.setPort(5672);
            
            try {
                connection = factory.newConnection();            
                channel=connection.createChannel();  
                channel.queueDeclare(queueName, true, false, false, null);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        
    }
    public static void tt() throws Exception {
        
            
            for(int i=0;i<100;i++) { 
                new Thread(new Runnable() {
                    
                    public void run() {
                        // TODO Auto-generated method stub
                        for ( int j = 0; j < 1000; j++) {  
                            //发送的消息    
                    String message = "{*********}"+ ++k;
                            //往队列中发出一条消息    
                            try {
                                if (channel != null) {
                                    channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
                                }
                                
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }    

                               
                            
                            double l=(double)((System.currentTimeMillis()-startTime)/1000);
                            int t=++k;

                               
                            System.out.println("tps:"+ t/l);

                        }  
                        
                        
                    }
                }).start();
                
            }
            }
    
    public static void main(String[] args) throws Exception{  
           startTime= System.currentTimeMillis();
        
          Sender.tt();
        
        
        
         
          
      
          
    }  

}

     Consumer (consumer) side steps:

     (1): Create a ConnectionFactory and set some parameters, such as hostname, portNumber, etc.

     (2): Use ConnectionFactory to create a Connection connection

     (3): Use Connection to create a Channel channel

     (4): Bind the queue to the Channel, note that the queue name here should be consistent with the queue created by the previous producer

     (5): Create a consumer Consumer to receive messages, and bind the consumer to the queue at the same time

     Consumer side code:

package com.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class Consumer {
      private static String queueName = "rabbit";  
      static int i=0;
      
        public static void main(String[] args) throws Exception {  
     
            ConnectionFactory factory = new ConnectionFactory();  
            factory.setHost("*.*.* .*");  
            factory.setVirtualHost(" ");
            factory.setUsername(" ");  
            factory.setPassword(" ");  
            factory.setPort(5672);
            Connection connection = factory.newConnection();  
            Channel channel = connection. createChannel();  
      
            // Declare the queue, mainly to prevent the message receiver from running this program first, and create the queue when the queue does not yet exist.  
            channel.queueDeclare(queueName, true, false, false, null);  
            System.out.println(Consumer.class.hashCode()  
                    + " [*] Waiting for messages. To exit press CTRL+C");  
      
            // create queue Consumer  
            QueueingConsumer consumer = new QueueingConsumer(channel);  
      
            // Set the maximum number of service messages received  
            int prefetchCount = 1;  
            channel.basicQos(prefetchCount);  
      
            boolean ack = false; // Whether to automatically confirm that the message is successfully consumed  
            channel.basicConsume(queueName , ack, consumer); // Specify the consumption queue  
            long startTime= System.currentTimeMillis();
           
            while (true) {  
                // nextDelivery is a blocking method (the internal implementation is actually the take method of the blocking queue)  
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
                String message = new String(delivery.getBody());  
              
                    
                    System.out.println(" [x] Received '" + message + "'");  
                    int k=++i;
                    System.out.println(k);  
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); 
                    float l=(float)(System.currentTimeMillis()-startTime)/1000;
                   
                    System.out.println("tps:"+k/l);
                 
      
               
                }
            
            
           
        }  

}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324378045&siteId=291194637