最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springBoot整合rabbitMQ的方法詳解

 更新時間:2021年04月20日 09:59:08   作者:喜羊羊love紅太狼  
這篇文章主要介紹了springBoot整合rabbitMQ的方法詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

引入pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.wxy</groupId>
	<artifactId>test-rabbitmq</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>test-rabbitmq</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</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.amqp</groupId>
			<artifactId>spring-rabbit-test</artifactId>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
 
</project>

測試

package com.wxy.rabbit;
 
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
 
@RunWith(SpringRunner.class)
@SpringBootTest
class TestRabbitmqApplicationTests {
 
	@Autowired
	RabbitTemplate rabbitTemplate;
 
	@Test
	public  void sendmessage() {
		String exchange  = "exchange.direct";
		String routingkey  = "wxy.news";
		//object為消息發(fā)送的消息體,可以自動實現(xiàn)消息的序列化
		Map<String,Object> msg = new HashMap<>();
		msg.put("msg","使用mq發(fā)送消息");
		msg.put("data", Arrays.asList("helloword",123456,true));
		rabbitTemplate.convertAndSend(exchange, routingkey,msg);
	}
 
 
	@Test
	public  void receive() {
		Object object  = rabbitTemplate.receiveAndConvert("wxy.news");
		System.out.println(object);
	}
 
}

