RabbitMQ(三)Direct Exchange Demo

配置类

在application.yml中添加

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest

pom.xml

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.2.RELEASE
         
    
      
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-amqp
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
    

DirectConfig配置类

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DirectConfig {

    public final  static String DIRECTQUEUE = "direct";
    @Bean
    public Queue queue(){
        return new Queue(DIRECTQUEUE);
    }
}

生产者

DirectSender

import com.gebiwangdaye.rabbitmq.config.DirectConfig;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DirectSender {
    @Autowired
    private AmqpTemplate amqpTemplate;

    public void send(){
        String context = "发送消息 ================== direct";
        System.out.println(context);
        this.amqpTemplate.convertAndSend(DirectConfig.DIRECTQUEUE,context);
    }

}

消费者

DirectReceiver

import com.gebiwangdaye.rabbitmq.config.DirectConfig;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = DirectConfig.DIRECTQUEUE)
public class DirectReceiver {
    @RabbitHandler
    public void process(String hello) {
        System.out.println("接收到消息 : " + hello);
    }
}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqApplicationTests {


    @Autowired
    private DirectSender directSender;

    @Test
    public void testDirectExchange(){
        for (int i = 0;i < 30;i++){
            directSender.send();
        }
    }

}

你可能感兴趣的:(RabbitMQ(三)Direct Exchange Demo)