Spring integrates message queue rabbitmq

https://my.oschina.net/never/blog/140368

spring is too familiar to everyone, so I won't talk about

rabbitmq, an amqp queue service implementation. For details, please refer to this article http://lynnkong.iteye.com/blog/ 1699684

This article focuses on how to integrate rabbitmq into the project

ps: This article is just a simple integration introduction, which belongs to the introduction, and the specific implementation still needs to be studied in depth.




1. The first is the producer configuration

<?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">

   
   <!-- 连接服务配置  -->
   <rabbit:connection-factory id="connectionFactory" host="localhost" username="guest"
        password="guest" port="5672"  />
       
   <rabbit:admin connection-factory="connectionFactory"/>
  
   <!-- queue 队列声明-->
   <rabbit:queue id="queue_one" durable="true" auto-delete="false" exclusive="false" name="queue_one"/>
  
  
   <!-- exchange queue binging key 绑定 -->
    <rabbit:direct-exchange name="my-mq-exchange" durable="true" auto-delete="false" id="my-mq-exchange">
        <rabbit:bindings>
            <rabbit:binding queue="queue_one " key="queue_one_key"/>
        </rabbit:bindings>
    </rabbit:direct-exchange>
   
    <-- spring amqp is a jackson plugin by default, the purpose is to convert the data produced by the producer into json and store it in the message queue. Since fastjson is faster than jackson, it is replaced by an implementation of fastjson-->
    <bean id="jsonMessageConverter" class="mq.convert.FastJsonMessageConverter"></bean>
   
    <-- spring template declaration-->
    <rabbit :template exchange="my-mq-exchange" id="amqpTemplate" connection-factory="connectionFactory" message-converter="jsonMessageConverter"/>
</beans>
2. Fastjson messageconver plugin implementation


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 fe.json.FastJson;

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();
//init();
}

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) FastJson.fromJson(json, t.getClass());
}


protected Message createMessage(Object objectToConvert,
MessageProperties messageProperties)
throws MessageConversionException {
byte[] bytes = null;
try {
String jsonString = 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);

}
}
3.生产者端调用


import java.util.List;

import org.springframework.amqp.core.AmqpTemplate;


public class MyMqGatway {

@Autowired
private AmqpTemplate amqpTemplate;

public void sendDataToCrQueue(Object obj) {
amqpTemplate.convertAndSend("queue_one_key", obj);
}
}
4.消费者端配置(与生产者端大同小异)

<?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">

   
   <!-- 连接服务配置  -->
   <rabbit:connection-factory id="connectionFactory" host="localhost" username="guest"
        password="guest" port="5672"  />
       
   <rabbit:admin connection-factory="connectionFactory"/>
  
   <!-- queue queue declaration -->
   <rabbit:queue id="queue_one" durable="true" auto-delete="false" exclusive="false" name="queue_one"/>
  
  
   <!-- exchange queue binging key binding-->
    <rabbit:direct -exchange name="my-mq-exchange" durable="true" auto-delete="false" id="my-mq-exchange">
        <rabbit:bindings>
            <rabbit:binding queue="queue_one" key=" queue_one_key"/>
        </rabbit:bindings>
    </rabbit:direct-exchange>

   
    
    <!-- queue literener Observation listening mode When a message arrives, it will notify the listening object listening on the corresponding queue -->
    <rabbit:listener -container connection-factory="connectionFactory" acknowledge="auto" task-executor=" taskExecutor">
        <rabbit:listener queues="queue_one" ref="queueOneLitener"/>
    </rabbit:listener-container>
</beans>

5. The consumer calls

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

public class QueueOneLitener implements MessageListener{
@Override
public void onMessage(Message message) {
System.out.println( " data :" + message.getBody());
}
}
6. Since the consumer side will be notified when data arrives in the queue, the corresponding listening object will be notified, and it cannot be obtained in batches and stored in batches, so it can be consumed A temporary queue is cached on the side, and the data taken out by mq is stored in the local queue, and the background thread can process it in batches at regular intervals.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326705872&siteId=291194637