- 首先引入pom支持
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
- 其次基本XML的配置
<!-- 启用注解 -->
<rabbit:annotation-driven/>
<rabbit:connection-factory id="connectionFactory" username="${RabbitMQ.message.user}"
password="${RabbitMQ.message.password}" host="${RabbitMQ.message.ip}"
port="${RabbitMQ.message.port}"
virtual-host="/"/>
<rabbit:template id="innjia" connection-factory="connectionFactory" />
<rabbit:admin connection-factory="connectionFactory"/>
<!-- 用于注解 -->
<bean id="rabbitListenerContainerFactory"
class="org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="concurrentConsumers" value="3"/>
<property name="maxConcurrentConsumers" value="10"/>
</bean>
- 代码调用
/**
* @author zhouxianglh@gmail.com
*/
@Service
public class DemoServiceImpl {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoServiceImpl.class);
/** 定义消息队列名称 **/
private static final String QUEUE_NAME = "testB";
/** 创建消息队列 **/
@Bean
public org.springframework.amqp.core.Queue getQueue() {
return new org.springframework.amqp.core.Queue(QUEUE_NAME);
}
@Autowired
private RabbitTemplate template;
/** 发送消息方法 **/
public void send(Object obj) {
try {
template.convertAndSend(QUEUE_NAME,obj);
} catch (Exception e) {
LOGGER.error("", e);
}
}
/**
* 通过监听的方式接收消息(注意这里方法是 final ,因为Spring开启代码,如果不设置final 会报异常)
* @param obj 接收消息实体
* @param deliveryTag 消息发送次数,第一次为空,之后累加(这里因为抛出异常,消息会不断重试)
* @param message 未折封的消息对象(非必需要)
*/
@RabbitListener(queues = QUEUE_NAME)
public final void recive(Object obj, @Header(value = AmqpHeaders.DELIVERY_TAG, required = false) String deliveryTag, Message message) {
LOGGER.error(deliveryTag + " ++++++++++++++++++++ " + obj);
//这里抛出异常,测试消息重发机制
throw new RuntimeException("***********");
}
}
更多文档参考 https://docs.spring.io/spring-amqp/reference/html/_reference.html