《rabbitMQ学习》 十二 spring注解集成rabbitMQ

1.pom.xml


	4.0.0
	com.cloudtech.web
	climate
	war
	0.0.1-SNAPSHOT
	climate
	http://maven.apache.org

	
		climate
		
			
				maven-compiler-plugin
				3.6.1
				
					1.7
					1.7
					UTF-8
				
			
		
		
			
				src/main/java
				
					**/*.xml
					**/*.xlsx
				
			
			
				src/main/resources
				
					**/*.xml
					**/*.properties
				
			
		
	

	
		4.3.6.RELEASE
		2.3.3
		2.2.1
		5.1.30
		
		1.6.6
		1.2.12
		
		4.10
		
		3.2.8
		2.5
		3.3.2
		1.3.2
		3.3
		2.4.2
		4.3.5
		1.2
		2.5
		2.0
		1.2.3
		1.1.10

		1.6.6.RELEASE
	

	
	
		
			clojars.org
			http://clojars.org/repo
		
	

	
		
			org.apache.maven.plugins
			maven-war-plugin
			3.0.0
		
		
		
			junit
			junit
			
			4.12
		

		
		
			com.alibaba
			druid
			${druid.version}
		

		
		
			org.springframework
			spring-web
			${spring-version}
		
		
			org.springframework
			spring-oxm
			${spring-version}
		
		
			org.springframework
			spring-test
			${spring-version}
			test
			
				
					commons-logging
					commons-logging
				
			
		
		
			org.springframework
			spring-webmvc
			${spring-version}
		
		
			org.springframework
			spring-core
			${spring-version}
		

		
			org.springframework
			spring-context
			${spring-version}
		
		
			org.springframework
			spring-context-support
			${spring-version}
		
		
			org.springframework
			spring-aop
			${spring-version}
		
		
			org.springframework
			spring-beans
			${spring-version}
		
		
			org.springframework
			spring-tx
			${spring-version}
		
		
			org.springframework
			spring-jdbc
			${spring-version}
		
		
			org.springframework
			spring-orm
			${spring-version}
		

		
		
			mysql
			mysql-connector-java
			${mysql-version}
			runtime
		

		
		
			com.fasterxml.jackson.core
			jackson-core
			${jackson-version}
		
		
			com.fasterxml.jackson.core
			jackson-databind
			${jackson-version}
		
		
			com.fasterxml.jackson.core
			jackson-annotations
			${jackson-version}
		
		
		
			org.slf4j
			slf4j-api
			1.7.2
		
		
			org.slf4j
			jcl-over-slf4j
			1.7.2
		
		
			org.codehaus.janino
			commons-compiler
			2.6.1
		
		
			janino
			janino
			2.5.10
		
		
		
			org.quartz-scheduler
			quartz
			${quartz-version}
		
		
			org.quartz-scheduler
			quartz-jobs
			${quartz-version}
		
		
		
			org.aspectj
			aspectjweaver
			1.7.1
		

		
			javax.servlet
			servlet-api
			3.0-alpha-1
			provided
		
		
			org.apache.geronimo.specs
			geronimo-servlet_3.0_spec
			1.0
			test
		
		
			org.codehaus.jackson
			jackson-mapper-asl
			1.9.11
		
		
			jstl
			jstl
			1.2
		
		
			taglibs
			standard
			1.1.2
		

		
		
			org.mybatis
			mybatis
			3.2.7
		
		
			org.mybatis
			mybatis-spring
			1.2.2
		
		
			commons-dbcp
			commons-dbcp
			1.4
		
		
			commons-pool
			commons-pool
			1.5.4
		
		
			c3p0
			c3p0
			0.9.1.2
		

		
		
			org.apache.poi
			poi
			3.8
		
		
			org.apache.poi
			poi-ooxml
			3.8
		
		
			org.apache.poi
			poi-scratchpad
			3.8
		
		
			org.apache.poi
			poi-ooxml-schemas
			3.8
		
		
		
			com.corundumstudio.socketio
			netty-socketio
			1.6.0
		
		
			org.slf4j
			slf4j-simple
			1.7.2
		
		
			javax.mail
			mail
			1.4.7
		
		
		
			joda-time
			joda-time
			2.6
		

		
		
			commons-io
			commons-io
			2.4
		

		
		
			com.alibaba
			dubbo
			2.5.3
			
				
					spring
					org.springframework
				
			
		
		
			org.apache.zookeeper
			zookeeper
			3.4.6
		

		
			org.apache.curator
			curator-framework
			2.8.0
		
		
			org.apache.curator
			curator-recipes
			2.8.0
		

		
			com.101tec

			zkclient
			0.10
		

		
		
			org.apache.shiro
			shiro-core
			${shiro.version}
		
		
			org.apache.shiro
			shiro-web
			${shiro.version}
		
		
			org.apache.shiro
			shiro-cas
			${shiro.version}
		
		
			org.apache.shiro
			shiro-spring
			${shiro.version}
		

		
		
			tk.mybatis
			mapper
			3.1.0
		
		
		
			com.github.pagehelper
			pagehelper
			4.0.0
		

		
			commons-fileupload
			commons-fileupload
			1.3.1
		

		
		
			log4j
			log4j
			${log4j.version}
		
		
			org.slf4j
			slf4j-api
			${slf4j.version}
		
		
			org.slf4j
			slf4j-log4j12
			${slf4j.version}
		

		
		
			org.apache.commons
			commons-lang3
			${commons-lang3.version}
		
		
			org.apache.commons
			commons-io
			${commons-io.version}
		
		
			commons-net
			commons-net
			${commons-net.version}
		

		
		
			org.apache.httpcomponents
			httpclient
			${httpclient.version}
		

		
			com.alibaba
			fastjson
			1.2.7
		

		
		
		
			org.springframework
			spring-messaging
			4.3.6.RELEASE
		

		 
        
            org.springframework.amqp
            spring-rabbit
            2.0.1.RELEASE
        
        
        
            org.springframework.amqp
            spring-amqp
            2.0.1.RELEASE
        
		
		
        org.springframework.retry
        spring-retry
        1.2.2.RELEASE
    
	

