1. 程式人生 > >Spring Cloud整合 RabbitMQ

Spring Cloud整合 RabbitMQ

 ubuntu伺服器安裝RabbitMQ:

 sudo apt-get install erlang  //安裝erlang
 echo 'deb http://www.rabbitmq.com/debian/ testing main' |sudo tee /etc/apt/source.list.d/rabbitmq.list  //新增RabbitMQ倉庫
 sudo apt-get update
 sudo apt-get install rabbitmq-server
 sudo rabbitmq-plugins enable rabbitmq_management //rabbitmq啟動
 
//直接訪問伺服器15672埠,guest帳戶登陸失敗,百度得知需要建立新使用者

 sudo rabbitctl add-user yhc yhc
 sudo rabbitctl set_user_tags yhc administrator

 登陸成功


設定預設VirtualHost給yhc

然後開始配置demo
建立spring boot專案,Maven引入spring-cloud-starter-bus-amqp、spring-cloud-starter-eureka、spring-boot-starter-actuator新增RabbitMQ配置:

spring.application.name=amqp-demo
server.port=6666
spring.rabbitmq.host=伺服器IP
spring.rabbitmq.port=5672
spring.rabbitmq.username=yhc
spring.rabbitmq.password=yhc

建立Producer、Consumer、RabbitConfig

@Component
public class Producer {
    @Autowired
    private AmqpTemplate template;

    public void produce(){
        template.convertAndSend("hello","Hello World!");
    }
}
@Component
@RabbitListener(queues = "hello")
public class Consumer {
    @RabbitHandler
    public void consume(String msg){
        System.out.println(msg);
    }
}
@Configuration
public class RabbitConfig {
    @Bean
    public Queue getQueue(){
        return new Queue("hello");
    }
}

編寫Test執行produce方法:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbusdemoApplication.class)
public class SpringbusdemoApplicationTests {
    @Autowired
    Producer producer;

    @Test
    public void test() {
        producer.produce();
    }
}

執行程式,觀察控制檯:

RabbitMQ管理頁面顯示:

證明確實有訊息傳遞