SpringBoot整合ActiveMq

1、先下載activemq安裝

從ActiveMq官方上下載ActiveMq服務
下載地址:http://activemq.apache.org/download.html

我當前下載的是版本是5.15.3 官方備註:當前最新的穩定版本。

下載下來解壓後進到window相對應的版本的bin目錄下執行activemq.bat

2、創建SpringBoot項目

pom.xml

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.8.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<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-activemq</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-pool</artifactId>
		</dependency>

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

		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.40</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
			<!-- optional=true,依賴不會傳遞,該項目依賴devtools;之後依賴myboot項目的項目如果想要使用devtools,需要重新引入 -->
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

生產者:

@Service("userProducer")
public class UserProducer {
	
	@Resource
	private JmsMessagingTemplate jmsMessagingTemplate;
	
	@Resource
	private Queue userQueue;
	@Resource
	private Queue queue;
	@Resource
	private Topic topic;
	

	public void sendData(Serializable obj) {
        this.jmsMessagingTemplate.convertAndSend(userQueue,obj);
    }
	public void sendMessage(String message) {
		this.jmsMessagingTemplate.convertAndSend(queue,message);
	}
	
	public void sendTopicMessage(String message) {
		this.jmsMessagingTemplate.convertAndSend(topic,message);
	}
}

activemq配置

@Configuration
public class ActiveMqConfig {

	@Bean
	public Queue userQueue() {
		return new ActiveMQQueue("userMqQueue");
	}

	@Bean
	public ActiveMQQueue queue() {
		return new ActiveMQQueue("weisg.queue");
	}

	@Bean
	public Topic topic() {
		return new ActiveMQTopic("weisg.topic");
	}

	// topic模式的ListenerContainer
	@Bean
	public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) {
		DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
		bean.setPubSubDomain(true);
		bean.setConnectionFactory(activeMQConnectionFactory);
		return bean;
	}

	// queue模式的ListenerContainer
	@Bean
	public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ConnectionFactory activeMQConnectionFactory) {
		DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
		bean.setConnectionFactory(activeMQConnectionFactory);
		return bean;
	}
}
以上的配置爲支持同時發送和接收queue/topic

消費者

@Service
public class UserConsumer {
	@JmsListener(destination = "userMqQueue",containerFactory = "jmsListenerContainerQueue")
	public void receive(ObjectMessage message) throws JMSException {
		System.out.println("----------UserConsumer-----------"+message);
		System.out.println("----------message-----------"+message.getObject());
		User user = new User();
		
		BeanUtils.copyProperties(message.getObject(), user);
		
		System.out.println("user--------------"+user);
		System.out.println("user數據數據完成...");
	}
	
	@JmsListener(destination = "weisg.topic",containerFactory = "jmsListenerContainerTopic")
	public void receiveTopicMessage(String message) throws JMSException {
		System.out.println("receiveTopicMessage--------------"+message);
	}
	
	@JmsListener(destination = "weisg.topic",containerFactory = "jmsListenerContainerTopic")
	public void receiveTopicMessage2(String message) throws JMSException {
		System.out.println("receiveTopicMessage2--------------"+message);
	}
}

請求方法

@RequestMapping(value="/api/addUser",method = RequestMethod.POST)
	public Map<String, Object> beetl(@RequestParam Map<String, Object> params){
		Map<String, Object> retMap = new HashMap<String, Object>();
		User user = new User();
		user.setUserId((String)params.get("userId"));
		user.setUserName((String)params.get("userName"));
		user.setMobile((String)params.get("mobile"));
		userProducer.sendData((Serializable)user);
		userProducer.sendMessage(user.getUserId());
		for (int i = 0; i < 10; i++) {
			userProducer.sendTopicMessage((String)params.get("userId")+i);
		}
		retMap.put("code", "200");
		retMap.put("msg", "success!");
		
		return retMap;
	}

配置文件:

spring.activemq.broker-url=tcp://127.0.0.1:61616
#如果此處設置爲true,需要加activemq-pool的依賴包,否則會自動配置失敗,報JmsMessagingTemplate注入失敗
spring.activemq.pool.enabled=true
spring.activemq.user=admin
# 密碼
spring.activemq.password=admin

