springboot整合activeMQ

springboot整合activeMQ


  1. 安装activeMQ
下载地址:http://activemq.apache.org/
解压
进入解压后的目录运行 ./bin/activemq start
启动后activemq会启动两个端口:
8161是activemq的管理页面,默认的账号密码都是admin
61616是程序连接activemq的通讯地址
  1. 引入依赖

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

3.修改application.yml

 	spring:
		  activemq:
		#ActiveMQ通讯地址
		broker-url: tcp://localhost:61616
		#用户名
		user: admin
		#密码
		password: admin
		#是否启用内存模式(就是不安装MQ,项目启动时同时启动一个MQ实例)
		in-memory: false
		packages:
		  #信任所有的包
		  trust-all: true
		pool:
		  #是否替换默认的连接池,使用ActiveMQ的连接池需引入的依赖
		  enabled: false

4.配置activeMQ

    @Configuration
	@EnableJms
	public class ActiveMQConfig {
	    @Bean
	    public Queue queue() {
	        return new ActiveMQQueue("springboot.queue") ;
	    }
	
	    //springboot默认只配置queue类型消息,如果要使用topic类型的消息,则需要配置该bean
	    @Bean
	    public JmsListenerContainerFactory jmsTopicListenerContainerFactory(ConnectionFactory connectionFactory){
	        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
	        factory.setConnectionFactory(connectionFactory);
	        //这里必须设置为true,false则表示是queue类型
	        factory.setPubSubDomain(true);
	        return factory;
	    }
	
	    @Bean
	    public Topic topic() {
	        return new ActiveMQTopic("springboot.topic") ;
	    }
	}

5.创建消费者

	@Component
	public class Consumer {
	
	    //接收queue类型消息
	    //destination对应配置类中ActiveMQQueue("springboot.queue")设置的名字
	    @JmsListener(destination="springboot.queue")
	    public void ListenQueue(String msg){
	        System.out.println("接收到queue消息:" + msg);
	    }
	
	    //接收topic类型消息
	    //destination对应配置类中ActiveMQTopic("springboot.topic")设置的名字
	    //containerFactory对应配置类中注册JmsListenerContainerFactory的bean名称
	    @JmsListener(destination="springboot.topic", containerFactory = "jmsTopicListenerContainerFactory")
	    public void ListenTopic(String msg){
	        System.out.println("接收到topic消息:" + msg);
	    }
	}

6.创建生产者

@RestController
public class Producer {
    @Autowired
    private JmsMessagingTemplate jmsTemplate;

    @Autowired
    private Queue queue;

    @Autowired
    private Topic topic;

    //发送queue类型消息
    @GetMapping("/queue")
    public void sendQueueMsg(String msg){
        jmsTemplate.convertAndSend(queue, msg);
    }

    //发送topic类型消息
    @GetMapping("/topic")
    public void sendTopicMsg(String msg){
        jmsTemplate.convertAndSend(topic, msg);
    }

}
  1. 启动程序测试
浏览器中输入http://localhost:8080/queue?msg=hello
控制台:接收到queue消息:hello

浏览器中输入http://localhost:8080/topic?msg=hello
控制台:接收到topic消息:hello
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值