一。生产者模块(以通配模式为例)
配置类:
@Configuration
public class RabbitConfig {
public static final String GUANGZHOU_XIAOZHANG_QUEUE= "guangzhou_xiaozhang_queue" ;
public static final String ZONGBU_CAIWU_QUEUE= "zongbu_caiwu_queue" ;
public static final String TOPIC_EXCHANGE= "topic_exchange" ;
@Bean ( TOPIC_EXCHANGE)
public Exchange exchange ( ) {
return ExchangeBuilder . topicExchange ( TOPIC_EXCHANGE) . durable ( true ) . build ( ) ;
}
@Bean ( GUANGZHOU_XIAOZHANG_QUEUE)
public Queue queue1 ( ) {
return new Queue ( GUANGZHOU_XIAOZHANG_QUEUE, true , false , false , null ) ;
}
@Bean ( ZONGBU_CAIWU_QUEUE)
public Queue queue2 ( ) {
return new Queue ( ZONGBU_CAIWU_QUEUE, true , false , false , null ) ;
}
@Bean
public Binding binding1 ( @Qualifier ( GUANGZHOU_XIAOZHANG_QUEUE) Queue queue,
@Qualifier ( TOPIC_EXCHANGE) Exchange exchange) {
return BindingBuilder . bind ( queue) . to ( exchange) . with ( "guangzhou.*.*" ) . noargs ( ) ;
}
@Bean
public Binding binding2 ( @Qualifier ( ZONGBU_CAIWU_QUEUE) Queue queue,
@Qualifier ( TOPIC_EXCHANGE) Exchange exchange) {
return BindingBuilder . bind ( queue) . to ( exchange) . with ( "*.caiwu.*" ) . noargs ( ) ;
}
}
yml配置端口,主机,用户,虚拟机等等略
测试用例
@RunWith ( SpringRunner . class )
@SpringBootTest ( classes = ProducerApplication . class )
public class RabbitTest {
@Autowired
RabbitTemplate rabbitTemplate;
@Test
public void send ( ) {
String msg = "123" ;
rabbitTemplate. convertAndSend ( RabbitConfig . TOPIC_EXCHANGE, "guangzhou.haha.eee" , msg) ;
}
}
依赖略
二。消费者:
监听类:
@Component
public class MyListener {
@RabbitListener ( queues = RabbitConfig . GUANGZHOU_XIAOZHANG_QUEUE)
public void receive ( Message message, String msg) {
System . out. println ( "msg:" + msg) ;
byte [ ] body = message. getBody ( ) ;
try {
System . out. println ( new String ( body, "utf-8" ) ) ;
} catch ( UnsupportedEncodingException e) {
e. printStackTrace ( ) ;
}
}
}
主启动类启动消费者:
@SpringBootApplication
public class ConsumerApplication {
public static void main ( String [ ] args) {
SpringApplication . run ( ConsumerApplication . class , args) ;
}
}
config配置类和生产者一致,保险起见,要加此类
yml配置略