JMSとは?

Glassfish (MQ) の設定

JMS の利用方法

JavaSE からの利用用法

JMS通信の手順を全部自分で書かなければいけない うげぇ。特に必要なければ JavaEE 使おう

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>JMSExam</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.glassfish.main.appclient</groupId>
            <artifactId>gf-client</artifactId>
            <version>4.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.mq</groupId>
            <artifactId>imqjmsra</artifactId>
            <version>5.1</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>

Sender.java

package com.mycompany.jmsexam;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Sender {

    public static void main(String[] args) {
        try {
            Properties props = new Properties();
            props.setProperty("java.naming.factory.initial",
                    "com.sun.enterprise.naming.SerialInitContextFactory");
            props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");//your server ip
            props.setProperty("org.omg.CORBA.ORBInitialPort", "3700"); //default is 3700
            Context jndiContext = new InitialContext(props);

            // (1)
            ConnectionFactory factory = (ConnectionFactory) jndiContext.lookup("jms/myQueueFactory");
            // (2)
            Queue queue = (Queue) jndiContext.lookup("jms/myQueue");
            // (3)
            try (Connection connection = factory.createConnection()) {
                 // (4)
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                // (5)
                TextMessage message = session.createTextMessage();
                message.setText("Hello JMS World");
                // (6)
                MessageProducer producer = session.createProducer(queue);
                // (7)
                producer.send(message);
                connection.close();
            }
        } catch (NamingException | JMSException ex) {
            Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Receiver.java

package com.mycompany.jmsexam;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Receiver {

    public static void main(String[] args) {
        try {
            Properties props = new Properties();
            props.setProperty("java.naming.factory.initial",
                    "com.sun.enterprise.naming.SerialInitContextFactory");
            props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");//your server ip
            props.setProperty("org.omg.CORBA.ORBInitialPort", "3700"); //default is 3700
            Context jndiContext = new InitialContext(props);

            // (1)
            ConnectionFactory factory = (ConnectionFactory) jndiContext.lookup("jms/myQueueFactory");
            // (2)
            Queue queue = (Queue) jndiContext.lookup("jms/myQueue");
            // (3)
            try (Connection connection = factory.createConnection()) {
                // (4)
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                // (5)
                MessageConsumer consumer = session.createConsumer(queue);
                // (6)
                connection.start();
                TextMessage message = (TextMessage) consumer.receive(5000L);\
                connection.close();
                System.out.println(message);
            }
        } catch (NamingException | JMSException ex) {
            Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

実行結果

JavaEE からの利用方法

Sender (Session Bean) は Queue を Inject するだけ やったー
Receiver (Message Driven Bean) では、ユーザプログラムがメッセージを待つ必要がない。JavaEE コンテナが、メッセージが届いたら MDB#onMessage() を呼んでくれる。

Sender (Session Bean)

https://github.com/kagyuu/WebSocketExam/blob/master/src/main/java/com/mycompany/websocketexam/QueueSenderSessionBean.java

package com.mycompany.websocketexam;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jms.JMSContext;
import javax.jms.Queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@LocalBean
@Stateless
public class QueueSenderSessionBean {

    private static final Logger logger 
            = LoggerFactory.getLogger(QueueSenderSessionBean.class);

    @Resource(mappedName = "jms/myQueue")    
    private Queue myQueue;

    @Inject
    private JMSContext jmsContext;

    public void sendMessage(String message) {
        logger.info("Enqueu Message to JMS");        
        jmsContext.createProducer().send(myQueue, message);
    }

}

Receiver (Message Driven Bean)

https://github.com/kagyuu/WebSocketExam/blob/master/src/main/java/com/mycompany/websocketexam/WebSocketMDB.java

package com.mycompany.websocketexam;

import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@MessageDriven(mappedName = "jms/myQueue")
public class WebSocketMDB implements MessageListener {
    
    private static final Logger logger 
            = LoggerFactory.getLogger(WebSocketMDB.class);

    @Inject
    @WSJMSMessage
    private Event<Message> jmsEvent;

    @Override
    public void onMessage(Message msg) {
        logger.info("Fire CDI Event");
        jmsEvent.fire(msg);
    }
}

Topic の場合

Message

トランザクション


Java#Glassfish


添付ファイル: filejms-5.png 2113件 [詳細] filejms-4.png 2142件 [詳細] filejms-3.png 2032件 [詳細] filejms-2.png 1988件 [詳細] filejms-1.png 2102件 [詳細] filejms-0.png 2216件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2015-09-29 (火) 02:12:52 (3355d)
Short-URL:
ISBN10
ISBN13
9784061426061