spring amqp rabbitmq 学习(一) 发送消息

关于amqp的一些概念请参照http://wubin850219.iteye.com/category/152656 

 

使用到的工具 Myeclipse、Maven

maven配置如下:

<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>io.github.itanxi</groupId>
	<artifactId>itanxi-amqp</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringAmqpDemo</name>
	<description />
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.amqp</groupId>
			<artifactId>spring-rabbit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>io.spring.platform</groupId>
				<artifactId>platform-bom</artifactId>
				<version>1.1.0.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<build>
		<resources>
			<resource>
				<directory>src/test/resources</directory>
				<excludes>
					<exclude>**/*</exclude>
				</excludes>
			</resource>
			<resource>
				<directory>src/test/java</directory>
				<excludes>
					<exclude>**/*</exclude>
				</excludes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*</include>
				</includes>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<version>3.0</version>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

 

新建一个web项目,web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 <display-name>SpringAmqpDemo</display-name>

 <context-param>
  <param-name>webAppRootKey</param-name>
  <param-value>itanxi.amqp</param-value>
 </context-param>

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:applicationContext*.xml</param-value>
 </context-param>

 <context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>classpath:log4j.properties</param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
 </listener>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <filter>
  <filter-name>SetCharacterEncoding</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
  <async-supported>true</async-supported>
 </filter>
 <filter-mapping>
  <filter-name>SetCharacterEncoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.jpg</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.jpeg</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.png</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.gif</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.bmp</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.js</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.swf</url-pattern>
 </servlet-mapping>

 <servlet>
  <servlet-name>springMVC</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath*:springMVC.xml </param-value>
  </init-param>
  <async-supported>true</async-supported>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>springMVC</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

 <session-config>
  <session-timeout>60</session-timeout>
 </session-config>
</web-app>

  

applicationContext-send-simple-direct.xml的配置如下,这个主要是用来发送信息的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xsi:schemaLocation="http://www.springframework.org/schema/beans    
      http://www.springframework.org/schema/beans/spring-beans.xsd   
      http://www.springframework.org/schema/context   
      http://www.springframework.org/schema/context/spring-context.xsd   
      http://www.springframework.org/schema/aop   
      http://www.springframework.org/schema/aop/spring-aop.xsd   
      http://www.springframework.org/schema/tx   
      http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/mvc  
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/rabbit
	  http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd">

	<!-- 端口号默认是5672,可以不写,但是记得打开防火墙端口 -->
	<rabbit:connection-factory id="connectionFactory" host="192.168.1.175" port="5672" channel-cache-size="25" />

	<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" routing-key="simpleSend"/>

	<rabbit:admin connection-factory="connectionFactory" />
	
	<rabbit:queue name="simpleSend"/>

	<!-- 
	<rabbit:listener-container connection-factory="connectionFactory">
		<rabbit:listener ref="foo" method="listen" queue-names="myQueue" />
	</rabbit:listener-container>

	<bean id="foo" class="io.github.itnaxi.amqp.Foo" />
	 -->

</beans>

  rabbitmq发送信息需要exchange 和routing-key根据这两个决定发送到哪个队列上,当exchange为空时,rabbitmq默认使用direct exchange将消息发送到名称为routing-key的队列上;

  这里是将消息发送到队列名为simpleSend的队列上,先从最简单的来,后续跟进

 

接下来使用junit测试

先定义一个SpringJUnit4Log4jClassRunner类,这个主要是在junit测试用使用自己的log4j配置文件

import java.io.FileNotFoundException;

import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;

public class SpringJUnit4Log4jClassRunner extends SpringJUnit4ClassRunner {  
  
    static {  
        try {  
            Log4jConfigurer.initLogging("classpath:log4j.properties");  
        } catch (FileNotFoundException ex) {  
            System.err.println("Cannot Initialize log4j");  
        }  
    }  
      
    public SpringJUnit4Log4jClassRunner(Class<?> clazz) throws InitializationError {  
        super(clazz);  
    }  
  
} 

 

 

然后是AbstractConfig

import org.junit.runner.RunWith;

@RunWith(SpringJUnit4Log4jClassRunner.class)
public abstract class AbstractConfig {

}

 

最后开始写

import io.github.itnaxi.amqp.AbstractConfig;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations={"/springMVC.xml","/applicationContext-send-simple-direct.xml"})
public class HomeControllerSendTest extends AbstractConfig{
 
 private final Logger log=Logger.getLogger(HomeControllerSendTest.class);
 
 @Resource
 private RabbitTemplate rabbitTemplate;
 
 @Test
 public void testSend() throws InterruptedException {
  
  MessageProperties props = MessagePropertiesBuilder.newInstance().setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN).setMessageId("123").setHeader("bar", "baz").build();
  Message message = MessageBuilder.withBody("foo".getBytes()).andProperties(props).build();
  
  //Message message = MessageBuilder.withBody("helloword".getBytes()).build();
  rabbitTemplate.send(message);
  log.info("send foo");
 }

}

  

执行testSend,可以看到打印结果如下:

send foo

 

然后登录rabbitmq的图形管理界面可以看到

 
spring amqp rabbitmq 学习(一) 发送消息_第1张图片
 表示发送成功

 

 

你可能感兴趣的:(spring,rabbitmq,AMQP)