【java-activemq】 请求应答模式
博客专区 > _______- 的博客 > 博客详情
【java-activemq】 请求应答模式
_______- 发表于5个月前
【java-activemq】 请求应答模式
  • 发表于 5个月前
  • 阅读 6
  • 收藏 1
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   


import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;


/**
 *  这里server端要执行的过程和client端相反,它是先接收消息,在接收到消息后根据提供的JMSCorelationID来发送返回的消息
 * @author JS-007
 *
 */
public class Server  {
    private static String messageBrokerUrl;
 
    private Session session;
    private MessageProducer replyProducer;
 
    static {
        messageBrokerUrl = "tcp://localhost:61616";
    }
 
    public Server() {
        try {
            BrokerService broker = new BrokerService();
            broker.setPersistent(false);
            broker.setUseJmx(false);
            broker.addConnector(messageBrokerUrl);
            broker.start();
        } catch (Exception e) {
            
        }
 
        this.setupMessageQueueConsumer();
    }
 
    private void setupMessageQueueConsumer() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(messageBrokerUrl);
        Connection connection;
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            
            //Producer
            this.replyProducer = this.session.createProducer(null); //设置一个消息生成器响应来自客户端的消息,我们将从一个消息发送到从jmsreplytoheader字段发送到的目的地
            this.replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            
            //consumer
            Destination adminQueue = this.session.createQueue("client.messages");
            MessageConsumer consumer = this.session.createConsumer(adminQueue);//设置消费者从管理队列中消费消息
            consumer.setMessageListener(new MessageListener(){

				@Override
				public void onMessage(Message message) {
					try {
			            TextMessage response = session.createTextMessage();
			            if (message instanceof TextMessage) {
			                TextMessage txtMsg = (TextMessage) message;
			                String messageText = txtMsg.getText();
			                
			                String responseText;
			                if ("MyProtocolMessage".equalsIgnoreCase(messageText)) {// 判断是否是client传过来的信息,在这里就可以做些解析
			                    responseText = "服务端返回给你消息了";
			                } else {
			                    responseText = "我不知道你传的是什么: " + messageText;
			                }
			                response.setText(responseText);
			            }
			 
			            //从接收到的消息中设置相关ID为响应消息的相关ID
			            //这可以让客户端识别该消息的响应
			            //向服务器发送的一个未完成的消息
			            response.setJMSCorrelationID(message.getJMSCorrelationID());
			 
			            //将响应发送到接收消息的JMSReplyTo字段指定的目的地,
			            //这大概是客户创建的临时队列
			           replyProducer.send(message.getJMSReplyTo(), response);
			        } catch (JMSException e) {
			            //妥善处理异常
			        }
				}
            	
            });
        } catch (JMSException e) {
            
        }
    }
 
 
    public static void main(String[] args) {
        new Server();
    }
}


import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.Random;


/**
 * 
 *client端创建一个临时队列并在发送的消息里指定了发送返回消息的destination以及correlationID。那么在处理消息的server端得到这个消息后就知道该发送给谁
 * @author JS-007
 *
 */
public class Client {
 
    private MessageProducer producer;
 
    public Client() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection;
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            
            //producer
            Destination adminQueue = session.createQueue("client.messages");
            producer = session.createProducer(adminQueue);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            
            //consumer
            Destination tempDest = session.createTemporaryQueue();
            MessageConsumer responseConsumer = session.createConsumer(tempDest);
            responseConsumer.setMessageListener(new MessageListener(){
				@Override
				 public void onMessage(Message message) {
			        String messageText = null;
			        try {
			            if (message instanceof TextMessage) {
			                TextMessage textMessage = (TextMessage) message;
			                messageText = textMessage.getText();
			                System.out.println("客户端等待服务端应答 = " + messageText);
			            }
			        } catch (JMSException e) {
			           
			        }
			    }
            });
 
            TextMessage txtMessage= createTextMessage(session,tempDest);
            this.producer.send(txtMessage);
        } catch (JMSException e) {
        	
        }
    }
    
    private TextMessage createTextMessage(Session session,Destination tempDest) {
		TextMessage txtMessage=null;
		try {
			txtMessage = session.createTextMessage();
			txtMessage.setText("MyProtocolMessage1");
			txtMessage.setJMSReplyTo(tempDest);
			String correlationId = createRandomString();
			txtMessage.setJMSCorrelationID(correlationId);
		} catch (JMSException e) {
			e.printStackTrace();
		}
        return txtMessage;
    }
 
    private String createRandomString() {
        Random random = new Random(System.currentTimeMillis());
        long randomLong = random.nextLong();
        return Long.toHexString(randomLong);
    }
 
    public static void main(String[] args) {
        new Client();
    }
}
标签: 请求应答模式
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 3
博文 73
码字总数 34982
×
_______-
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: