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

詳解SpringBoot中使用RabbitMQ的RPC功能

 更新時間:2021年11月15日 16:20:07   作者:黑瑩de希望  
這篇文章主要介紹了詳解SpringBoot中使用RabbitMQ的RPC功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、RabbitMQ的RPC簡介

實際業(yè)務(wù)中,有的時候我們還需要等待消費者返回結(jié)果給我們,或者是說我們需要消費者上的一個功能、一個方法或是一個接口返回給我們相應(yīng)的值,而往往大型的系統(tǒng)軟件,生產(chǎn)者跟消費者之間都是相互獨立的兩個系統(tǒng),部署在兩個不同的電腦上,不能通過直接對象.方法的形式獲取想要的結(jié)果,這時候我們就需要用到RPC(Remote Procedure Call)遠程過程調(diào)用方式。
RabbitMQ實現(xiàn)RPC的方式很簡單,生產(chǎn)者發(fā)送一條帶有標簽(消息ID(correlation_id)+回調(diào)隊列名稱)的消息到發(fā)送隊列,消費者(也稱RPC服務(wù)端)從發(fā)送隊列獲取消息并處理業(yè)務(wù),解析標簽的信息將業(yè)務(wù)結(jié)果發(fā)送到指定的回調(diào)隊列,生產(chǎn)者從回調(diào)隊列中根據(jù)標簽的信息獲取發(fā)送消息的返回結(jié)果。

在這里插入圖片描述

如圖,客戶端C發(fā)送消息,指定消息的ID=rpc_id,回調(diào)響應(yīng)的隊列名稱為rpc_resp,消息從C發(fā)送到rpc_request隊列,服務(wù)端S獲取消息業(yè)務(wù)處理之后,將correlation_id附加到響應(yīng)的結(jié)果發(fā)送到指定的回調(diào)隊列rpc_resp中,客戶端從回調(diào)隊列獲取消息,匹配與發(fā)送消息的correlation_id相同的值為消息應(yīng)答結(jié)果。

二、SpringBoot中使用RabbitMQ的RPC功能

注意:springboot中使用的時候,correlation_id為系統(tǒng)自動生成的,reply_to在加載AmqpTemplate實例的時候設(shè)置的。

實例:
說明:隊列1為發(fā)送隊列,隊列2為返回隊列

1.先配置rabbitmq

package com.ws.common;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/*
 * rabbitMQ配置類
 */
@Configuration
public class RabbitMQConfig {
	public static final String TOPIC_QUEUE1 = "topic.queue1";
    public static final String TOPIC_QUEUE2 = "topic.queue2";
    public static final String TOPIC_EXCHANGE = "topic.exchange";
    
    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.port}")
    private int port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;
    
    @Autowired
    ConnectionFactory connectionFactory;
    
    @Bean(name = "connectionFactory")
    public ConnectionFactory connectionFactory() {
    	CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    	connectionFactory.setHost(host);
    	connectionFactory.setPort(port);
    	connectionFactory.setUsername(username);
    	connectionFactory.setPassword(password);
    	connectionFactory.setVirtualHost("/");
    	return connectionFactory;
    }
    
    @Bean
    public RabbitTemplate rabbitTemplate() {
    	RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    	//設(shè)置reply_to(返回隊列,只能在這設(shè)置)
    	rabbitTemplate.setReplyAddress(TOPIC_QUEUE2);
    	rabbitTemplate.setReplyTimeout(60000);
    	return rabbitTemplate;
    }
    //返回隊列監(jiān)聽器(必須有)
    @Bean(name="replyMessageListenerContainer")
    public SimpleMessageListenerContainer createReplyListenerContainer() {
         SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
         listenerContainer.setConnectionFactory(connectionFactory);
         listenerContainer.setQueueNames(TOPIC_QUEUE2);
         listenerContainer.setMessageListener(rabbitTemplate());
         return listenerContainer;
    }
    

    
    //創(chuàng)建隊列
    @Bean
    public Queue topicQueue1() {
        return new Queue(TOPIC_QUEUE1);
    }
    @Bean
    public Queue topicQueue2() {
        return new Queue(TOPIC_QUEUE2);
    }
    
    //創(chuàng)建交換機
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }
    
    //交換機與隊列進行綁定
    @Bean
    public Binding topicBinding1() {
        return BindingBuilder.bind(topicQueue1()).to(topicExchange()).with(TOPIC_QUEUE1);
    }
    @Bean
    public Binding topicBinding2() {
        return BindingBuilder.bind(topicQueue2()).to(topicExchange()).with(TOPIC_QUEUE2);
    }
}

