Activemq简单的实现

Activemq简单的例子


public class SendServiceImplimplements SendService {

@Override

    public void Producer(int times,int interval,String topicname,String url,String context,String username,String password) {

try{

//创建连接工厂

ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(username,password,url);

//创建连接

            Connection connection=connectionFactory.createConnection();

            connection.start();

//创建会话

            Session session=connection.createSession(true,Session.AUTO_ACKNOWLEDGE);

//创建目的地

            Destination destination=session.createTopic(topicname);

//创建生产者

            MessageProducer messageProducer=session.createProducer(destination);

            for(int i=1;i

//创建消息

TextMessage textMessage=session.createTextMessage(context+i);

                messageProducer.send(textMessage);

                System.out.println("发送消息:"+textMessage.getText());

                session.commit();

                Thread.sleep(interval);

            }

if(connection!=null){

connection.close();

            }

}catch (Exception e){

e.printStackTrace();

        }

}

@Override

    public void Consumer(String topicname) {

try{

ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,

                    ActiveMQConnectionFactory.DEFAULT_PASSWORD,"failover:(tcp://localhost:61616)?Randomize=false");

            Connection connection=connectionFactory.createConnection();

            connection.start();

            Session session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

            Destination destination=session.createTopic(topicname);

            //MessageProducer messageProducer=session.createProducer(null);

            MessageConsumer messageConsumer=session.createConsumer(destination);

            while(true){

TextMessage textMessage=(TextMessage)messageConsumer.receive();

                if(textMessage==null){

break;

                }

System.out.println("收到的内容:"+textMessage.getText());

            }

}catch (Exception e){

e.printStackTrace();

        }

}

}

你可能感兴趣的:(Activemq简单的实现)