rabbitmq发布订阅模式-生产者

pom:

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

yml:

server:
  port: 8080
spring:
  rabbitmq:
    host: 192.168.31.97
    port: 5672
    password: admin
    username: admin
    virtual-host: /
order:
  fanout:
    exchange: order.fanout.exchange

Producer:

package com.kejin.mqtest.mq;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
public class Producer{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //1.定义交换机
    @Value("${order.fanout.exchange}")
    private String exchangeName;

    //2.路由key
    private String routeKey="";

    public void sendMessage(int i){
        String orderId= UUID.randomUUID().toString();
        String message=i+"==>你的订单id是"+orderId+",日期是"+new Date();
        rabbitTemplate.convertAndSend(exchangeName,routeKey,message);

    }
}

test:

package com.kejin.mqtest;

import com.kejin.mqtest.mq.Producer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class MqtestApplicationTests {
    @Autowired
    private Producer producer;

    @Test
    void contextLoads() {
        for (int i = 0; i <100 ; i++) {
            try {
                Thread.sleep(1000);
                producer.sendMessage(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页