The JMS API stipulates that the client can use four ACK_MODEs. In the javax.jms.Session interface:
AUTO_ACKNOWLEDGE = 1 Automatically confirms
CLIENT_ACKNOWLEDGE = 2 The client manually confirms
DUPS_OK_ACKNOWLEDGE = 3 Automatic batch confirmation
SESSION_TRANSACTED = 0 Transactions are submitted and confirmed
Can be sent Message types include ObjectMessage, TextMessage, and MapMessage
(1) The point-to-point message model requires only one message producer and message consumer. The following is the code.
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.jms.ObjectMessage; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; /** * The producer (sender) of the message * * */ public class JMSProducer { //default connection username private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; //default connection password private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; //default connection address private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL; //Number of messages sent private static final int SENDNUM = 10; public static void main(String[] args) { //connection factory ConnectionFactory connectionFactory; //connect Connection connection = null; //The thread that the session accepts or sends messages Session session; // destination of the message Destination destination; // message producer MessageProducer messageProducer; //Instantiate the connection factory connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL); try { //Get the connection through the connection factory connection = connectionFactory.createConnection(); // start the connection connection.start(); //create session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); //Create a message queue named HelloWorld destination = session.createQueue("HelloWorld"); //create message producer messageProducer = session.createProducer(destination); //send messages sendMessage(session, messageProducer); session.commit(); } catch (Exception e) { e.printStackTrace (); }finally{ if(connection != null){ try { connection.close(); } catch (JMSException e) { e.printStackTrace (); } } } } /** * send messages * @param session * @param messageProducer message producer * @throws Exception */ public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception{ for (int i = 0; i < JMSProducer.SENDNUM; i++) { //create a text message TextMessage message = session.createTextMessage("ActiveMQ 发送消息" +i); System.out.println("Send message: Activemq sends message" + i); // Send a message through the message producer messageProducer.send(message); } } }
write consumer
import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.ObjectMessage; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; /** * The consumer (receiver) of the message * * */ public class JMSConsumer { private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;//The default connection username, the default is empty private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//The default connection password, the default is empty private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;//Default connection address, tcp://localhost:61616 public static void main(String[] args) { ConnectionFactory connectionFactory;//Connection Factory Connection connection = null;//Connection Session session;//The thread that the session accepts or sends messages Destination destination;//The destination of the message MessageConsumer messageConsumer;//Message consumer //Instantiate the connection factory connectionFactory = new ActiveMQConnectionFactory(JMSConsumer.USERNAME, JMSConsumer.PASSWORD, JMSConsumer.BROKEURL); try { //Get the connection through the connection factory connection = connectionFactory.createConnection(); // start the connection connection.start(); //create session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //Create a message queue connected to HelloWorld destination = session.createQueue("HelloWorld"); //create message consumer messageConsumer = session.createConsumer(destination); while (true) { //Set the time for the receiver to receive the message. If the receiver does not receive the message after the time is exceeded, the next step will be executed. If this parameter is not set, it will be blocked for a long time and will not execute the next operation until there is a message before executing the next step. For the convenience of testing, who decides here for 500s TextMessage textMessage = (TextMessage) messageConsumer.receive(50000); if(textMessage != null){ System.out.println("Received message: " + textMessage.getText()); }else { connection.close(); break; } } System.out.println("Message execution completed!"); } catch (JMSException e) { e.printStackTrace (); } } }
Run
First , start ActiveMQ, then enter: http://localhost:8161/admin/ in the browser, and then start executing:
run the sender, myeclipse console output, as shown below:
At this point, let's take a look at the ActiveMQ server, The content of Queues is as follows:
We can see that a message queue named HelloWorld has been created. There are 10 messages in the queue that have not been consumed. We can also view which messages are through Browse, as shown in the figure below:
(2) The publish-subscribe mode of the message is
written message publishing object
import java.util.Random; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQMapMessage; public class Publisher { //default connection username private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; //default connection password private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; //default connection address private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL; //connection factory ConnectionFactory connectionFactory; //connect Connection connection = null; //The thread that the session accepts or sends messages Session session; // message producer MessageProducer messageProducer; // destination of the message Destination []destinations; public Publisher() throws JMSException { //Instantiate the connection factory connectionFactory = new ActiveMQConnectionFactory(Publisher.USERNAME, Publisher.PASSWORD, Publisher.BROKEURL); //Get the connection through the connection factory connection = connectionFactory.createConnection(); try { connection.start(); } catch (JMSException jmse) { connection.close(); throw jmse; } session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ; messageProducer = session.createProducer(null); } protected void setTopics(String[] topics) throws JMSException { destinations = new Destination[topics.length]; for(int i = 0; i < topics.length; i++) { destinations[i] = session.createTopic("TOPICS." + topics[i]); } } protected Message createMessage(String msg,int age, Session session) throws JMSException { MapMessage message = session.createMapMessage(); message.setString("name", msg); message.setInt("age", age); return message; } protected void sendMessage(String msg,int age) throws JMSException { for(int i = 0; i < destinations.length; i++) { Message message = createMessage(msg,age, session); System.out.println("Send: " + ((ActiveMQMapMessage)message).getContentMap() + " to destination: " + destinations[i]); messageProducer.send(destinations[i], message); } } public void close() throws JMSException { if (connection != null) { connection.close(); } } public static void main(String[] args) throws JMSException { // create a post message object Publisher publisher = new Publisher(); // set up subscribers String []strs=new String[]{"Subscriber01","Subscriber02","Subscriber03","Subscriber04"}; publisher.setTopics(strs); Random generator = new Random(); for(int i=0;i<2;i++){ //Set the message to send publisher.sendMessage("美男"+i,generator.nextInt(90)); try { Thread.sleep(1000);//Pause for 1 second each time a message is sent, this is optional, in order to display the effect of a pause } catch(InterruptedException e) { e.printStackTrace (); } } // close the link publisher.close(); } }
Write a message subscription object (receiver)
import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Session; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; public class Consumer implements MessageListener{ //default connection username private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; //default connection password private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; //default connection address private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL; //connection factory ConnectionFactory connectionFactory; //connect Connection connection = null; //The thread that the session accepts or sends messages Session session; MessageConsumer messageConsumer; public Consumer(String topic) throws JMSException { //Instantiate the connection factory connectionFactory = new ActiveMQConnectionFactory(Consumer.USERNAME, Consumer.PASSWORD, Consumer.BROKEURL); //Get the connection through the connection factory connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createTopic("TOPICS." + topic); messageConsumer = session.createConsumer(destination); } public MessageConsumer getMessageConsumer() { return messageConsumer; } public static void main(String[] args) throws JMSException { String []topics=new String[]{"Subscriber01","Subscriber02","Subscriber03","Subscriber04"}; for (String topic : topics) { Consumer consumer = new Consumer(topic); MessageConsumer messageConsumer=consumer.getMessageConsumer(); messageConsumer.setMessageListener(consumer); } } @Override public void onMessage(Message msg) { // TODO Auto-generated method stub try { MapMessage map = (MapMessage)msg; String name = map.getString("name"); int age = map.getInt("age"); System.out.println(name+" 年龄:"+age+"\n"); } catch (Exception e) { e.printStackTrace (); } } }
Run the subscriber object first, because under the publish/subscribe message model, only the subscriber can send successfully in the start or listening state. myeclispe is shown in the following figure.
At this point , let's take a look at the ActiveMQ server. The Topic content is as follows: