Spring Cloud整合 RabbitMQ

时间:2024-03-30 12:50:13

 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

 登陆成功

Spring Cloud整合 RabbitMQ
设置默认VirtualHost给yhc

Spring Cloud整合 RabbitMQ

然后开始配置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();
    }
}

运行程序,观察控制台:

Spring Cloud整合 RabbitMQ

RabbitMQ管理页面显示:

Spring Cloud整合 RabbitMQ

证明确实有消息传递