spring boot2.x使用rabbitmq

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

在spring boot中使用rabbitmq比较简单:

pom中引入:


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

application.properties中添加:

#rabbitmq
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

新建rabbitmq config文件

@Configuration
public class MqConfig {
    // 队列名称
    public final static String SPRING_BOOT_QUEUE = "spring-boot-queue";
    // 交换机名称
    public final static String SPRING_BOOT_EXCHANGE = "spring-boot-exchange";
    // 绑定的值
    public static final String SPRING_BOOT_BIND_KEY = "spring-boot-bind-key";


    // === 在RabbitMQ上创建queue,exchange,binding 方法一:通过@Bean实现 begin ===
    /**
     * 定义队列:
     * @return
     */
    @Bean
    Queue queue() {
        return new Queue(SPRING_BOOT_QUEUE, false);
    }

    /**
     * 定义交换机
     * @return
     */
    @Bean
    TopicExchange exchange() {
        return new TopicExchange(SPRING_BOOT_EXCHANGE);
    }

    /**
     * 定义绑定
     * @param queue
     * @param exchange
     * @return
     */
    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(SPRING_BOOT_BIND_KEY );
    }
}

创建sender:

@Component
public class Sender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String msg){
        rabbitTemplate.convertAndSend(SPRING_BOOT_QUEUE,msg);
    }
}

创建receiver:

@Component
@RabbitListener(queues = SPRING_BOOT_QUEUE)
public class Receiver {
    @RabbitHandler
    public void process(String msg){
        System.out.println("Receiver:"+msg+"------"+ LocalDateTime.now());
    }
}

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SenderTest {
    @Autowired
    private Sender sender;

    @Test
    public void send() {
        sender.send("Hello spring boot and rabbitmq "+ LocalDateTime.now());
    }
}

输入结果:Receiver:Hello spring boot and rabbitmq  2018-10-02T22:16:53.927869300------2018-10-02T22:16:53.964968700

转载于:https://my.oschina.net/yunduansing/blog/2222486

你可能感兴趣的:(spring boot2.x使用rabbitmq)