本文整理了Java中javax.jms.Message
类的一些代码示例,展示了Message
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Message
类的具体详情如下:
包路径:javax.jms.Message
类名称:Message
[英]The Message interface is the root interface of all JMS messages. It defines the message header and the acknowledge method used for all messages.
Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header and a body. The header contains fields used for message routing and identification; the body contains the application data being sent.
Within this general form, the definition of a message varies significantly across products. It would be quite difficult for the JMS API to support all of these message models.
With this in mind, the JMS message model has the following goals:
JMS messages are composed of the following parts:
The JMS API defines five types of message body:
The JMSCorrelationID header field is used for linking one message with another. It typically links a reply message with its requesting message.
JMSCorrelationID can hold a provider-specific message ID, an application-specific String object, or a provider-native byte[] value.
A Message object contains a built-in facility for supporting application-defined property values. In effect, this provides a mechanism for adding application-specific header fields to a message.
Properties allow an application, via message selectors, to have a JMS provider select, or filter, messages on its behalf using application-specific criteria.
Property names must obey the rules for a message selector identifier. Property names must not be null, and must not be empty strings. If a property name is set and it is either null or an empty string, an IllegalArgumentException must be thrown.
Property values can be boolean, byte, short, int, long, float, double, and String.
Property values are set prior to sending a message. When a client receives a message, its properties are in read-only mode. If a client attempts to set properties at this point, a MessageNotWriteableException is thrown. If clearProperties is called, the properties can now be both read from and written to. Note that header fields are distinct from properties. Header fields are never in read-only mode.
A property value may duplicate a value in a message's body, or it may not. Although JMS does not define a policy for what should or should not be made a property, application developers should note that JMS providers will likely handle data in a message's body more efficiently than data in a message's properties. For best performance, applications should use message properties only when they need to customize a message's header. The primary reason for doing this is to support customized message selection.
Message properties support the following conversion table. The marked cases must be supported. The unmarked cases must throw a JMSException. The String-to-primitive conversions may throw a runtime exception if the primitive's valueOf method does not accept the String as a valid representation of the primitive.
A value written as the row type can be read as the column type.
| | boolean byte short int long float double String
|----------------------------------------------------------
|boolean | X X
|byte | X X X X X
|short | X X X X
|int | X X X
|long | X X
|float | X X X
|double | X X
|String | X X X X X X X X
|----------------------------------------------------------
In addition to the type-specific set/get methods for properties, JMS provides the setObjectProperty and getObjectProperty methods. These support the same set of property types using the objectified primitive values. Their purpose is to allow the decision of property type to made at execution time rather than at compile time. They support the same property value conversions.
The setObjectProperty method accepts values of class Boolean, Byte, Short, Integer, Long, Float, Double, and String. An attempt to use any other class must throw a JMSException.
The getObjectProperty method only returns values of class Boolean, Byte, Short, Integer, Long, Float, Double, and String.
The order of property values is not defined. To iterate through a message's property values, use getPropertyNames to retrieve a property name enumeration and then use the various property get methods to retrieve their values.
A message's properties are deleted by the clearPropertiesmethod. This leaves the message with an empty set of properties.
Getting a property value for a name which has not been set returns a null value. Only the getStringProperty and getObjectProperty methods can return a null value. Attempting to read a null value as a primitive type must be treated as calling the primitive's corresponding valueOf(String) conversion method with a null value.
The JMS API reserves the JMSX property name prefix for JMS defined properties. The full set of these properties is defined in the Java Message Service specification. The specification also defines whether support for each property is mandatory or optional. New JMS defined properties may be added in later versions of the JMS API. The String[] ConnectionMetaData.getJMSXPropertyNames method returns the names of the JMSX properties supported by a connection.
JMSX properties may be referenced in message selectors whether or not they are supported by a connection. If they are not present in a message, they are treated like any other absent property. The effect of setting a message selector on a property which is set by the provider on receive is undefined.
JMSX properties defined in the specification as "set by provider on send" are available to both the producer and the consumers of the message. JMSX properties defined in the specification as "set by provider on receive" are available only to the consumers.
JMSXGroupID and JMSXGroupSeq are standard properties that clients should use if they want to group messages. All providers must support them. Unless specifically noted, the values and semantics of the JMSX properties are undefined.
The JMS API reserves the JMS_vendor_name property name prefix for provider-specific properties. Each provider defines its own value for vendor_name. This is the mechanism a JMS provider uses to make its special per-message services available to a JMS client.
The purpose of provider-specific properties is to provide special features needed to integrate JMS clients with provider-native clients in a single JMS application. They should not be used for messaging between JMS clients.
The JMS API provides a set of message interfaces that define the JMS message model. It does not provide implementations of these interfaces.
Each JMS provider supplies a set of message factories with its Session object for creating instances of messages. This allows a provider to use message implementations tailored to its specific needs.
A provider must be prepared to accept message implementations that are not its own. They may not be handled as efficiently as its own implementation; however, they must be handled.
Note the following exception case when a provider is handling a foreign message implementation. If the foreign message implementation contains a JMSReplyTo header field that is set to a foreign destination implementation, the provider is not required to handle or preserve the value of this header field.
A JMS message selector allows a client to specify, by header field references and property references, the messages it is interested in. Only messages whose header and property values match the selector are delivered. What it means for a message not to be delivered depends on the MessageConsumer being used (see javax.jms.QueueReceiver and javax.jms.TopicSubscriber).
Message selectors cannot reference message body values.
A message selector matches a message if the selector evaluates to true when the message's header field values and property values are substituted for their corresponding identifiers in the selector.
A message selector is a String whose syntax is based on a subset of the SQL92 conditional expression syntax. If the value of a message selector is an empty string, the value is treated as a null and indicates that there is no message selector for the message consumer.
The order of evaluation of a message selector is from left to right within precedence level. Parentheses can be used to change this order.
Predefined selector literals and operator names are shown here in uppercase; however, they are case insensitive.
A selector can contain:
Literals:
A string literal is enclosed in single quotes, with a single quote represented by doubled single quote; for example, 'literal' and 'literal''s'. Like string literals in the Java programming language, these use the Unicode character encoding.
Identifiers:
An identifier is an unlimited-length sequence of letters and digits, the first of which must be a letter. A letter is any character for which the method Character.isJavaLetterreturns true. This includes '_' and '$'. A letter or digit is any character for which the method Character.isJavaLetterOrDigit returns true.
myMessage.setStringProperty("NumberOfOrders", "2");
The following expression in a message selector would evaluate to false, because a string cannot be used in an arithmetic expression:
"NumberOfOrders > 1"
* Identifiers are case-sensitive.
* Message header field references are restricted to JMSDeliveryMode, JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be null and if so are treated as a NULL value.
* Any name beginning with 'JMSX' is a JMS defined property name.
* Any name beginning with 'JMS_' is a provider-specific property name.
* Any name that does not begin with 'JMS' is an application-specific property name.
White space is the same as that defined for the Java programming language: space, horizontal tab, form feed, and line terminator.
Expressions:
A selector is a conditional expression; a selector that evaluates to true matches; a selector that evaluates to false or unknown does not match.
Standard bracketing () for ordering expression evaluation is supported.
Logical operators in precedence order: NOT, AND, OR
Comparison operators: =, >, >=, (not equal)
Only like type values can be compared. One exception is that it is valid to compare exact numeric values and approximate numeric values; the type conversion required is defined by the rules of numeric promotion in the Java programming language. If the comparison of non-like type values is attempted, the value of the operation is false. If either of the type values evaluates to NULL, the value of the expression is unknown.
Arithmetic operators in precedence order:
+, - (unary)
arithmetic-expr1 [NOT] BETWEEN arithmetic-expr2 (comparison operator)
"age BETWEEN 15 AND 19" is equivalent to "age >= 15 AND age "age NOT BETWEEN 15 AND 19" is equivalent to "age 19"
identifier [NOT] IN (string-literal1, (comparison operator where identifier has a String or NULL value)
"Country IN (' UK', 'US', 'France')"is true for 'UK' and false for 'Peru'; it is equivalent to the expression "(Country = ' UK') OR (Country = ' US') OR (Country = ' France')"
identifier [NOT] LIKE pattern-value [ESCAPE (comparison operator, where identifier has a String value; pattern-value is a string literal where '' stands for any single character; '%' stands for any sequence of characters, including the empty sequence; and all other characters stand for themselves. The optional escape-character is a single-character string literal whose character is used to escape the special meaning of the '' and '%' in pattern-value.)
"phone LIKE '12%3'" is true for '123' or '12993' and false for '1234'
identifier IS NULL (comparison operator that tests for a null header field value or a missing property value)
"prop_name IS NULL"
identifier IS NOT NULL (comparison operator that tests for the existence of a non-null header field value or a property value)
"prop_name IS NOT NULL"
JMS providers are required to verify the syntactic correctness of a message selector at the time it is presented. A method that provides a syntactically incorrect selector must result in a JMSException. JMS providers may also optionally provide some semantic checking at the time the selector is presented. Not all semantic checking can be performed at the time a message selector is presented, because property types are not known.
The following message selector selects messages with a message type of car and color of blue and weight greater than 2500 pounds:
"JMSType = 'car' AND color = 'blue' AND weight > 2500"
As noted above, property values may be NULL. The evaluation of selector expressions containing NULL values is defined by SQL92 NULL semantics. A brief description of these semantics is provided here.
SQL treats a NULL value as unknown. Comparison or arithmetic with an unknown value always yields an unknown value.
The IS NULL and IS NOT NULL operators convert an unknown value into the respective TRUE and FALSE values.
The boolean operators use three-valued logic as defined by the following tables:
The definition of the AND operator
| AND | T | F | U
+------+-------+-------+-------
| T | T | F | U
| F | F | F | F
| U | U | F | U
+------+-------+-------+-------
The definition of the OR operator
| OR | T | F | U
+------+-------+-------+--------
| T | T | T | T
| F | T | F | U
| U | T | U | U
+------+-------+-------+-------
The definition of the NOT operator
| NOT
+------+------
| T | F
| F | T
| U | U
+------+-------
When used in a message selector, the JMSDeliveryMode header field is treated as having the values 'PERSISTENT' and 'NON_PERSISTENT'.
Date and time values should use the standard long millisecond value. When a date or time literal is included in a message selector, it should be an integer literal for a millisecond value. The standard way to produce millisecond values is to use java.util.Calendar.
Although SQL supports fixed decimal comparison and arithmetic, JMS message selectors do not. This is the reason for restricting exact numeric literals to those without a decimal (and the addition of numerics with a decimal as an alternate representation for approximate numeric values).
SQL comments are not supported.
[中]消息接口是所有JMS消息的根接口。它定义了用于所有消息的消息头和确认方法。
大多数面向消息的中间件(MOM)产品将消息视为轻量级实体,由头和体组成。报头包含用于消息路由和标识的字段;正文包含正在发送的应用程序数据。
在这种通用形式中,消息的定义因产品而异。JMS API很难支持所有这些消息模型。
考虑到这一点,JMS消息模型具有以下目标:
*提供单一、统一的消息API
*提供一个API,用于创建与提供者本机消息传递应用程序使用的格式相匹配的消息
*支持跨操作系统、机器体系结构和计算机语言的异构应用程序的开发
*支持包含Java编程语言中对象的消息(“Java对象”)
*支持包含可扩展标记语言(XML)页面的消息
JMS消息由以下部分组成:
*Header—所有消息都支持相同的标题字段集。标头字段包含客户端和提供者用于标识和路由消息的值。
*属性-每条消息都包含一个内置功能,用于支持应用程序定义的属性值。属性为支持应用程序定义的消息过滤提供了一种有效的机制。
*正文——JMS API定义了几种类型的消息正文,涵盖了当前使用的大多数消息传递样式。
#####消息体
JMS API定义了五种类型的消息体:
*Stream——StreamMessage对象的消息体包含Java编程语言中的原语值流(“Java原语”)。它是按顺序填充和读取的。
*Map——MapMessage对象的消息体包含一组名称-值对,其中名称是字符串对象,值是Java原语。可以按名称顺序或随机访问条目。条目的顺序未定义。
*Text-TextMessage对象的消息体包含java。字符串对象。此消息类型可用于传输纯文本消息和XML消息。
*对象-ObjectMessage对象的消息体包含可序列化的Java对象。
*字节-ByteMessage对象的消息体包含未解释的字节流。此消息类型用于对正文进行字面编码,以匹配现有消息格式。在许多情况下,可以使用其他更易于使用的车身类型之一。尽管JMS API允许在字节消息中使用消息属性,但通常不使用它们,因为包含属性可能会影响格式。
#####消息头
JMSCorrelationID标头字段用于将一条消息链接到另一条消息。它通常将回复消息与其请求消息链接起来。
JMSCorrelationID可以保存特定于提供程序的消息ID、特定于应用程序的字符串对象或提供程序本机字节[]值。
#####消息属性
消息对象包含用于支持应用程序定义的属性值的内置工具。实际上,这提供了一种向消息中添加特定于应用程序的头字段的机制。
属性允许应用程序通过消息选择器让JMS提供程序使用特定于应用程序的条件代表其选择或筛选消息。
属性名称必须遵守消息选择器标识符的规则。属性名不能为null,也不能为空字符串。如果设置了属性名称,并且该名称为null或空字符串,则必须引发IllegalArgumentException。
属性值可以是布尔值、字节值、短值、int值、长值、浮点值、双精度值和字符串。
属性值在发送消息之前设置。当客户端收到消息时,其属性处于只读模式。如果客户端试图在此时设置属性,则会抛出MessageNotWriteableException。如果调用了clearProperties,那么现在可以读取和写入这些属性。请注意,标题字段不同于属性。标题字段从不处于只读模式。
属性值可以与消息正文中的值重复,也可以不重复。尽管JMS没有为哪些内容应该或不应该成为属性定义策略,但应用程序开发人员应该注意,JMS提供程序可能会比消息属性中的数据更有效地处理消息体中的数据。为了获得最佳性能,应用程序只应在需要自定义消息头时使用消息属性。这样做的主要原因是支持定制的消息选择。
消息属性支持以下转换表。标记的案例必须得到支持。未标记的病例必须带有JMSException。如果原语的valueOf方法不接受字符串作为原语的有效表示形式,则字符串到原语的转换可能会引发运行时异常。
作为行类型写入的值可以作为列类型读取。
| | boolean byte short int long float double String
|----------------------------------------------------------
|boolean | X X
|byte | X X X X X
|short | X X X X
|int | X X X
|long | X X
|float | X X X
|double | X X
|String | X X X X X X X X
|----------------------------------------------------------
除了针对属性的特定于类型的set/get方法外,JMS还提供了setObjectProperty和getObjectProperty方法。它们支持使用对象化原语值的同一组属性类型。它们的目的是允许在执行时而不是在编译时做出属性类型的决定。它们支持相同的属性值转换。
setObjectProperty方法接受Boolean、Byte、Short、Integer、Long、Float、Double和String类的值。尝试使用任何其他类都必须抛出JMSException。
getObjectProperty方法只返回Boolean、Byte、Short、Integer、Long、Float、Double和String类的值。
未定义属性值的顺序。要遍历消息的属性值,请使用getPropertyNames检索属性名枚举,然后使用各种property get方法检索它们的值。
通过clearPropertiesmethod删除消息的属性。这将使消息的属性集为空。
获取尚未设置的名称的属性值将返回空值。只有getStringProperty和getObjectProperty方法可以返回空值。尝试将null值作为基元类型读取时,必须视为使用null值调用基元对应的valueOf(String)转换方法。
JMS API为JMS定义的属性保留JMSX属性名称前缀。这些属性的完整集合在Java消息服务规范中定义。该规范还定义了对每个属性的支持是强制的还是可选的。新的JMS定义属性可能会添加到更高版本的JMS API中。字符串[]ConnectionMetaData。getJMSXPropertyNames方法返回连接支持的JMSX属性的名称。
JMSX属性可以在消息选择器中引用,无论连接是否支持它们。如果它们没有出现在消息中,它们将被视为任何其他不存在的属性。在提供者在接收时设置的属性上设置消息选择器的效果未定义。
规范中定义为“发送时由提供者设置”的JMSX属性对消息的生产者和使用者都可用。规范中定义为“接收时由提供者设置”的JMSX属性仅对使用者可用。
JMSXGroupID和JMSXGroupSeq是标准属性,如果客户端希望对消息进行分组,则应使用这些属性。所有供应商都必须支持他们。除非特别说明,否则JMSX属性的值和语义尚未定义。
JMS API为特定于提供者的属性保留JMS_供应商_名称属性名称前缀。每个提供者都为供应商名称定义自己的值。这是JMS提供者用于使其特殊的每消息服务可用于JMS客户机的机制。
特定于提供者的属性的目的是提供在单个JMS应用程序中集成JMS客户端和提供者本地客户端所需的特殊功能。它们不应用于JMS客户端之间的消息传递。
#####JMS消息接口的提供者实现
JMS API提供了一组定义JMS消息模型的消息接口。它不提供这些接口的实现。
每个JMS提供程序都提供一组消息工厂及其会话对象,用于创建消息实例。这允许提供者使用根据其特定需求定制的消息实现。
提供者必须准备好接受非其自身的消息实现。它们的处理效率可能不如其自身的实施效率高;然而,它们必须得到处理。
请注意,当提供程序处理外部消息实现时,会出现以下异常情况。如果外部消息实现包含设置为外部目标实现的JMSReplyTo头字段,则提供程序无需处理或保留此头字段的值。
#####消息选择器
JMS消息选择器允许客户端通过头字段引用和属性引用指定它感兴趣的消息。只有标头和属性值与选择器匹配的消息才会被传递。消息不被传递意味着什么取决于所使用的MessageConsumer(请参见javax.jms.QueueReceiver和javax.jms.TopicSubscriber)。
消息选择器无法引用消息正文值。
当消息的标题字段值和属性值替换为选择器中相应的标识符时,如果选择器的计算结果为true,则消息选择器将匹配消息。
消息选择器是一个字符串,其语法基于SQL92条件表达式语法的子集。如果消息选择器的值为空字符串,则该值将被视为null,并指示消息使用者没有消息选择器。
消息选择器的求值顺序在优先级范围内从左到右。括号可用于更改此顺序。
预定义的选择器文字和运算符名称在此以大写形式显示;然而,事实并非如此
代码示例来源:origin: spring-projects/spring-framework
try {
try {
String correlationId = jmsMessage.getJMSCorrelationID();
if (correlationId != null) {
headers.put(JmsHeaders.CORRELATION_ID, correlationId);
Destination destination = jmsMessage.getJMSDestination();
if (destination != null) {
headers.put(JmsHeaders.DESTINATION, destination);
int deliveryMode = jmsMessage.getJMSDeliveryMode();
headers.put(JmsHeaders.DELIVERY_MODE, deliveryMode);
long expiration = jmsMessage.getJMSExpiration();
headers.put(JmsHeaders.EXPIRATION, expiration);
String messageId = jmsMessage.getJMSMessageID();
if (messageId != null) {
headers.put(JmsHeaders.MESSAGE_ID, messageId);
headers.put(JmsHeaders.PRIORITY, jmsMessage.getJMSPriority());
Destination replyTo = jmsMessage.getJMSReplyTo();
if (replyTo != null) {
headers.put(JmsHeaders.REPLY_TO, replyTo);
headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered());
String type = jmsMessage.getJMSType();
代码示例来源:origin: spring-projects/spring-framework
String typeId = message.getStringProperty(this.typeIdPropertyName);
if (typeId == null) {
throw new MessageConversionException(
"Could not find type id property [" + this.typeIdPropertyName + "] on message [" +
message.getJMSMessageID() + "] from destination [" + message.getJMSDestination() + "]");
代码示例来源:origin: apache/hive
Message msg = session.get().createTextMessage(hCatEventMessage.toString());
msg.setStringProperty(HCatConstants.HCAT_EVENT, hCatEventMessage.getEventType().toString());
msg.setStringProperty(HCatConstants.HCAT_MESSAGE_VERSION, messageFactory.getVersion());
msg.setStringProperty(HCatConstants.HCAT_MESSAGE_FORMAT, messageFactory.getMessageFormat());
MessageProducer producer = createProducer(topic);
producer.send(msg);
session.get().commit();
} catch (Exception e) {
if (retries >= 0) {
代码示例来源:origin: spring-projects/spring-framework
/**
* Post-process the given response message before it will be sent.
* <p>The default implementation sets the response's correlation id
* to the request message's correlation id, if any; otherwise to the
* request message id.
* @param request the original incoming JMS message
* @param response the outgoing JMS message about to be sent
* @throws JMSException if thrown by JMS API methods
* @see javax.jms.Message#setJMSCorrelationID
*/
protected void postProcessResponse(Message request, Message response) throws JMSException {
String correlation = request.getJMSCorrelationID();
if (correlation == null) {
correlation = request.getJMSMessageID();
}
response.setJMSCorrelationID(correlation);
}
代码示例来源:origin: apache/activemq
/**
* Copies the standard JMS and user defined properties from the givem
* message to the specified message
*
* @param fromMessage the message to take the properties from
* @param toMessage the message to add the properties to
* @throws JMSException
*/
public static void copyProperties(Message fromMessage, Message toMessage) throws JMSException {
toMessage.setJMSMessageID(fromMessage.getJMSMessageID());
toMessage.setJMSCorrelationID(fromMessage.getJMSCorrelationID());
toMessage.setJMSReplyTo(transformDestination(fromMessage.getJMSReplyTo()));
toMessage.setJMSDestination(transformDestination(fromMessage.getJMSDestination()));
toMessage.setJMSDeliveryMode(fromMessage.getJMSDeliveryMode());
toMessage.setJMSRedelivered(fromMessage.getJMSRedelivered());
toMessage.setJMSType(fromMessage.getJMSType());
toMessage.setJMSExpiration(fromMessage.getJMSExpiration());
toMessage.setJMSPriority(fromMessage.getJMSPriority());
toMessage.setJMSTimestamp(fromMessage.getJMSTimestamp());
Enumeration propertyNames = fromMessage.getPropertyNames();
while (propertyNames.hasMoreElements()) {
String name = propertyNames.nextElement().toString();
Object obj = fromMessage.getObjectProperty(name);
toMessage.setObjectProperty(name, obj);
}
}
}
代码示例来源:origin: apache/activemq-artemis
@Test
public void testReceiveNoWaitOnTopic() throws Exception {
Connection producerConnection = null;
Connection consumerConnection = null;
try {
producerConnection = createConnection();
consumerConnection = createConnection();
Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final MessageProducer topicProducer = producerSession.createProducer(ActiveMQServerTestCase.topic1);
MessageConsumer topicConsumer = consumerSession.createConsumer(ActiveMQServerTestCase.topic1);
consumerConnection.start();
Message m = topicConsumer.receiveNoWait();
ProxyAssertSupport.assertNull(m);
Message m1 = producerSession.createMessage();
topicProducer.send(m1);
// block this thread for a while to allow ServerConsumerDelegate's delivery thread to kick in
Thread.sleep(500);
m = topicConsumer.receiveNoWait();
ProxyAssertSupport.assertEquals(m1.getJMSMessageID(), m.getJMSMessageID());
} finally {
if (producerConnection != null) {
producerConnection.close();
}
if (consumerConnection != null) {
consumerConnection.close();
}
}
}
代码示例来源:origin: org.jboss.arquillian.example/arquillian-example-domain
public void onMessage(Message msg)
{
try
{
System.out.println("received " + msg.getJMSMessageID());
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(msg.getJMSReplyTo());
producer.send(msg);
producer.close();
session.close();
connection.close();
}
catch (Exception e)
{
throw new RuntimeException("Could not reply to message", e);
}
}
}
代码示例来源:origin: apache/activemq-artemis
private void testPriority(Connection connection1, Connection connection2) throws JMSException {
try {
Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue1 = session1.createQueue(getQueueName());
javax.jms.Queue queue2 = session2.createQueue(getQueueName());
final MessageConsumer consumer2 = session2.createConsumer(queue2);
MessageProducer producer = session1.createProducer(queue1);
producer.setPriority(2);
connection1.start();
TextMessage message = session1.createTextMessage();
message.setText("hello");
producer.send(message);
Message received = consumer2.receive(100);
assertNotNull("Should have received a message by now.", received);
assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);
assertEquals(2, received.getJMSPriority());
} finally {
connection1.close();
connection2.close();
}
}
代码示例来源:origin: apache/cxf
private void receiveAndRespond() {
try (ResourceCloser closer = new ResourceCloser()) {
Connection connection = closer.register(connectionFactory.createConnection());
connection.start();
Session session = closer.register(connection.createSession(false, Session.AUTO_ACKNOWLEDGE));
MessageConsumer consumer = closer.register(session.createConsumer(session
.createQueue(receiveQueueName)));
final javax.jms.Message inMessage = consumer.receive(10000);
if (inMessage == null) {
//System.out.println("TestReceiver timed out");
throw new RuntimeException("No message received on destination " + receiveQueueName);
}
requestMessageId = inMessage.getJMSMessageID();
//System.out.println("Received message " + requestMessageId);
final TextMessage replyMessage = session.createTextMessage("Result");
String correlationId = (forceMessageIdAsCorrelationId || inMessage.getJMSCorrelationID() == null)
? inMessage.getJMSMessageID() : inMessage.getJMSCorrelationID();
replyMessage.setJMSCorrelationID(correlationId);
Destination replyDest = staticReplyQueue != null
? session.createQueue(staticReplyQueue) : inMessage.getJMSReplyTo();
if (replyDest != null) {
final MessageProducer producer = closer
.register(session.createProducer(replyDest));
//System.out.println("Sending reply with correlation id " + correlationId + " to " + replyDest);
producer.send(replyMessage);
}
} catch (Throwable e) {
ex = e;
}
}
代码示例来源:origin: apache/activemq-artemis
@Test
public void testSendMessageAndCloseConsumer1() throws Exception {
Connection producerConnection = null;
Connection consumerConnection = null;
try {
producerConnection = createConnection();
consumerConnection = createConnection();
Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer queueProducer = producerSession.createProducer(queue1);
MessageConsumer queueConsumer = consumerSession.createConsumer(queue1);
Message m = producerSession.createMessage();
queueProducer.send(m);
queueConsumer.close();
// since no message was received, we expect the message back in the queue
queueConsumer = consumerSession.createConsumer(queue1);
consumerConnection.start();
Message r = queueConsumer.receive(2000);
ProxyAssertSupport.assertEquals(m.getJMSMessageID(), r.getJMSMessageID());
} finally {
if (producerConnection != null) {
producerConnection.close();
}
if (consumerConnection != null) {
consumerConnection.close();
}
}
removeAllMessages(queue1.getQueueName(), true);
}
代码示例来源:origin: apache/activemq-artemis
conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer cons1 = sess.createConsumer(ActiveMQServerTestCase.topic1, selector1);
MessageProducer prod = sess.createProducer(ActiveMQServerTestCase.topic1);
Message m = sess.createMessage();
m.setStringProperty("beatle", "john");
prod.send(m);
m = sess.createMessage();
m.setStringProperty("beatle", "kermit the frog");
prod.send(m);
Message m = cons1.receive(1000);
Message m = cons1.receiveNoWait();
conn.close();
代码示例来源:origin: apache/activemq
@Before
public void setUp() throws Exception {
brokerService = new BrokerService();
brokerService.setPersistent(false);
brokerService.setUseJmx(true);
String connectionUri = brokerService.addConnector("tcp://localhost:0").getPublishableConnectString();
brokerService.start();
brokerService.waitUntilStarted();
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri);
final Connection conn = connectionFactory.createConnection();
try {
conn.start();
final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Destination queue = session.createQueue(testQueueName);
final Message toSend = session.createMessage();
toSend.setStringProperty("foo", "bar");
final MessageProducer producer = session.createProducer(queue);
producer.send(queue, toSend);
} finally {
conn.close();
}
}
代码示例来源:origin: apache/activemq-artemis
private void sendMessageUsingCoreJms(String queueName) throws Exception {
Connection jmsConn = null;
try {
jmsConn = coreCf.createConnection();
Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Message message = session.createMessage();
message.setBooleanProperty("booleanProperty", false);
message.setLongProperty("longProperty", 99999L);
message.setByteProperty("byteProperty", (byte) 5);
message.setIntProperty("intProperty", 979);
message.setShortProperty("shortProperty", (short) 1099);
message.setStringProperty("stringProperty", "HelloMessage");
Queue queue = session.createQueue(queueName);
MessageProducer producer = session.createProducer(queue);
producer.send(message);
} finally {
if (jmsConn != null) {
jmsConn.close();
}
}
}
代码示例来源:origin: apache/activemq-artemis
public static String[] sendMessages(final ConnectionFactory cf,
final Destination destination,
final int messagesToSend) throws Exception {
String[] messageIDs = new String[messagesToSend];
Connection conn = cf.createConnection();
Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = s.createProducer(destination);
for (int i = 0; i < messagesToSend; i++) {
Message m = s.createTextMessage(RandomUtil.randomString());
producer.send(m);
messageIDs[i] = m.getJMSMessageID();
}
conn.close();
return messageIDs;
}
代码示例来源:origin: spring-projects/spring-framework
MessageConsumer consumer = null;
try {
responseQueue = session.createTemporaryQueue();
producer = session.createProducer(queue);
consumer = session.createConsumer(responseQueue);
requestMessage.setJMSReplyTo(responseQueue);
producer.send(requestMessage);
long timeout = getReceiveTimeout();
return (timeout > 0 ? consumer.receive(timeout) : consumer.receive());
代码示例来源:origin: apache/activemq-artemis
protected void readMessagesOnBroker(Connection connection, int count, AtomicInteger sequence) throws Exception {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(getQueueName());
MessageConsumer consumer = session.createConsumer(queue);
for (int i = 0; i < MESSAGE_COUNT; ++i) {
Message message = consumer.receive(RECEIVE_TIMEOUT);
assertNotNull(message);
LOG.debug("Read message #{}: type = {}", i, message.getClass().getSimpleName());
String gid = message.getStringProperty("JMSXGroupID");
int seq = message.getIntProperty("JMSXGroupSeq");
LOG.debug("Message assigned JMSXGroupID := {}", gid);
LOG.debug("Message assigned JMSXGroupSeq := {}", seq);
assertEquals("Sequence order should match", sequence.incrementAndGet(), seq);
}
session.close();
}
代码示例来源:origin: apache/activemq
try {
if (durable && destination instanceof Topic) {
consumer = session.createDurableSubscriber((Topic) destination, getName());
} else {
consumer = session.createConsumer(destination);
Message msg = consumer.receive(receiveTimeOut);
if (msg != null) {
LOG.info(threadName + " Received " + (msg instanceof TextMessage ? ((TextMessage) msg).getText() : msg.getJMSMessageID()));
if (bytesAsText && (msg instanceof BytesMessage)) {
long length = ((BytesMessage) msg).getBodyLength();
if (session.getTransacted()) {
if (batchSize > 0 && received > 0 && received % batchSize == 0) {
LOG.info(threadName + " Committing transaction: " + transactions++);
if (batchSize > 0 && received > 0 && received % batchSize == 0) {
LOG.info("Acknowledging last " + batchSize + " messages; messages so far = " + received);
msg.acknowledge();
LOG.info(threadName + " Consumed: " + this.getReceived() + " messages");
try {
consumer.close();
} catch (JMSException e) {
e.printStackTrace();
代码示例来源:origin: spring-projects/spring-integration
public void onMessage(javax.jms.Message request, Session session) throws JMSException {
String text = "priority=" + request.getJMSPriority();
TextMessage reply = session.createTextMessage(text);
MessageProducer producer = session.createProducer(request.getJMSReplyTo());
reply.setJMSCorrelationID(request.getJMSMessageID());
producer.send(reply);
}
}
代码示例来源:origin: apache/activemq-artemis
@Test
public void testJMSDestinationSimple() throws Exception {
Message m = queueProducerSession.createMessage();
TemporaryQueue tempQ = queueProducerSession.createTemporaryQueue();
m.setJMSReplyTo(tempQ);
queueProducer.send(m);
queueConsumer.receive();
ProxyAssertSupport.assertEquals(tempQ, m.getJMSReplyTo());
}
代码示例来源:origin: wildfly/wildfly
protected ActiveMQMessage(final Message foreign, final byte type, final ClientSession session) throws JMSException {
this(type, session);
setJMSTimestamp(foreign.getJMSTimestamp());
byte[] corrIDBytes = foreign.getJMSCorrelationIDAsBytes();
setJMSCorrelationIDAsBytes(corrIDBytes);
} catch (JMSException e) {
String corrIDString = foreign.getJMSCorrelationID();
if (corrIDString != null) {
setJMSCorrelationID(corrIDString);
String corrIDString = foreign.getJMSCorrelationID();
if (corrIDString != null) {
setJMSCorrelationID(corrIDString);
setJMSReplyTo(foreign.getJMSReplyTo());
setJMSDestination(foreign.getJMSDestination());
setJMSDeliveryMode(foreign.getJMSDeliveryMode());
setJMSExpiration(foreign.getJMSExpiration());
setJMSPriority(foreign.getJMSPriority());
setJMSType(foreign.getJMSType());
for (Enumeration<String> props = foreign.getPropertyNames(); props.hasMoreElements(); ) {
String name = props.nextElement();
Object prop = foreign.getObjectProperty(name);
内容来源于网络,如有侵权,请联系作者删除!