3.2. Hello World の実行
Hello World の例では、ブローカーへの接続を作成し、グリーティングが含まれるメッセージを example キューに送信し、それを受け取ります。成功すると、受け取ったメッセージをコンソールに出力します。
例: "Hello World!" の送受信 (HelloWorld.java)
package net.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
@EnableJms
@SpringBootApplication
public class HelloWorld implements CommandLineRunner {
@Autowired
private JmsTemplate jmsTemplate;
public static void main(String[] args) {
SpringApplication.run(HelloWorld.class, args);
}
@Override
public void run(String... strings) throws Exception {
sendMessage("Hello World!");
}
public void sendMessage(String text) {
System.out.println(String.format("Sending '%s'", text));
this.jmsTemplate.convertAndSend("example", text);
}
@JmsListener(destination = "example")
public void receiveMessage(String text) {
System.out.println(String.format("Received '%s'", text));
}
}
サンプルの実行
サンプルプログラムをコンパイルして実行するには、次の手順を使用します。
手順
-
新しいプロジェクトディレクトリーを作成します。これは、以降の手順で
<project-dir>と呼ばれます。 サンプル一覧を以下の場所にコピーします。
<project-dir>/src/main/java/net/example/HelloWorld.javaテキストエディターを使用して、新しい
<project-dir>/pom.xmlファイルを作成します。以下の XML を追加します。<project> <modelVersion>4.0.0</modelVersion> <groupId>net.example</groupId> <artifactId>example</artifactId> <version>1.0.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.0</version> </parent> <dependencies> <dependency> <groupId>org.amqphub.spring</groupId> <artifactId>amqp-10-jms-spring-boot-starter</artifactId> <version>2.5.0.redhat-00001</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>プロジェクトディレクトリーに移動し、
mvnコマンドを使用してプログラムをコンパイルします。$ mvn clean packagejavaコマンドを使用してプログラムを実行します。$ java -jar target/example-1.0.0-SNAPSHOT.jarHello World の例を実行すると、以下のコンソール出力が表示されます。
$ java -jar target/example-1.0.0-SNAPSHOT.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.5.RELEASE) [...] 2018-11-05 16:21:09.849 INFO 14805 --- [main] net.example.HelloWorld: Started HelloWorld in 1.074 seconds (JVM running for 1.38) Sending 'Hello World!' Received 'Hello World!'