栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

springboot2整合ActiveMQ

Java 更新时间:发布时间: 百科书网 趣学号

直接上代码,按流程搭建配置即可,其他讲解网上肯定可以自己跟进需要搜索

1、导入依赖


    org.springframework.boot
    spring-boot-starter-activemq


    org.apache.activemq
    activemq-pool

2、添加配置

spring:
  activemq:
    broker-url: tcp://192.168.199.145:61616
    in-memory: false #true 使用内置的MQ,false连接服务器
    user: admin
    password: admin
    pool:
      enabled: true #开启连接池
      max-connections: 10

3、相关bean对象

import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;

@Configuration
public class BeanConfig {

    @Autowired
    private Environment environment;

    @Bean
    public ConnectionFactory connectionFactory() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(environment.getProperty("spring.activemq.broker-url"));
        connectionFactory.setUserName(environment.getProperty("spring.activemq.user"));
        connectionFactory.setPassword(environment.getProperty("spring.activemq.password"));
        return connectionFactory;
    }

    @Bean
    public JmsTemplate genJmsTemplate() {
        return new JmsTemplate(connectionFactory());
    }

    @Bean
    public JmsMessagingTemplate jmsMessageTemplate() {
        return new JmsMessagingTemplate(connectionFactory());
    }
}

4、send信息

import com.example.demo.service.ProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jms.Destination;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ProducerService producerService;

    @GetMapping("/activemq")
    private Object order(String msg) {
        try {
            Destination destination = new ActiveMQQueue("order.queue");
            producerService.sendMsg(destination, msg);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }
}

5、消费信息

@Component
public class MyListener {

    @JmsListener(destination = "order.queue") // 监听test队列
    public void receiveQueue(String text) {
        System.out.println("Message: " + text);
    }
}

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/273984.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号