Spring整合RabbitMQ

在整合Spring/Springboot之前,我们加入相关的依赖在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-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>
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
        </dependency>
    </dependencies>

我们写一个配置类的bean注入进去:

@Configuration
@ComponentScan({"com.jlu.rabbitmqspring.*"})
public class RabbitMQConfig {

    @Bean
    public ConnectionFactory connectionFactory(){

        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setHost("192.168.119.134"); 
        factory.setUsername("king");
        factory.setPassword("123456");
        factory.setVirtualHost("/");

        return factory;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }
}

上面那些根据你自己的情况进行修改,包括主机名以及账号密码等设置。接下来,我们写一下测试类:

@SpringBootTest
class RabbitmqSpringApplicationTests {

    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Test
    void contextLoads() {
        rabbitAdmin.declareExchange(new DirectExchange("test.direct",false,false));
        rabbitAdmin.declareExchange(new TopicExchange("test.topic",false,false));
        rabbitAdmin.declareQueue(new Queue("test.direct.queue",false));
        rabbitAdmin.declareQueue(new Queue("test.topic.queue",false));
        rabbitAdmin.declareBinding(new Binding("test.direct.queue",
                Binding.DestinationType.QUEUE,
                "test.direct","direct",new HashMap<>()));
// 上面是方式一,下面是方式二
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue("test.topic.queue",false))
                .to(new TopicExchange("test.topic",false,false))
        .with("test.#"));
        //第一步创建队列,第二步创建exchange并绑定到上面,第三步创建路由键
    }
}

方式二是流式写法,方式一需要提前创建exchange和queue,方式二不需要。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值