2.發(fā)送消息并同步等待返回值

@Autowired
private RabbitTemplate rabbitTemplate;


//報文body
String sss = "報文的內(nèi)容";
//封裝Message
Message msg = this.con(sss);
log.info("客戶端--------------------"+msg.toString());
//使用sendAndReceive方法完成rpc調(diào)用
Message message=rabbitTemplate.sendAndReceive(RabbitMQConfig.TOPIC_EXCHANGE, RabbitMQConfig.TOPIC_QUEUE1, msg);
//提取rpc回應(yīng)內(nèi)容body
String response = new String(message.getBody());
log.info("回應(yīng):" + response);
log.info("rpc完成---------------------------------------------");


public Message con(String s) {
	MessageProperties mp = new MessageProperties();
	byte[] src = s.getBytes(Charset.forName("UTF-8"));
	//mp.setReplyTo("adsdas");   加載AmqpTemplate時設(shè)置,這里設(shè)置沒用
	//mp.setCorrelationId("2222");   系統(tǒng)生成,這里設(shè)置沒用
	mp.setContentType("application/json");
	mp.setContentEncoding("UTF-8");
	mp.setContentLength((long)s.length());
	return new Message(src, mp);
} 

3.寫消費者

package com.ws.listener.mq;

import java.nio.charset.Charset;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ws.common.RabbitMQConfig;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class Receiver {
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	@RabbitListener(queues=RabbitMQConfig.TOPIC_QUEUE1)
	public void receiveTopic1(Message msg) {
		log.info("隊列1:"+msg.toString());
		String msgBody = new String(msg.getBody());
		//數(shù)據(jù)處理,返回的Message
		Message repMsg = con(msgBody+"返回了", msg.getMessageProperties().getCorrelationId());
		
		rabbitTemplate.send(RabbitMQConfig.TOPIC_EXCHANGE, RabbitMQConfig.TOPIC_QUEUE2, repMsg);
		
    }
	@RabbitListener(queues=RabbitMQConfig.TOPIC_QUEUE2)
	public void receiveTopic2(Message msg) {
		log.info("隊列2:"+msg.toString());
		
    }
	
	public Message con(String s, String id) {
		MessageProperties mp = new MessageProperties();
		byte[] src = s.getBytes(Charset.forName("UTF-8"));
		mp.setContentType("application/json");
		mp.setContentEncoding("UTF-8");
		mp.setCorrelationId(id);
		
		return new Message(src, mp);
	} 
}

日志打?。?/p>

