1. 程式人生 > >022 spring與Rabbitmq整合

022 spring與Rabbitmq整合

ring config resource 進行 virt vat gte urn address

一 .概述

  本次我們使用spring幫助我們完成Rabbitmq的使用.


二 .環境的搭建

  本次使用springboot的jar文件幫助整合rabbitmq,但是本質上還是使用spring的方式進行整合.

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <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> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8
</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>


三 .創建ConnectionFactory

@Configuration
public class RabbitmqConfig {
    
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory factory 
= new CachingConnectionFactory(); factory.setAddresses("39.106.154.23:5672"); factory.setVirtualHost("/"); factory.setUsername("root"); factory.setPassword("trek"); return factory; } }

在上面的代碼之中,我們創建了一個ConnectionFactory,記住這個Bean是spring為我們提供的哪一個ConnectionFactory,並不是Rabbitmq提供的那一個ConnectionFactory.

下面,我們做一下測試:  

@RunWith(SpringRunner.class)
@SpringBootTest
public class ConfigTest {
    
    @Resource
    private ConnectionFactory connectionFactory;
    
    @Test
    public void testConnectionFactory() {
        System.out.println(connectionFactory.createConnection());
    }
    
}

如果能夠正確的得到Connection對象,就說明我們的整合的第一步是成功的了,下面我們會繼續整合spirngampq之中的其它的組件

022 spring與Rabbitmq整合