rabbitmq spring

 

 

demo 下载 :http://download.csdn.net/download/knight_black_bob/9544857

 

 



 

 

 

 

applicationContext-rabbit-consumer.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:context="http://www.springframework.org/schema/context"
	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/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">

	<context:property-placeholder location="classpath:rabbitmq.properties" />

	<rabbit:connection-factory  id="connectionFactory"
		host="${rabbit.host}" 
		username="${rabbit.username}" 
		password="${rabbit.password}" />
		
	<bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">
		<constructor-arg ref="connectionFactory" />
	</bean>

	<rabbit:admin connection-factory="connectionFactory" />
	<rabbit:queue id="cqueue"  name="${rabbit.queue.name}"   durable="true" auto-delete="false" exclusive="false" />

	<rabbit:direct-exchange id="cmq-exchange" durable="true"
		auto-delete="false" name="${rabbit.exchange.name}">
		<rabbit:bindings>
			<rabbit:binding queue="cqueue" key="cqueue-key"></rabbit:binding>
		</rabbit:bindings>
	</rabbit:direct-exchange>

	<bean id="listener" class="com.curiousby.core.MessageProcessListener" />
	
	<rabbit:listener-container id="listenerContainer" connection-factory="connectionFactory" >
		<rabbit:listener ref="listener" queues="cqueue" />
	</rabbit:listener-container>
  
	
</beans>

 

applicationContext-rabbit-producer.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:context="http://www.springframework.org/schema/context"
	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/rabbit
                http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">

	<context:property-placeholder location="classpath:rabbitmq.properties" />

	<rabbit:connection-factory id="connectionFactory"
		host="${rabbit.host}"
		username="${rabbit.username}" 
		password="${rabbit.password}" />

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

	<rabbit:queue id="pqueue"  name="${rabbit.queue.name}" />
	 
	<rabbit:direct-exchange id="pmq-exchange" durable="true" auto-delete="false" name="pmq-exchange">
		<rabbit:bindings>
			<rabbit:binding queue="pqueue" key="pqueuekey" />
		</rabbit:bindings>
	</rabbit:direct-exchange>

	<bean id="jsonMessageConverter"
		class="com.curiousby.util.FastJsonMessageConverter"></bean>
	  
	  
	  <rabbit:template 
	        exchange="pmq-exchange" 
	  		id="amqpTemplate"  
	  		connection-factory="connectionFactory"  
	 		message-converter="jsonMessageConverter"/>

</beans>

 

applicationContext.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:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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/tool http://www.springframework.org/schema/tool/spring-tool.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
	default-autowire="byName"> 
     
    <context:annotation-config />
	<aop:aspectj-autoproxy /> 
	
	<context:property-placeholder location="classpath:rabbitmq.properties" />

	<context:component-scan base-package="com.curiousby" /> 
	
</beans>

 

package com.curiousby.entity;

public class Message {

	public String msgId;
	public String content;
	public String from;
	public String to;
	public String isValid;
	public String insertTime;
	public String lastUpdateTime;

	
	public Message (){}
	public Message(String msgId, String content, String from, String to, String isValid, String insertTime,
			String lastUpdateTime) { 
		this.msgId = msgId;
		this.content = content;
		this.from = from;
		this.to = to;
		this.isValid = isValid;
		this.insertTime = insertTime;
		this.lastUpdateTime = lastUpdateTime;
	}

	public String getMsgId() {
		return msgId;
	}

	public String getContent() {
		return content;
	}

	public String getFrom() {
		return from;
	}

	public String getTo() {
		return to;
	}

	public String getIsValid() {
		return isValid;
	}

	public String getInsertTime() {
		return insertTime;
	}

	public String getLastUpdateTime() {
		return lastUpdateTime;
	}

	public Message setMsgId(String msgId) {
		this.msgId = msgId;
		return this;
	}

	public Message setContent(String content) {
		this.content = content;
		return this;
	}

	public Message setFrom(String from) {
		this.from = from;
		return this;
	}

	public Message setTo(String to) {
		this.to = to;
		return this;
	}

	public Message setIsValid(String isValid) {
		this.isValid = isValid;
		return this;
	}

