1. pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. application.properties
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
3. RabbitConfig.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
private static final Logger log = LoggerFactory.getLogger(RabbitConfig.class);
@Bean
public Queue newsQueue() {
return new Queue("newsQueue");
}
@Bean
public Queue news1Queue() {
return new Queue("news1");
}
@Bean
public Queue news2Queue() {
return new Queue("news2");
}
@Bean
public FanoutExchange fanoutExchange() {
return new FanoutExchange("newsTopic");
}
@Bean
public Binding bindingNews1Queue(Queue news1Queue, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(news1Queue).to(fanoutExchange);
}
@Bean
public Binding bindingNews2Queue(Queue news2Queue, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(news2Queue).to(fanoutExchange);
}
}
4. 发送消息
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Producer {
private static final Logger log = LoggerFactory.getLogger(Producer.class);
@Autowired
private AmqpTemplate rabbitTemplate;
public void sendNewsQueue(String msg) {
rabbitTemplate.convertAndSend("newsQueue", msg);
}
// 参数可以直接传对象
public void sendStockTopic(String msg) {
rabbitTemplate.convertAndSend("newsTopic", "", msg);
}
}
5. 接收消息
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class News1Consumer {
private static final Logger log = LoggerFactory.getLogger(News1Consumer.class);
public static long count = 0;
@RabbitHandler
@RabbitListener(queues = "news1", containerFactory = "rabbitListenerContainerFactory")
public void process(String msg) {
log.info("msg:" + msg);
}
}