2.web.xml



	parwa

	
	
		contextConfigLocation
		classpath*:/applicationContext.xml,classpath*:/applicationContext-shiro.xml,classpath*:/rabbitMQ.xml
	
	
	
		
		log4jRefreshInterval
		6000
	
	
	   
	
		characterEncodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
		
			forceEncoding
			true
		
	
	
	
		characterEncodingFilter
		/*
	
	
	  
 	
		shiroFilter
		org.springframework.web.filter.DelegatingFilterProxy
	
	
		shiroFilter
		/*
	 
	
	   
	
		org.springframework.web.context.ContextLoaderListener
	
	
	
		org.springframework.web.util.IntrospectorCleanupListener
	
	
	
		com.cloudtech.web.listener.StartupApplicationContextListener
	
	
	   
	
		springmvc
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath*:/applicationContext-mvc.xml
		
		1
	
	
		springmvc
		/
	
	
	  
	
		DruidWebStatFilter
		com.alibaba.druid.support.http.WebStatFilter
		
			exclusions
			*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
		
	
	
		DruidWebStatFilter
		/*
	
	
	  
	
		DruidStatView
		com.alibaba.druid.support.http.StatViewServlet
	
	
		DruidStatView
		/druid/* 
	
	
		60
	
	
		default
		*.html
		*.png
		*.js
		*.css
		*.gif
		*.jpg
		*.jpeg
		*.eot
		*.svg
		*.ttf
		*.woff
		*.woff2
		*.swf
		*.mp3
		*.xls
		*.xlsx
	
	
	
		/WEB-INF/jsp/login.jsp
		index.jsp
	



	
	
	 
	
	
	  
    

	
	
	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	

	
	
		
		
		
		
		
		
		
			
				
					
						
						
							mapper=tk.mybatis.mapper.common.Mapper
							dialect=mysql
							
							identity=mysql
							
							
							
							offsetAsPageNum=true
							
							
							rowBoundsWithCount=true
						
					
				
				
					
						
						
							mappers=tk.mybatis.mapper.common.Mapper
							identity=mysql
						
					
				
			
		
	

	
	

	
	
		
		
	

	
	
		
	

	
	
	

	
	
	

	
	
	
	 




	
	
	
	
		
	
	

	

	  
      
          
        
    

	
	  
	       
	      
	       
	

	
	
	
       
             
                 
                 
             
        
	

	
	
		
	

5.配置代码

package com.cloudtech.web.mq.config;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;

/**
 * 抽象类,rabbitMQ的主配置类
 * 
 * @author xdx
 *
 */
