---会社にRabbitMQの実際のプロジェクトを導入し、サブチャネルメッセージの送信

大量の需要のユーザーがメッセージのプッシュ機能を必要とするので最近、私は、処理のためのRabbitMQを使用するのではと思いました。その後、ユーティリティクラスに引き込まれるのRabbitMQ直接呼び出すことができ、騒ぎ直接開始

1、インストールのRabbitMQ 

https://blog.csdn.net/red_sheeps/article/details/78386303

2、追加のVirtualHost -------メンバーを

3、プロジェクトの依存関係に導入される(注:FASTJSONに有用です)

<dependency>
	<groupId>com.rabbitmq</groupId>
	<artifactId>amqp-client</artifactId>
	<version>5.4.1</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.49</version>
</dependency>

4、および定数の名前を書き込むチャネルを切り替えます

package com.ldd.common.addr.service.queue;

/**
 * @program: ldd
 * @description: This is a constant class for queue name and exchange name
 * @author: W.HL
 * @create: 2019-01-29 16:32
 **/

public class ConstantParam
{
    /**
     * This is sms channel queue name
     */
    public static final String SMS_QUEUE_NAME = "SMS_QUEUE_NAME_M";
    /**
     * This is jpush channel queue name
     */
    public static final String JPUSH_QUEUE_NAME = "JPUSH_QUEUE_NAME_M";
    /**
     * This is sys log channel queue name
     */
    public static final String SYS_QUEUE_NAME = "SYS_QUEUE_NAME_M";

    /**
     * This is sms exchange name
     */
    public static final String SMS_EXCHANGE_NAME = "SMS_EXCHANGE_NAME_M";
    /**
     * This is jpush exchange name
     */
    public static final String JPUSH_EXCHANGE_NAME = "JPUSH_EXCHANGE_NAME_M";
    /**
     * This is sys log exchange name
     */
    public static final String SYS_EXCHANGE_NAME = "SYS_EXCHANGE_NAME_M";

}

5、書き込みプロデューサーツール(注:関連する設定情報は、接続を変更)

package com.ldd.common.addr.service.queue;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author hl.Wu
 * Thie is send message use rabbitMQ queueUtil
 */
public class ProductQueueUtil
{
    private static Logger logger = LoggerFactory.getLogger(ProductQueueUtil.class);

