直接上代码,按流程搭建配置即可,其他讲解网上肯定可以自己跟进需要搜索
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
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);
}
}