public abstract class AbstractRabbitConfiguration {

    private int port = 5672;

    protected abstract void configureRabbitTemplate(RabbitTemplate template);

    /**
     * 由于connectionFactory会与项目中的redis的connectionFactory命名冲突,
     * 所以这边改名为rabbit_connectionFactory
     * 
     * @return
     */
    @Bean
    public ConnectionFactory rabbit_connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
                "192.168.1.198");
        connectionFactory.setUsername("test");
        connectionFactory.setPassword("test");
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost("/test");
        return connectionFactory;
    }
    
    

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(rabbit_connectionFactory());
        template.setMessageConverter(jsonMessageConverter());
        configureRabbitTemplate(template);
        return template;
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpAdmin amqpAdmin() {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbit_connectionFactory());
        return rabbitAdmin;
    }
}
package com.cloudtech.web.mq.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.cloudtech.web.service.impl.LogRabbitRecHandler;

/**
 * 日志管理的Rabbit配置类的具体实现类
 * 
 * @author xdx
 *
 */
@Configuration
public class LogRabbitConfiguration extends AbstractRabbitConfiguration {
    protected static String LOG_EXCHANGE_NAME = "warrior.exchange.log";// topic
                                                                        // exchange的名称
    protected static String LOG_QUEUE_NAME = "warrior.queue.log";// 接收消息的queue
    protected static String LOG_ROUTING_KEY = LOG_QUEUE_NAME;
    @Autowired
    private LogRabbitRecHandler logRabbitRecHandler;// 监听器的委托类,委托其处理接收到的消息

    /**
     * 设置Exchange为LOG_EXCHANGE_NAME,RoutingKey为LOG_ROUTING_KEY,这样将信息发送到
     * Exchange为LOG_EXCHANGE_NAME,RouteKey为LOG_ROUTING_KEY的通道中
     */
    @Override
    protected void configureRabbitTemplate(RabbitTemplate template) {
        System.err.println("创建一个RabbitTemplate,名字是 " + template);
        template.setExchange(LOG_EXCHANGE_NAME);
        template.setRoutingKey(LOG_ROUTING_KEY);
    }

    /**
     * 用于接收日志消息的Queue,默认绑定自己的名称
     * 
     * @return
     */
    @Bean
    public Queue logQueue() {
        return new Queue(LOG_QUEUE_NAME);
    }

    /**
     * 定义一个topExchange
     * 
     * @return
     */
    @Bean
    public TopicExchange logExchange() {
        return new TopicExchange(LOG_EXCHANGE_NAME);
    }

    /**
     * 定义一个绑定日志接收的Queue的binding
     * 
     * @return
     */
    @Bean
    public Binding logQueueBinding() {
        return BindingBuilder.bind(logQueue()).to(logExchange())
                .with(LOG_ROUTING_KEY);
    }