# 在考慮結束之前等待的時間
spring.activemq.close-timeout=150
# 默認代理URL是否應該在內存中。如果指定了顯式代理,則忽略此值。
spring.activemq.in-memory=false 
# 是否在回滾回滾消息之前停止消息傳遞。這意味着當啓用此命令時,消息順序不會被保留。
spring.activemq.non-blocking-redelivery=false

# 等待消息發送響應的時間。設置爲0等待永遠。
spring.activemq.send-timeout=0

#發佈模式,爲true時是topic模式,爲false是queue模式
spring.jms.pub-sub-domain=true

# 是否信任所有包
#注意:對象傳輸需要開啓包白名單,否則會報錯
spring.activemq.packages.trust-all=true
# 要信任的特定包的逗號分隔列表(當不信任所有包時)

#spring.activemq.packages.trusted=
# 當連接請求和池滿時是否阻塞。設置false會拋“JMSException異常”。
#spring.activemq.pool.block-if-full=true
# 如果池仍然滿,則在拋出異常前阻塞時間。
#spring.activemq.pool.block-if-full-timeout=-1ms
# 是否在啓動時創建連接。可以在啓動時用於加熱池。
#spring.activemq.pool.create-connection-on-startup=true
# 是否用Pooledconnectionfactory代替普通的ConnectionFactory。
#spring.activemq.pool.enabled=false 
# 連接過期超時。
#spring.activemq.pool.expiry-timeout=0ms
#空閒的連接過期時間,默認爲30秒
spring.activemq.pool.idle-timeout=30
# 連接池最大連接數
spring.activemq.pool.max-connections=10
# 每個連接的有效會話的最大數目。
#spring.activemq.pool.maximum-active-session-per-connection=500
# 當有"JMSException"時嘗試重新連接
#spring.activemq.pool.reconnect-on-exception=true
# 在空閒連接清除線程之間運行的時間。當爲負數時,沒有空閒連接驅逐線程運行。
#spring.activemq.pool.time-between-expiration-check=-1ms
# 是否只使用一個MessageProducer
#spring.activemq.pool.use-anonymous-producers=true

結果:如下

2018-03-10 11:51:25.582 [http-nio-8889-exec-4] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization completed in 20 ms
----------UserConsumer-----------ActiveMQObjectMessage {commandId = 5, responseRequired = true, messageId = ID:admin-PC-51016-1520653879572-1:4:1:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:admin-PC-51016-1520653879572-1:4:1:1, destination = queue://userMqQueue, transactionId = null, expiration = 0, timestamp = 1520653885674, arrival = 0, brokerInTime = 1520653885675, brokerOutTime = 1520653885677, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@6df8e57e, marshalledProperties = org.apache.activemq.util.ByteSequence@4306219a, dataStructure = null, redeliveryCounter = 0, size = 0, properties = {timestamp=1520653885637}, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false}
----------message-----------User [userId=zhangsan001, userName=張三, userNo=null, mobile=15819295938]
user--------------User [userId=zhangsan001, userName=張三, userNo=null, mobile=15819295938]
user數據數據完成...
receiveTopicMessage--------------zhangsan0010
receiveTopicMessage2--------------zhangsan0010
receiveTopicMessage2--------------zhangsan0011
receiveTopicMessage--------------zhangsan0011
receiveTopicMessage--------------zhangsan0012
receiveTopicMessage2--------------zhangsan0012
receiveTopicMessage--------------zhangsan0013
receiveTopicMessage2--------------zhangsan0013
receiveTopicMessage--------------zhangsan0014
receiveTopicMessage--------------zhangsan0015
receiveTopicMessage2--------------zhangsan0014
receiveTopicMessage2--------------zhangsan0015
receiveTopicMessage--------------zhangsan0016
receiveTopicMessage--------------zhangsan0017
receiveTopicMessage2--------------zhangsan0016
receiveTopicMessage2--------------zhangsan0017
receiveTopicMessage--------------zhangsan0018
receiveTopicMessage2--------------zhangsan0018
receiveTopicMessage--------------zhangsan0019
receiveTopicMessage2--------------zhangsan0019




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章