线程池与mq的简单结合使用

本文考虑发送方和接收方有多个线程发布消息和多个线程接收消息的情况:  

1.生产者

package com.activemq3;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者-消息发布者(多线程发送)
 * 
 */
public class JMSProducerThread {

    private static final String USERNAME=ActiveMQConnection.DEFAULT_USER; // 默认的连接用户名
    private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD; // 默认的连接密码
    private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL; // 默认的连接地址
    private static final int SENDNUM=10; // 发送的消息数量
    ConnectionFactory connectionFactory=null; // 连接工厂
    private Connection connection = null;
    private Session session = null;
    private Destination destination=null; // 消息的目的地
    public void init(){
        // 实例化连接工厂
        connectionFactory=new ActiveMQConnectionFactory(JMSProducerThread.USERNAME, JMSProducerThread.PASSWORD, JMSProducerThread.BROKEURL);
        try {
            connection=connectionFactory.createConnection(); // 通过连接工厂获取连接
            connection.start();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
    public void produce(){
        try {
            MessageProducer messageProducer; // 消息生产者
            session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 创建Session
            destination=session.createQueue("queue1");
            messageProducer=session.createProducer(destination); // 创建消息生产者
            for(int i=0;i

2.消费者

package com.activemq3;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者-消息发布者(多线程发送消息)
 *
 */
public class JMSConsumerThread {

    private static final String USERNAME=ActiveMQConnection.DEFAULT_USER; // 默认的连接用户名
    private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD; // 默认的连接密码
    private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL; // 默认的连接地址

    ConnectionFactory connectionFactory=null; // 连接工厂
    private Connection connection = null;
    private Session session = null;
    private Destination destination=null; // 消息的目的地
    public void init(){
        // 实例化连接工厂
        connectionFactory=new ActiveMQConnectionFactory(JMSConsumerThread.USERNAME, JMSConsumerThread.PASSWORD, JMSConsumerThread.BROKEURL);
        try {
            connection=connectionFactory.createConnection(); // 通过连接工厂获取连接
            connection.start();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
    public void consumer(){
        MessageConsumer messageConsumer; // 消息的消费者

        try {
            session=connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); // 创建Session
            destination=session.createQueue("queue1");
            messageConsumer=session.createConsumer(destination); // 创建消息消费者
            messageConsumer.setMessageListener(new Listener3()); // 注册消息监听
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }


}

package com.activemq3;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * 消息监听(多线程接收)
 *
 */
public class Listener3 implements MessageListener{
    private ExecutorService threadPool =Executors.newFixedThreadPool(8);
    @Override
    public void onMessage(final Message message) {
    threadPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    try {
                        Thread.sleep(new Random().nextInt(2)*500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("接收线程..."+Thread.currentThread().getName()+"收到的消息是:"+((TextMessage)message).getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }               
            }
        }); 
    }
}
生产者执行发送的主函数:  

在main方法中创建了一个固定3个 线程的线程池,去处理5个线程任务。

package com.activemq3;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 多线程发送消息
 */

public class MainProducer {
          public static void main(String[] args) {

              ExecutorService threadPool=Executors.newFixedThreadPool(3);
              for (int i = 0; i < 5; i++) {
                  threadPool.submit(new Runnable() {

                    @Override
                    public void run() {
                        JMSProducerThread jph=new JMSProducerThread();
                        try {
                            Thread.sleep(new Random().nextInt(5)*500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        jph.init();
                        jph.produce();                      
                    }
                });

            }
             /* 
            for (int i = 0; i <5; i++) {

               new Thread(new Runnable() {

                @Override
                public void run() {
                    JMSProducerThread js=new JMSProducerThread();
                    try {
                        Thread.sleep(new Random().nextInt(5)*500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    js.init();
                    js.produce();

                }
            }).start();

            }*/         
            }
}
消费者执行发送的主函数:  

消费者中监听器中创建了固定8个线程的线程池去接收消息。

package com.activemq3;
public class MainConsumer {
          public static void main(String[] args) {
            JMSConsumerThread jch=new JMSConsumerThread();
            jch.init();
            jch.consumer();             
  }
}

你可能感兴趣的:(rabbitmq,/radis/,线程池)