    /**
     * 这个bean为监听适配器,用于日志消息,并交由logRabbitRecHandler处理
     * 
     * @return
     */
    @Bean
    public MessageListenerAdapter messageListenerAdapter() {
        return new MessageListenerAdapter(logRabbitRecHandler,
                jsonMessageConverter());
    }

    /**
     * 这个bean用于监听服务端发过来的消息,监听的Queue为logQueue(),
     * 因为该Queue绑定了logExchange和logRouteKey, 所以它可以接收到我们发送的日志消息
     * @return
     */
    @Bean
    public SimpleMessageListenerContainer messageListenerContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
                rabbit_connectionFactory());
        container.setConcurrentConsumers(5);   //设置并发数,对业务数据顺序有要求,不需要设置
        container.setQueues(logQueue());
        container.setMessageListener(messageListenerAdapter());
        container.setAcknowledgeMode(AcknowledgeMode.AUTO);
        return container;
    }
}
package com.cloudtech.web.mq.po;

import java.util.Date;

public class TLog {
    private Integer logId;

    private String operator;

    private String event;

    private Date createTime;

    private Integer isDel;

    public TLog(String operator, String event) {
        this.operator = operator;
        this.event = event;
    }

    public TLog() {
    }

    public Integer getLogId() {
        return logId;
    }

    public void setLogId(Integer logId) {
        this.logId = logId;
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator == null ? null : operator.trim();
    }

    public String getEvent() {
        return event;
    }

    public void setEvent(String event) {
        this.event = event == null ? null : event.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Integer getIsDel() {
        return isDel;
    }

    public void setIsDel(Integer isDel) {
        this.isDel = isDel;
    }

	@Override
	public String toString() {
		return "TLog [logId=" + logId + ", operator=" + operator + ", event=" + event + ", createTime=" + createTime
				+ ", isDel=" + isDel + "]";
	}
}
package com.cloudtech.web.service;

/**
 * 用于处理监听到的消息的消息处理器接口,T为接收到的消息的类型
 * 
 * @author xdx
 *
 * @param 
 */
public interface RabbitRecHandler {
    void handleMessage(T t);
} 
package com.cloudtech.web.service;
/**
 * 定义一个泛型接口,用于发送消息,T为要发送的消息类型
 * @author xdx
 *
 * @param 
 */
public interface RabbitSend {
    void send(T t);
}
package com.cloudtech.web.service.impl;

import org.springframework.stereotype.Component;
import com.cloudtech.web.mq.po.TLog;
import com.cloudtech.web.service.RabbitRecHandler;
@Component("logRabbitRecHandler")
public class LogRabbitRecHandler implements RabbitRecHandler {
    
    @Override
    public void handleMessage(TLog log) {
        System.err.println("开始存储日志:"+log.toString());
    }
}
package com.cloudtech.web.service.impl;

import javax.annotation.Resource;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import com.cloudtech.web.mq.po.TLog;
import com.cloudtech.web.service.RabbitSend;

/**
 * 用于发送日志消息的通用实现类
 * 
 * @author xdx
 *
 */
@Component("logRabbitSend")
public class LogRabbitSend implements RabbitSend {
	 @Resource(name = "rabbitTemplate")
	 private RabbitTemplate rabbitTemplate;

    @Override
    public void send(TLog log) {
    	System.err.println("发送消息:" + log.toString());
        rabbitTemplate.convertAndSend(log);
    }
}
package com.cloudtech.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudtech.web.mq.po.TLog;
import com.cloudtech.web.service.impl.LogRabbitSend;

@Controller
@RequestMapping("rabbit")
public class RabbitMQController {
	
	
	@Autowired
	private LogRabbitSend logRabbitSend;
	
	
	@RequestMapping(value="/produce",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public void produce(@ModelAttribute("log") TLog log) throws Exception{
		logRabbitSend.send(log);
	}
	
	@RequestMapping("demo")
	public String demo(){
		return "demo";
	}
	
	
}

 

你可能感兴趣的:(#,rabbitMQ消息中间件)