1. Mac搭建Activemq

  1. 安装brew,如果已经安装了直接跳过
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
  1. 安装Activemq
brew install activemq 
  1. 启动Activemq
activemq  start
  1. 访问地址http://localhost:8161/

    默认账号密码都是:admin

image-20191121185932450

问题:

  1. 如果直接在官网下载linux版activemq,运行会报错。

    image-20191121190655476

    这个问题应该是mac os 10.15版本的原因。所以只能通过brew来安装。

2. 生产者

代码地址

2.1 pom导入

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
</dependencies>

2.2 yml配置

注意这里的地址是:tcp://127.0.0.1:61616,和后台访问的地址不一样。

server:
  port: 20001
  servlet:
    context-path: /

spring:
  application:
    name: activemq-consumer

  activemq:
    broker-url: tcp://127.0.0.1:61616
    user: admin
    password: admin
queue: queue

2.3 创建一个队列

@Configuration
public class QueueConfig {

    @Value("${queue}")
    private String queue;

    @Bean
    public Queue logQueue() {
        return new ActiveMQQueue(queue);
    }

}

2.4 发布消息

@Component
@EnableScheduling
@Slf4j
public class Producer {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Queue queue;

    @Scheduled(fixedDelay = 10000)
    public void send() {
        String message = "发布消息:" + System.currentTimeMillis();
        log.info(message);
        jmsMessagingTemplate.convertAndSend(queue,message);
    }

}

3. 消费者

代码地址

3.1 pom导入

和生产者导入的依赖一样

<dependencies>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
</dependencies>

3.2 yml配置

server:
  port: 20000
  servlet:
    context-path: /

spring:
  application:
    name: activemq-consumer

  activemq:
    broker-url: tcp://127.0.0.1:61616
    user: admin
    password: admin

queue: queue

3.3 接收消息

@Slf4j
@Component
public class Consumer {
    @JmsListener(destination = "${queue}")
    public void receive(String msg) {
        log.info("接收数据:{}",msg);
    }
}
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