默認消息轉(zhuǎn)換類型

 ###############在RabbitTemplate默認使用的是SimpleMessageConverter#######
  private MessageConverter messageConverter = new SimpleMessageConverter();
 
 
  ###############源碼:使用SerializationUtils.deserialize###############
   public Object fromMessage(Message message) throws MessageConversionException {
        Object content = null;
        MessageProperties properties = message.getMessageProperties();
        if (properties != null) {
            String contentType = properties.getContentType();
            if (contentType != null && contentType.startsWith("text")) {
                String encoding = properties.getContentEncoding();
                if (encoding == null) {
                    encoding = this.defaultCharset;
                }
 
                try {
                    content = new String(message.getBody(), encoding);
                } catch (UnsupportedEncodingException var8) {
                    throw new MessageConversionException("failed to convert text-based Message content", var8);
                }
            } else if (contentType != null && contentType.equals("application/x-java-serialized-object")) {
                try {
                    content = SerializationUtils.deserialize(this.createObjectInputStream(new ByteArrayInputStream(message.getBody()), this.codebaseUrl));
                } catch (IllegalArgumentException | IllegalStateException | IOException var7) {
                    throw new MessageConversionException("failed to convert serialized Message content", var7);
                }
            }
        }

將默認消息類型轉(zhuǎn)化成自定義json格式

第一:上面SimpleMessageConverter是org.springframework.amqp.support.converter包下MessageConverter接口的一個實現(xiàn)類
 
第二:查看該接口MessageConverter下支持哪些消息轉(zhuǎn)化
ctrl+H查看該接口中的所有實現(xiàn)類
 
第三步:找到json相關的convert

RabbitTemplateConfigurer中定義if (this.messageConverter != null)則使用配置的messageConverter
 ################## if (this.messageConverter != null)則使用配置的messageConverter 
public void configure(RabbitTemplate template, ConnectionFactory connectionFactory) {
        PropertyMapper map = PropertyMapper.get();
        template.setConnectionFactory(connectionFactory);
        if (this.messageConverter != null) {
            template.setMessageConverter(this.messageConverter);
        }
 
        template.setMandatory(this.determineMandatoryFlag());
        Template templateProperties = this.rabbitProperties.getTemplate();
        if (templateProperties.getRetry().isEnabled()) {
            template.setRetryTemplate((new RetryTemplateFactory(this.retryTemplateCustomizers)).createRetryTemplate(templateProperties.getRetry(), Target.SENDER));
        }
 
        templateProperties.getClass();
        map.from(templateProperties::getReceiveTimeout).whenNonNull().as(Duration::toMillis).to(template::setReceiveTimeout);
        templateProperties.getClass();
        map.from(templateProperties::getReplyTimeout).whenNonNull().as(Duration::toMillis).to(template::setReplyTimeout);
        templateProperties.getClass();
        map.from(templateProperties::getExchange).to(template::setExchange);
        templateProperties.getClass();
        map.from(templateProperties::getRoutingKey).to(template::setRoutingKey);
        templateProperties.getClass();
        map.from(templateProperties::getDefaultReceiveQueue).whenNonNull().to(template::setDefaultReceiveQueue);
    }

配置一個messageConversert(org.springframework.amqp.support.converter包中的)

package com.wxy.rabbit.config;
 
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MessageConverConfig {
 
    @Bean
    public MessageConverter getMessageConvert(){
        return  new Jackson2JsonMessageConverter();
    }
}

再次發(fā)送消息體json格式

使用注解@RabbitListener監(jiān)聽

監(jiān)聽多個隊列

@RabbitListener(queues = {"wxy.news","wxy.emps"})

監(jiān)聽單個隊列

@RabbitListener(queues = "wxy.news")
package com.wxy.rabbit.service;
 
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
 
@Service
public class RabbitMqReceiveService {
 
    @RabbitListener(queues = {"wxy.news","wxy.emps"})
    public void  getReceiveMessage(){
        System.out.println("監(jiān)聽到性的消息");
    }
 
 
    @RabbitListener(queues =  {"wxy.news","wxy.emps"})
    public void  getReceiveMessageHead(Message message){
        System.out.println(message.getBody());
        System.out.println( message.getMessageProperties());
    }
 
}

在程序中創(chuàng)建隊列,交換器,并進行綁定

@Test
	public  void create() {
		//創(chuàng)建一個點對點的交換器
		amqpAdmin.declareExchange(new DirectExchange("amqpexchange.direct"));
		//創(chuàng)建一個隊列
		// String name,:隊列名稱
		// boolean durable :持久化
		amqpAdmin.declareQueue(new Queue("amqp.queue",true));
		//綁定
		//String destination, Binding.DestinationType destinationType, String exchange, String routingKey
		//  @Nullable Map<String, Object> arguments
		amqpAdmin.declareBinding(new Binding("amqp.queue", Binding.DestinationType.QUEUE,
				"amqpexchange.direct","wxy.news", null));
 
	}

到此這篇關于springBoot整合rabbitMQ的方法詳解的文章就介紹到這了,更多相關springBoot整合rabbitMQ內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java 多線程并發(fā)AbstractQueuedSynchronizer詳情

    Java 多線程并發(fā)AbstractQueuedSynchronizer詳情

    這篇文章主要介紹了Java 多線程并發(fā)AbstractQueuedSynchronizer詳情,文章圍繞主題展開想象的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下
    2022-06-06
  • 詳解SpringBoot可執(zhí)行Jar包運行原理

    詳解SpringBoot可執(zhí)行Jar包運行原理

    SpringBoot有一個很方便的功能就是可以將應用打成可執(zhí)行的Jar,那么大家有沒想過這個Jar是怎么運行起來的呢,本篇博客就來介紹下 SpringBoot可執(zhí)行Jar包的運行原理,需要的朋友可以參考下
    2023-05-05
  • Java中的List與Set轉(zhuǎn)換方式

    Java中的List與Set轉(zhuǎn)換方式

    Java中,List和Set是兩種基本的集合類型,它們在允許重復元素、元素順序、實現(xiàn)類以及性能方面有著明顯的區(qū)別,List允許重復元素并保持元素插入的順序,常見實現(xiàn)有ArrayList、LinkedList和Vector;Set不允許重復元素
    2024-11-11
  • 詳解非spring框架下使用querydsl的方法

    詳解非spring框架下使用querydsl的方法

    Querydsl是一個采用API代替拼湊字符串來構(gòu)造查詢語句,可跟 Hibernate 和 JPA 等框架結(jié)合使用。本文介紹的是非spring環(huán)境下querydsl JPA整合使用,感興趣的小伙伴們可以參考一下
    2019-01-01
  • Java中的CountDownLatch同步工具類使用解析

    Java中的CountDownLatch同步工具類使用解析

    這篇文章主要介紹了Java中的CountDownLatch使用解析,CountDownLatch初始化的時候必須指定一個count,await方法會一直阻塞直到調(diào)用countdown方法,count為0,當count為0時,所有的等待線程都會被釋放,需要的朋友可以參考下
    2023-12-12
  • Java FastJson使用教程

    Java FastJson使用教程

    這篇文章主要介紹了如何使用FastJson,幫助大家將 Java 對象轉(zhuǎn)換為 JSON 格式,感興趣的朋友可以了解下
    2020-10-10
  • Java中final關鍵字和final的四種用法實例

    Java中final關鍵字和final的四種用法實例

    final關鍵字代表最終的、不可改變的,下面這篇文章主要給大家介紹了關于Java中final關鍵字和final的四種用法實例,文中通過圖文以及實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-02-02
  • 使用@ControllerAdvice同時配置過濾多個包

    使用@ControllerAdvice同時配置過濾多個包

    這篇文章主要介紹了使用@ControllerAdvice同時配置過濾多個包的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 淺談Spring-boot事件監(jiān)聽

    淺談Spring-boot事件監(jiān)聽

    這篇文章主要介紹了淺談Spring-boot事件監(jiān)聽,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • 95%的Java程序員人都用不好Synchronized詳解

    95%的Java程序員人都用不好Synchronized詳解

    這篇文章主要為大家介紹了95%的Java程序員人都用不好Synchronized詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03

最新評論

新泰市| 阿拉善左旗| 麻江县| 吴江市| 禹城市| 中超| 栖霞市| 北票市| 和平县| 郎溪县| 平阳县| 汉源县| 铜山县| 新源县| 德州市| 寻甸| 满洲里市| 喀什市| 张家港市| 饶河县| 灵璧县| 十堰市| 咸阳市| 壶关县| 东阳市| 万山特区| 宁化县| 永兴县| 汨罗市| 堆龙德庆县| 莱芜市| 昌邑市| 绩溪县| 登封市| 神农架林区| 河西区| 呼图壁县| 青冈县| 延庆县| 鄯善县| 垫江县|