2019-06-26 17:11:16.607 [http-nio-8080-exec-4] INFO com.ws.controller.UserController - 客戶端--------------------(Body:‘報文的內(nèi)容' MessageProperties [headers={}, contentType=application/json, contentEncoding=UTF-8, contentLength=5, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])

2019-06-26 17:11:16.618 [SimpleAsyncTaskExecutor-1] INFO com.ws.listener.mq.Receiver - 隊列1:(Body:‘報文的內(nèi)容' MessageProperties [headers={}, correlationId=1, replyTo=topic.queue2, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=topic.exchange, receivedRoutingKey=topic.queue1, deliveryTag=1, consumerTag=amq.ctag-8IzlhblYmTebqUYd-uferw, consumerQueue=topic.queue1])

2019-06-26 17:11:16.623 [http-nio-8080-exec-4] INFO com.ws.controller.UserController - 回應(yīng):報文的內(nèi)容返回了

2019-06-26 17:11:16.623 [http-nio-8080-exec-4] INFO com.ws.controller.UserController - rpc完成---------------------------------------------

到此這篇關(guān)于SpringBoot中使用RabbitMQ的RPC功能的文章就介紹到這了,更多相關(guān)SpringBoot使用RabbitMQ內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringMVC HttpMessageConverter報文信息轉(zhuǎn)換器

    SpringMVC HttpMessageConverter報文信息轉(zhuǎn)換器

    ??HttpMessageConverter???,報文信息轉(zhuǎn)換器,將請求報文轉(zhuǎn)換為Java對象,或?qū)ava對象轉(zhuǎn)換為響應(yīng)報文。???HttpMessageConverter???提供了兩個注解和兩個類型:??@RequestBody,@ResponseBody???,??RequestEntity,ResponseEntity??
    2023-01-01
  • SpringBoot中獲取微信用戶信息的方法

    SpringBoot中獲取微信用戶信息的方法

    這篇文章主要介紹了SpringBoot中獲取微信用戶信息的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • 微信公眾號測試賬號自定義菜單的實例代碼

    微信公眾號測試賬號自定義菜單的實例代碼

    這篇文章主要介紹了微信公眾號測試賬號自定義菜單的實例代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-02-02
  • Java中實現(xiàn)時間類型轉(zhuǎn)換的代碼詳解

    Java中實現(xiàn)時間類型轉(zhuǎn)換的代碼詳解

    這篇文章主要為大家詳細介紹了Java中實現(xiàn)時間類型轉(zhuǎn)換的相關(guān)方法,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考下
    2023-09-09
  • SpringBoot 單元測試JUnit的使用詳解

    SpringBoot 單元測試JUnit的使用詳解

    這篇文章主要介紹了SpringBoot 單元測試JUnit的使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • 了解Java線程池執(zhí)行原理

    了解Java線程池執(zhí)行原理

    那么有沒有一種辦法使得線程可以復(fù)用,就是執(zhí)行完一個任務(wù),并不被銷毀,而是可以繼續(xù)執(zhí)行其他的任務(wù)?在Java中可以通過線程池來達到這樣的效果。下面我們來詳細了解一下吧
    2019-05-05
  • Java 程序初始化順序

    Java 程序初始化順序

    這篇文章主要介紹了Java 程序初始化順序,在Java語言中,當(dāng)實例化對象時,對象所在類的所有成員變量首先要進行初始化,只有當(dāng)所有的類成員完成了初始化之后,才會調(diào)用對象所在類的構(gòu)造函數(shù)創(chuàng)建對象,需要的朋友可以參考一下
    2022-01-01
  • Java判斷字節(jié)流是否是 UTF8編碼方法示例

    Java判斷字節(jié)流是否是 UTF8編碼方法示例

    這篇文章主要我大家介紹了Java判斷字節(jié)流是否是 UTF8編碼方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • 關(guān)于@PostConstruct、afterPropertiesSet和init-method的執(zhí)行順序

    關(guān)于@PostConstruct、afterPropertiesSet和init-method的執(zhí)行順序

    這篇文章主要介紹了關(guān)于@PostConstruct、afterPropertiesSet和init-method的執(zhí)行順序,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 解析Java的Spring框架的BeanPostProcessor發(fā)布處理器

    解析Java的Spring框架的BeanPostProcessor發(fā)布處理器

    這篇文章主要介紹了Java的Spring框架的BeanPostProcessor發(fā)布處理器,Spring是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下
    2015-12-12

最新評論

茶陵县| 万年县| 永顺县| 手机| 昌邑市| 乌拉特后旗| 新津县| 乌拉特中旗| 罗山县| 阳谷县| 宣武区| 图们市| 兴城市| 兰考县| 确山县| 青铜峡市| 曲阳县| 密云县| 裕民县| 叙永县| 莎车县| 石林| 辽宁省| 瓮安县| 黄梅县| 苏州市| 徐水县| 旅游| 阳曲县| 祥云县| 玉屏| 商水县| 永泰县| 东兰县| 商城县| 高唐县| 河北省| 牡丹江市| 宜宾县| 宜宾市| 武功县|