rabbitmq(1)基础amqp使用

2019-05-14  本文已影响0人  Ukuleler

pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

application.yml

spring:
  profiles:
    active: usage_message
  rabbitmq:
    host: localhost
    port: 5672
    username: gust
    password:gust

tutorial:
  client:
    duration: 10000

MqtestApplication.java 启动类

@SpringBootApplication
@EnableScheduling
public class MqtestApplication {

    @Profile("usage_message")
    @Bean
    public CommandLineRunner usage() {
        return args -> {
            System.out.println("This app uses Spring Profiles to control its behavior.\n");
                    System.out.println("Sample usage: java -jar rabbit-tutorials.jar --spring.profiles.active=hello-world,sender");
        };
    }

    @Profile("!usage_message")
    @Bean
    public CommandLineRunner tutorial() {
        return new RabbitAmqpTutorialsRunner();
    }

    public static void main(String[] args) {
        SpringApplication.run(MqtestApplication.class, args);
    }

}

Tut1Config.java 配置文件

@Profile({"tut1","hello-world"})
@Configuration
public class Tut1Config {

    @Bean
    public Queue hello() {
        return new Queue("mqt1");
    }

    @Profile("receiver")
    @Bean
    public Tut1Receiver receiver() {
        return new Tut1Receiver();
    }

    @Profile("sender")
    @Bean
    public Tut1Sender sender() {
        return new Tut1Sender();
    }
}

RabbitAmqpTutorialsRunner.java rabbitmq启动限制类
这个类没有用,只是在启动一定时间后执行commandline,将应用停止

public class RabbitAmqpTutorialsRunner implements CommandLineRunner {
    @Value("${tutorial.client.duration:0}")
    private int duration;

    @Autowired
    private ConfigurableApplicationContext ctx;

    @Override
    public void run(String... arg0) throws Exception {
        System.out.println("Ready ... running for " + duration + "ms");
        Thread.sleep(duration);
        ctx.close();
    }
}

Tut1Receiver.java

@RabbitListener(queues = "mqt1")
public class Tut1Receiver {

    @RabbitHandler
    public void receive(String in) {
        System.out.println(" [x] Received '" + in + "'");
    }
}

Tut1Sender.java

public class Tut1Sender {
    @Autowired
    private RabbitTemplate template;

    @Autowired
    private Queue queue;

    @Scheduled(fixedDelay = 1000, initialDelay = 500)
    public void send() {
        System.out.println("发送了一次消息");
        String message = "Hello World!";
        this.template.convertAndSend(queue.getName(), message);
        System.out.println(" [x] Sent '" + message + "'");
    }
}

启动通过java -jar rabbit-tutorials.jar --spring.profiles.active=hello-world,sender

上一篇下一篇

猜你喜欢

热点阅读