Spring集成RabbitMQ测试通过Demo(一) XML配置

本文借鉴了其他博文,权当自己总结使用,如有侵权,请告知!

一、引入相关的包

<dependency>
			<groupId>com.rabbitmq</groupId>
			<artifactId>amqp-client</artifactId>
			<version>5.2.0</version>
		</dependency>
		<dependency>
		    <groupId>org.springframework.amqp</groupId>
		    <artifactId>spring-rabbit</artifactId>
    		<version>2.0.2.RELEASE</version>
		</dependency>

二、spring-mybatis.xml里面包含了RabbitMQ配置

<?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:p="http://www.springframework.org/schema/p"
	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/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.7.xsd">
	<!-- 自动扫描 -->
	<context:component-scan base-package="com.smtv" />
	<!-- 引入配置文件 -->
	<!-- <bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean> -->
	<!-- 引入配置文件 -->
	<bean id="propertyConsfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
				<value>classpath:rabbitmq.properties</value>
			</list>
		</property>
	</bean>
	
	<!--简化方式  -->  
    <!-- <context:property-placeholder location="classpath:jdbc.properties"/> -->

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 初始化连接大小 -->
		<property name="initialSize" value="${initialSize}"></property>
		<!-- 连接池最大数量 -->
		<property name="maxActive" value="${maxActive}"></property>
		<!-- 连接池最大空闲 -->
		<property name="maxIdle" value="${maxIdle}"></property>
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="${minIdle}"></property>
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="${maxWait}"></property>
		<!-- 保持连接,自动连接,防止连接丢失  -->
		<property name="validationQuery" value="SELECT 1" />
    	<property name="testOnBorrow" value="true"/>
	</bean>

	<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
	<!-- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		自动扫描mapping.xml文件
		<property name="mapperLocations" value="classpath:*/*/*.xml"></property>
	</bean> -->

	<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.xx.xxx.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

	<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 开启事务注解 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	
	<!-- rabbitMQ配置  BEGIN-->
    <bean id="rabbitConnectionFactory"
      class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
        <constructor-arg value="${rabbit.hosts}"/>
        <property name="username" value="${rabbit.username}"/>
        <property name="password" value="${rabbit.password}"/>
        <property name="channelCacheSize" value="${rabbit.channelCacheSize}"/>
        <property name="port" value="${rabbit.port}"></property>
        <property name="virtualHost" value="${rabbit.virtualHost}"></property>
    </bean>
    <rabbit:admin connection-factory="rabbitConnectionFactory"/>
	
	<!-- autoDelete:是否自动删除 durable:持久化  -->
    <rabbit:queue name="test_liam_queue" durable="true"/>
    <rabbit:queue name="${rabbit.queue}" durable="true"/>
	<!-- topic主题 -->
    <rabbit:topic-exchange name="test.liam.topic.exchange" xmlns="http://www.springframework.org/schema/rabbit" durable="true">
      <bindings>
        <binding queue="test_liam_queue" pattern="*.liam.queue" />
      </bindings>
    </rabbit:topic-exchange>
    <!-- 绑定交换机和队列 -->
    <rabbit:direct-exchange name="${rabbit.exchange}" xmlns="http://www.springframework.org/schema/rabbit" durable="true" >
	    <rabbit:bindings>
	        <rabbit:binding queue="${rabbit.queue}" key="${rabbit.routingKey}" />
	    </rabbit:bindings>
	</rabbit:direct-exchange>

    <!-- 创建rabbitTemplate 消息模板类 -->
    <bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">
        <constructor-arg ref="rabbitConnectionFactory"></constructor-arg>
        <!--消息确认回调 -->    
        <property name="confirmCallback" ref="producer"/>
    </bean>
      
      <bean name="queueListenter" class="com.smtv.rabbitmq.QueueListenter"></bean>  
      <bean name="producer" class="com.smtv.rabbitmq.RmqProducer"></bean>  
        
      <bean id="messageContainer" class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer">  
        <property name="queues" ref="${rabbit.queue}"></property>  
        <property name="exposeListenerChannel" value="true"></property>  
        <property name="maxConcurrentConsumers" value="10"></property>  
        <property name="concurrentConsumers" value="2"></property>  
        <property name="connectionFactory" ref="rabbitConnectionFactory"></property>  
        <property name="acknowledgeMode" value="MANUAL"></property>  
        <property name="messageListener" ref="queueListenter"></property>  
      </bean>  
	<!-- rabbitMQ配置  END-->
	
	

</beans>

三、生产者和消费者在同一项目中

  1. 生产者代码
    import java.util.UUID;  
    
    import org.springframework.amqp.rabbit.connection.ConnectionFactory;  
    import org.springframework.amqp.rabbit.core.RabbitTemplate;  
    import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;  
    import org.springframework.amqp.rabbit.support.CorrelationData;  
    import org.springframework.beans.factory.annotation.Autowired;  
      
    public class RmqProducer implements ConfirmCallback{  
      
    	@Autowired
        private RabbitTemplate rabbitTemplate;  
      
        public void sendMessage(String content) {  
            try {  
            	System.out.println(rabbitTemplate.getConnectionFactory().getHost());
            	System.out.println(rabbitTemplate.getConnectionFactory().getPort());
            	String id = UUID.randomUUID().toString();
                CorrelationData correlationId = new CorrelationData(id);  
                rabbitTemplate.convertAndSend("rabbit_driect_mq_exchange", "rabbitmq_test2",content,correlationId);  
                System.out.println("消息发送成功!" + id);
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
    
    	@Override
    	public void confirm(CorrelationData arg0, boolean arg1, String arg2) {
    		// TODO Auto-generated method stub
    		System.out.println(" 回调id:" + arg0+"ack:"+arg1+",  "+arg2);   
    	}  
    }  

  2. 消费者代码
    import java.io.UnsupportedEncodingException;
    
    import org.springframework.amqp.core.Message;
    import org.springframework.amqp.core.MessageListener;  
      
    public class QueueListenter implements MessageListener{  
    
    	@Override
    	public void onMessage(Message paramMessage) {
    		/*byte[] body = paramMessage.getBody();  
            System.out.println("receive msg : " + new String(body)); */   
            try {
    			System.out.print("receive msg: "+new String(paramMessage.getBody(),"UTF-8"));
    		} catch (UnsupportedEncodingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}  
      
    } 
  3. Junit测试代码
    import javax.annotation.Resource;
    
    import org.apache.log4j.Logger;
    import org.apache.shiro.cache.CacheManager;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.smtv.rabbitmq.RmqProducer;
    
    @RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类
    @ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
    public class TestMybatis {
    	private static Logger logger = Logger.getLogger(TestMybatis.class);
    	// private ApplicationContext ac = null;
    
    	// @Before
    	// public void before() {
    	// ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    	// userService = (IUserService) ac.getBean("userService");
    	// }
    
    	/**
    	 * 测试mybatis和spring无缝连接
    	 */
    	@Resource(name="producer")  
        private RmqProducer producer;
    	
    	@Test
    	public void test(){  
            try {  
            	System.out.println("发送消息!");
                //发送消息    
                producer.sendMessage("test");  
                System.out.println("结束发送消息!");
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        } 
    
    		
    }
  4. 运行结果




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Liam1994/article/details/80697371
文章标签: RabbitMQ Spring
个人分类: Java
想对作者说点什么? 我来说一句

SpringMvc rabbitMQ Demo

2016年12月07日 72KB 下载

rabbitmq spring demo

2016年06月08日 40KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