rabbitmq and spring multipoint connection

1. Configure rq connection information (rq.properties)

rb.host.batch=192.168.1.1:5672,192.168.1.2:5672


2. Get the configuration file value and process the generated Address[]

private static Address[] splitAddress(String hostAddress) {
        String[] hostArray = hostAddress.split(",");
        Address[] addArray = new Address[hostArray.length];
        for (int i = 0; i < hostArray.length; i++) {
            addArray[i] = new Address(hostArray[i].split(":")[0], Integer.parseInt(hostArray[i].split(":")[1]));
        }
        return addArray;
    }


3. Create connections, channels, queues

 
//address数组
public static void conRabbitMQ(Address[] addresses) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("guest");
        factory.setPassword("guest");
        try {
            Connection connection=factory.newConnection(addresses);
         
            Channel channel= connection.createChannel();

           channel.queueDeclare("queueName",true,false,false,null);
           channel.queueBind("queueName","exchangeName","queueName");
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

4. Summary

   Use the newConnection(Address[] addrs) method of ConnectionFactory to create a connection, support multiple host addresses, and use connection.isOpen() to determine whether the current mq service is normal during program operation. If the value is false, other hosts in the addrs array will be used. The address creates a connection, and re-creating a connection requires creating a connection and a channel, and the channel is used to send and receive messages.

   



Guess you like

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