最近因为一个需求需要对大批量的用户进行消息推送功能,就想到了使用RabbitMQ进行处理。然后就对RabbitMQ进行抽离变成一个工具类直接调用即可,废话不多说直接开始
1、安装RabbitMQ
https://blog.csdn.net/red_sheeps/article/details/78386303
2、添加VirtualHost -------member
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、大功告成 喝杯茶 哈哈