Spring整合Activemq

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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章