`
zk_chs
  • 浏览: 212874 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

spring boot + ActiveMQ 实现消息服务

 
阅读更多

上篇博客带来的是spring boot + redis实现session共享的文章,这次给大家带来的是spring boot + activemq。

 

首先,我在github上找到了一个不错的demo,这里放给大家一起看下:

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-activemq

 

确实可以实现功能,但是当我在8161默认的admin端口进行queue查询时,发现并没有我们的github-queue,虽然不太清楚具体的原因,但是解决方式倒是找到了,下面贴一下自己的实现:

pox.xml:

<!-- ActiveMQ -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.13.2</version>
        </dependency>

application.properties:

spring.activemq.in-memory=true
spring.activemq.pooled=false

 

 

接下来就是jms的配置了,首先是ActiveMQ4Config文件:

@EnableJms
@Configuration
public class ActiveMQ4Config {

    @Bean
    public Queue queue() {
        return new ActiveMQQueue("github-queue");
    }

    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory (){
        ActiveMQConnectionFactory activeMQConnectionFactory =
                new ActiveMQConnectionFactory(
                        ActiveMQConnectionFactory.DEFAULT_USER,
                        ActiveMQConnectionFactory.DEFAULT_PASSWORD,
//                        "tcp://192.168.0.100:61616");
                        ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
        return activeMQConnectionFactory;
    }

}

注释掉的那行,可以用来指定activemq的broker地址。

 

接下来的Producer和Consumer与github上一样:

@Component
public class Producer implements CommandLineRunner{

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Queue queue;

    @Override
    public void run(String... args) throws Exception {
        send("this message is send on begining!");
        System.out.println("Message was sent to the Queue");
    }

    public void send(String msg) {
        this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
    }

}
@Component
public class Consumer {

    @JmsListener(destination = "github-queue")
    public void receiveQueue(String text) {
        System.out.println(text);
    }

}

 

这样一来就完成了配置,而且在8161默认admin进行查询时,是能够查询到我们的github-queue这个队列的。

具体的测试,可以自己进行,这里不再贴测试用例了。

 

 

分享到:
评论
1 楼 fcs_our2010 2017-01-17  
赞一个的说

相关推荐

Global site tag (gtag.js) - Google Analytics