不哔哔,直接上代码
主要是 消费者添加配置
一,把配置放在配置中心(放在消费服务上也可以)
listener.direct.auto-startup设置为false,
然后添加 rabbitmq.start 作为启动属性
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
listener:
direct:
auto-startup: false
rabbitmq:
start: true
然后在消费服务的启动类 xxxxxApplication.class中添加
package com.test.service1;
import com.test.rabbitmq.RabbitmqApplication;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
@SpringBootApplication
@EnableEurekaClient
public class Service1Application {
public static void main(String[] args) {
ApplicationContext context=SpringApplication.run(Service1Application.class, args);
RabbitMQStart rabbitMQRun = context.getBean(RabbitMQStart.class);
rabbitMQRun.start();
}
@Bean
public RabbitMQStart rabbitMQRun() {
return new RabbitMQStart();
}
private static class RabbitMQStart {
//为了在main中的static方法中使用@value注解只能用这种办法
@Value("${rabbitmq.start}")
private Boolean rabbitmqStart;
@Resource
RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry;
public void start() {
if(rabbitmqStart)
rabbitListenerEndpointRegistry.start();
else
rabbitListenerEndpointRegistry.stop();
System.out.println("=================== Rabbitmq:"+rabbitmqStart+"===================");
}
}
}
二,测试:
rabbitmq.start = true 时
rabbitmq.start = false 时