在%JBOSS_HOME%\server\default\deploy\hornetq\hornetq-jms.xml中配置JMS 目标地址 如
<topic name="topic1">
<entry name="/topic/topic1"/>
</topic>
发送消息
- public class TopicMsg extends Properties{
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public TopicMsg(){
- InputStream in = Class.class.getResourceAsStream("jndi.properties");
- try {
- load(in);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- TopicSession tSession = null ; // session实例
- TopicConnection tConnection = null;// 连接实例
- Destination tDes = null;// 目标地址
- MessageProducer tProducer = null;//发布消息对象
- MapMessage mapMessage = null ;//消息的类型
- try {
- InitialContext context = new InitialContext();
- TopicConnectionFactory fFactory = (TopicConnectionFactory)context.lookup("ConnectionFactory");
- tConnection = fFactory.createTopicConnection();
- // 第一个参数 是否在事物中 第二个参数 : 自动回复状态,已经收到消息
- tSession = tConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
- tDes = (Destination)context.lookup("/topic/topic1");
- tProducer = tSession.createProducer(tDes);// 发布消息参数是发布的目标地址
- mapMessage = tSession.createMapMessage();
- mapMessage.setStringProperty("key1", "value1");
- mapMessage.setStringProperty("key2", "value2");
- tProducer.send(mapMessage);
- System.out.println("Topic 消息发送成功!");
- } catch (NamingException e) {
- e.printStackTrace();
- } catch (JMSException ex){
- ex.printStackTrace();
- } finally{
- try{
- tSession.close();
- tConnection.close();
- }catch(JMSException jmsE){
- jmsE.printStackTrace();
- }
- }
- }
- 订阅者
- /**
- * 主题与订阅的消息
- *
- * @author liujx
- *
- */
- @MessageDriven(activationConfig = {
- @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),// 指定消息类别
- @ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/topic1") })// 指定目标地址
- public class TopicMsg implements MessageListener {
- public void onMessage(Message arg0) {
- if(arg0 instanceof MapMessage){
- try {
- System.out.println("TopicMsg01 key1 = "+arg0.getStringProperty("key1"));
- System.out.println("TopicMsg01 key2 = "+arg0.getStringProperty("key2"));
- } catch (JMSException e) {
- e.printStackTrace();
- }
- }
- }
- }
这样一个简单jms就完成了。