	public Message setInsertTime(String insertTime) {
		this.insertTime = insertTime;
		return this;
	}

	public Message setLastUpdateTime(String lastUpdateTime) {
		this.lastUpdateTime = lastUpdateTime;
		return this;
	}

	@Override
	public String toString() {
		return "Message [msgId=" + msgId + ", content=" + content + ", from=" + from + ", to=" + to + ", isValid="
				+ isValid + ", insertTime=" + insertTime + ", lastUpdateTime=" + lastUpdateTime + "]";
	}

	
	
}

 

package com.curiousby.core;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonAnyFormatVisitor;
//com.curiousby.core.MessageProcessListener
public class MessageProcessListener implements MessageListener{

	@Override
	public void onMessage(Message message) { 
		process(message);
	}

	private void  process(Message message){
		if (message != null) {
			byte[] msg = message.getBody();
			System.out.println("===============" + msg.toString());
		}
	}
	
}

 

 

package com.curiousby.core;

import javax.annotation.Resource;

import org.springframework.amqp.core.AmqpTemplate; 
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Repository
public class MessagePush {

	@Resource
	private AmqpTemplate amqpTemplate;
	 
	public void convertAndSend(Object obj) {
	     amqpTemplate.convertAndSend("pqueuekey", obj);
	}	
	 
}

 

 

package com.curiousby.util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import com.alibaba.fastjson.JSON; 
//import fe.json.FastJson;



//com.curiousby.util.FastJsonMessageConverter
public class FastJsonMessageConverter  extends AbstractMessageConverter {
    private static Log log = LogFactory.getLog(FastJsonMessageConverter.class);

    public static final String DEFAULT_CHARSET = "UTF-8";

    private volatile String defaultCharset = DEFAULT_CHARSET;
    
    public FastJsonMessageConverter() {
        super(); 
    }
    
    public void setDefaultCharset(String defaultCharset) {
        this.defaultCharset = (defaultCharset != null) ? defaultCharset
                : DEFAULT_CHARSET;
    }
    
    public Object fromMessage(Message message)
            throws MessageConversionException {
        return null;
    }
    
    public <T> T fromMessage(Message message,T t) {
        String json = "";
        try {
            json = new String(message.getBody(),defaultCharset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return   (T) JSON.parseObject(json, t.getClass());
        		//(T) FastJson.fromJson(json, t.getClass());
    }	
    

    protected Message createMessage(Object objectToConvert,
            MessageProperties messageProperties)
            throws MessageConversionException {
        byte[] bytes = null;
        try {
            String jsonString = JSON.toJSONString(objectToConvert);
            		//FastJson.toJson(objectToConvert);
            bytes = jsonString.getBytes(this.defaultCharset);
        } catch (UnsupportedEncodingException e) {
            throw new MessageConversionException(
                    "Failed to convert Message content", e);
        } 
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        messageProperties.setContentEncoding(this.defaultCharset);
        if (bytes != null) {
            messageProperties.setContentLength(bytes.length);
        }
        return new Message(bytes, messageProperties);

    }
}

 

 

package com.curiousby;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.curiousby.core.MessagePush;

@Component
@RunWith(SpringJUnit4ClassRunner.class)   
@ContextConfiguration(locations = {"classpath*:applicationContext*.xml"}) 
public class MainStart {

 
	@Autowired
	MessagePush messagePush;
	
	@Test
	public  void testMain() throws InterruptedException{ 
			Thread.sleep(100000000);
	}
}

 

package com.curiousby;

import java.util.UUID;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.curiousby.core.MessagePush;
import com.curiousby.entity.Message;

@Component
@RunWith(SpringJUnit4ClassRunner.class)   
@ContextConfiguration(locations = {"classpath*:applicationContext*.xml"}) 
public class TestProducter {

	@Autowired
	MessagePush messagePush;
	
	@Test
	public  void testMain() throws InterruptedException{ 
		Thread.sleep(10000);
		Message m = new Message();
		m.setContent("baoyou")
		 .setMsgId(UUID.randomUUID().toString().replaceAll("-", ""))
		 .setFrom("1")
		 .setTo("2");
		messagePush.convertAndSend(m);
	}
}

 

 

 

 

 

 

 

 

 

 

 

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