    /**
     * get connection
     * @return connection
     */
    public static Connection getConnection(){
        /*get the ConnectionFactory*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        /*set connectionFactory property*/
        connectionFactory.setHost("192.168.1.24");
        /*set port*/
        connectionFactory.setPort(5672);
        /*set userName*/
        connectionFactory.setUsername("admin");
        /*set password*/
        connectionFactory.setPassword("1234567");
        /*set connection out time */
        connectionFactory.setConnectionTimeout(600000);
        /*set virtual host */
        connectionFactory.setVirtualHost("/member");
        Connection connection = null;
        try
        {
            /*create connection by factory*/
            connection = connectionFactory.newConnection();
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * get the channel
     * @param connection
     * @param queueName
     * @param exchangeName
     * @return
     * @throws IOException
     */
    public static Channel getChannel(Connection connection, String queueName,String exchangeName) throws IOException
    {
        /*create the channel*/
        Channel channel = connection.createChannel();
        /*declare exchange not durable exchange*/
        channel.exchangeDeclare(exchangeName,"direct",false);
        /*declare channel*/
        channel.queueDeclare(queueName,false,false,false,null);
        /*bind exchange with queue*/
        channel.queueBind(queueName,exchangeName,queueName);
        /*the same time operate message*/
        channel.basicQos(6);
        return channel;
    }

    /**
     * send message
     * @param channel which channel to send message eg:SMS_QUEUE_NAME、JPUSH_QUEUE_NAME、SYS_QUEUE_NAME
     * @param queueName
     * @param exchangeName
     * @param msgList
     * @throws IOException
     */
    public static void sendMessage(Channel channel,String queueName,String exchangeName,List<Map<String,Object>> msgList) throws IOException
    {
        if(msgList != null && msgList.size()>0){
            logger.info("The current user send message list is {}",JSON.toJSON(msgList).toString());
            channel.basicPublish(exchangeName,queueName,null, JSON.toJSON(msgList).toString().getBytes());
        }
    }

    public static void closeResource(Connection connection,Channel channel){
        try
        {
            if (channel.isOpen()) {
                channel.abort();
            }

            if (connection.isOpen()) {
                connection.close();
            }
        }
        catch (Exception e)
        {
            logger.info("------",e);
        }
    }
}

6、書き込み消費者ツール

package com.ldd.common.addr.service.queue;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @author hl.Wu
 * queue comsumer receive message
 */
public class ConsumerMsgUtil
{
    private Logger logger = LoggerFactory.getLogger(ConsumerMsgUtil.class);

    public void comsumeMessage(Channel channel,String queueName,String exchangeName) throws IOException
    {
        /*operate message*/
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            sendMessage(delivery.getBody());
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
    }

    private void sendMessage(byte[] body) throws UnsupportedEncodingException
    {
        String param = new String(body, "UTF-8");
        List<Map<String,Object>> list = (List)JSON.parse(param);
        logger.info("The current user received message list is {}",list);
        //TODO some something
    }

}

図7に示すように、書き込みテストクラス(注:なぜならそうスレッドプールを使用して行う処理を高速化するために大量のデータをテストする必要があります)

package com.ldd.common.addr.service.queue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.Cleanup;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RabbitMQTest2
{

    public static void main(String[] args)
    {
        // 线程池
        ExecutorService pool = Executors.newCachedThreadPool();
        pool.execute(() -> test1());
        pool.execute(() -> test2());

        try{
             Connection connection = ProductQueueUtil.getConnection();
             Channel jpushChannel = ProductQueueUtil.getChannel(connection,ConstantParam.JPUSH_QUEUE_NAME,ConstantParam.JPUSH_EXCHANGE_NAME);
             Channel smsChannel = ProductQueueUtil.getChannel(connection,ConstantParam.JPUSH_QUEUE_NAME,ConstantParam.JPUSH_EXCHANGE_NAME);
            for (int i =1;i<2;i++){
                new ConsumerMsgUtil().comsumeMessage(smsChannel,ConstantParam.SMS_QUEUE_NAME,ConstantParam.SMS_EXCHANGE_NAME);
            }
            for (int i =1;i<2;i++){
                new ConsumerMsgUtil().comsumeMessage(jpushChannel,ConstantParam.JPUSH_QUEUE_NAME,ConstantParam.JPUSH_EXCHANGE_NAME);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void test1()
    {
        try
        {
             Connection connection = ProductQueueUtil.getConnection();
             Channel channel = ProductQueueUtil.getChannel(connection,ConstantParam.JPUSH_QUEUE_NAME,ConstantParam.JPUSH_EXCHANGE_NAME);
            for (int i=1;i<300;i++){
                Map<String, Object> param = new HashMap<>();
                List<Map<String,Object>> list = new ArrayList<>();
                param.put("name", "1---"+i);
                list.add(param);
                ProductQueueUtil.sendMessage(channel,ConstantParam.JPUSH_QUEUE_NAME,ConstantParam.JPUSH_EXCHANGE_NAME,list);
            }
            /*close resource*/
            ProductQueueUtil.closeResource(connection,channel);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void test2()
    {
        try
        {
             Connection connection = ProductQueueUtil.getConnection();
             Channel channel = ProductQueueUtil.getChannel(connection,ConstantParam.SMS_QUEUE_NAME,ConstantParam.SMS_EXCHANGE_NAME);
            for (int i=300;i<600;i++){
                List<Map<String,Object>> list = new ArrayList<>();
                Map<String, Object> param = new HashMap<>();
                param.put("name", "2---"+i);
                list.add(param);
                // 创建队列
                ProductQueueUtil.sendMessage(channel,ConstantParam.SMS_QUEUE_NAME,ConstantParam.SMS_EXCHANGE_NAME,list);
            }
            /*close resource*/
            ProductQueueUtil.closeResource(connection,channel);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

8、結果を参照してください実行

9は、彼らはお茶のハハカップをやっています 

公開された21元の記事 ウォンの賞賛8 ビュー40万+

おすすめ

転載: blog.csdn.net/qq_31150503/article/details/86694030