springbootconfigspringbootmybatis

Spring Boot应用中整合消息中间件RabbitMQ

2017-11-13  本文已影响96人  angeChen
dota2.jpg

我们通过在Spring Boot应用中整合RabbitMQ,实现一个简单的发送、接收消息的例子来对RabbitMQ有一个直观的感受和理解。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring.rabbitmq.addresses=10.110.200.29:5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
@Component
public class Sender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        rabbitTemplate.convertAndSend("hello", context);
    }
}
@Component
@RabbitListener(queues = "hello")
public class Receiver {

    // 这里 process 方法名 和 hello 参数名 可以任意。
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver : " + hello);
    }
}
@Configuration
public class RabbitConfig {

    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }
}
@SpringBootApplication
public class RabbitMQApplication {

    public static void main(String[] args) {
        SpringApplication.run(RabbitMQApplication.class, args);
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RabbitMQApplicationTests {

    @Autowired
    private Sender sender;

    @Test
    public void contextLoads() {
        sender.send();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读