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

SpringCloudStream原理和深入使用小結(jié)

 更新時間:2024年06月20日 12:29:59   作者:7仔要加油  
Spring?Cloud?Stream是一個用于構(gòu)建與共享消息傳遞系統(tǒng)連接的高度可擴展的事件驅(qū)動型微服務(wù)的框架,本文給大家介紹SpringCloudStream原理和深入使用,感興趣的朋友跟隨小編一起看看吧

簡單概述

Spring Cloud Stream是一個用于構(gòu)建與共享消息傳遞系統(tǒng)連接的高度可擴展的事件驅(qū)動型微服務(wù)的框架。

應(yīng)用程序通過inputs或outputs來與Spring Cloud Stream中binder對象交互,binder對象負(fù)責(zé)與消息中間件交互。也就是說:Spring Cloud Stream能夠屏蔽底層消息中間件【RabbitMQ,kafka等】的差異,降低切換成本,統(tǒng)一消息的編程模型。

相關(guān)概念

Channel(通道):Channel是消息的傳輸管道,用于在生產(chǎn)者和消費者之間傳遞消息。生產(chǎn)者通過輸出通道將消息發(fā)送到Destination,消費者通過輸入通道從Destination接收消息。

在Spring Cloud Stream中,有兩種類型的通道:輸入(input)和輸出(output)。這兩種通道分別用于消費者接收消息和生產(chǎn)者發(fā)送消息。

  • Input(輸入):Input通道用于消費者從消息代理接收消息。消費者可以通過監(jiān)聽Input通道來實時接收傳入的消息
  • Output(輸出):Output通道用于生產(chǎn)者向消息代理發(fā)送消息。生產(chǎn)者可以通過向Output通道發(fā)送消息來發(fā)布新的消息

Destination(目標(biāo)):Destination是消息的目的地,通常對應(yīng)于消息代理中的Topic或Queue。生產(chǎn)者將消息發(fā)送到特定的Destination,消費者從其中接收消息。

Binder(綁定器):Binder是Spring Cloud Stream的核心組件之一。它作為消息代理與外部消息中間件進行交互,并負(fù)責(zé)將消息發(fā)送到消息總線或從消息總線接收消息。Binder負(fù)責(zé)處理消息傳遞、序列化、反序列化、消息路由等底層細(xì)節(jié),使得開發(fā)者能夠以統(tǒng)一的方式與不同的消息中間件進行交互。Spring Cloud Stream提供了多個可用的Binder實現(xiàn),包括RabbitMQ、Kafka等。

**消費者組:**在Spring Cloud Stream中,消費組(Consumer Group)是一組具有相同功能的消費者實例。當(dāng)多個消費者實例屬于同一個消費組時,消息代理會將消息均勻地分發(fā)給消費者實例,以實現(xiàn)負(fù)載均衡。如果其中一個消費者實例失效,消息代理會自動將消息重新分配給其他可用的消費者實例,以實現(xiàn)高可用性。(對于一個消息來說,每個消費者組只會有一個消費者消費消息)

分區(qū):Spring Cloud Stream支持在多個消費者實例之間創(chuàng)建分區(qū),這樣我們通過某些特征量做消息分發(fā),保證相同標(biāo)識的消息總是能被同一個消費者處理

Spring Message

Spring Message是Spring Framework的一個模塊,其作用就是統(tǒng)一消息的編程模型。

package org.springframework.messaging;
public interface Message<T> {
    T getPayload();
    MessageHeaders getHeaders();
}

消息通道 MessageChannel 用于接收消息,調(diào)用send方法可以將消息發(fā)送至該消息通道中:

@FunctionalInterface
public interface MessageChannel {
	long INDEFINITE_TIMEOUT = -1;
	default boolean send(Message<?> message) {
		return send(message, INDEFINITE_TIMEOUT);
	}
	boolean send(Message<?> message, long timeout);
}

消息通道里的消息由消息通道的子接口可訂閱的消息通道SubscribableChannel實現(xiàn),被MessageHandler消息處理器所訂閱

public interface SubscribableChannel extends MessageChannel {
	boolean subscribe(MessageHandler handler);
	boolean unsubscribe(MessageHandler handler);
}

MessageHandler真正地消費/處理消息

@FunctionalInterface
public interface MessageHandler {
    void handleMessage(Message<?> message) throws MessagingException;
}

Spring Integration

Spring Integration 提供了 Spring 編程模型的擴展用來支持企業(yè)集成模式(Enterprise Integration Patterns),是對 Spring Messaging 的擴展。

它提出了不少新的概念,包括消息路由MessageRoute、消息分發(fā)MessageDispatcher、消息過濾Filter、消息轉(zhuǎn)換Transformer、消息聚合Aggregator、消息分割Splitter等等。同時還提供了MessageChannel和MessageHandler的實現(xiàn),分別包括 DirectChannel、ExecutorChannel、PublishSubscribeChannel和MessageFilter、ServiceActivatingHandler、MethodInvokingSplitter 等內(nèi)容。

Spring-Cloud-Stream的架構(gòu)

img

快速入門

引入依賴

        <!--stream-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
        </dependency>

增加配置文件

spring:
    cloud:
        stream:
            # 定義消息中間件
            binders:
              MyRabbit:
                  type: rabbit
                  environment:
                    spring:
                        rabbitmq:
                            host: localhost
                            port: 5672
                            username: root
                            password: root
                            vhost: /
            bindings:
            # 生產(chǎn)者中定義,定義發(fā)布對象
              myInput:
                destination: myStreamExchange
                group: myStreamGroup
                binder: MyRabbit
            # 消費者中定義,定義訂閱的對象
              myOutput-in-0:
                destination: myStreamExchange
                group: myStreamGroup
                binder: MyRabbit
        # 消費者中定義,定義輸出的函數(shù)
        function:
            definition: myOutput

生產(chǎn)者

@Resource
	private StreamBridge streamBridge;
	public void sendNormal() {
		streamBridge.send("myInput", "hello world");
	}

消費者

@Bean("myOutput")
	public Consumer<Message<String>> myOutput() {
		return (message) -> {
			MessageHeaders headers = message.getHeaders();
			System.out.println("myOutput head is : " + headers);
			String payload = message.getPayload();
			System.out.println("myOutput payload is : " + payload);
		};
	}

如何自定義Binder

  • 添加spring-cloud-stream依賴
  • 提供ProvisioningProvider的實現(xiàn)提供
  • MessageProducer的實現(xiàn)提供
  • MessageHandler的實現(xiàn)提供
  • Binder的實現(xiàn)創(chuàng)建Binder的配置
  • META-INF/spring.binders中定義綁定器

添加spring-cloud-stream依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream</artifactId>
    <version>${spring.cloud.stream.version}</version>
</dependency>

提供ProvisioningProvider的實現(xiàn)

ProvisioningProvider負(fù)責(zé)提供消費者和生產(chǎn)者目的地,并需要將 application.yml 或 application.properties 文件中包含的邏輯目的地轉(zhuǎn)換為物理目的地引用。

public class FileProvisioningProvider implements ProvisioningProvider<
	ExtendedConsumerProperties<FileConsumerProperties>, ExtendedProducerProperties<FileProducerProperties>> {
	public FileProvisioningProvider() {
		super();
	}
	@Override
	public ProducerDestination provisionProducerDestination(String name, ExtendedProducerProperties<FileProducerProperties> properties) throws ProvisioningException {
		return new FileMessageDestination(name);
	}
	@Override
	public ConsumerDestination provisionConsumerDestination(String name, String group, ExtendedConsumerProperties<FileConsumerProperties> properties) throws ProvisioningException {
		return new FileMessageDestination(name);
	}
	private static class FileMessageDestination implements ProducerDestination, ConsumerDestination {
		private final String destination;
		private FileMessageDestination(final String destination) {
			this.destination = destination;
		}
		@Override
		public String getName() {
			return destination.trim();
		}
		@Override
		public String getNameForPartition(int partition) {
			throw new UnsupportedOperationException("Partitioning is not implemented for file messaging.");
		}
	}
}

提供MessageProducer的實現(xiàn)

MessageProducer負(fù)責(zé)使用事件并將其作為消息處理,發(fā)送給配置為使用此類事件的客戶端應(yīng)用程序。

super.onInit();
		executorService = Executors.newScheduledThreadPool(1);
	}
	@Override
	public void doStart() {
		executorService.scheduleWithFixedDelay(() -> {
			String payload = getPayload();
			if (payload != null) {
				Message<String> receivedMessage = MessageBuilder.withPayload(payload).build();
				sendMessage(receivedMessage);
			}
		}, 0, 50, TimeUnit.MILLISECONDS);
	}
	@Override
	protected void doStop() {
		executorService.shutdownNow();
	}
	private String getPayload() {
		try {
			List<String> allLines = Files.readAllLines(Paths.get(fileExtendedBindingProperties.getPath() + File.separator + destination.getName() + ".txt"));
			String currentPayload = allLines.get(allLines.size() - 1);
			if (!currentPayload.equals(previousPayload)) {
				previousPayload = currentPayload;
				return currentPayload;
			}
		} catch (IOException e) {
			FileUtil.touch(new File(fileExtendedBindingProperties.getPath() + File.separator + destination.getName() + ".txt"));
		}
		return null;
	}
}

提供MessageHandler的實現(xiàn)

MessageHandler提供產(chǎn)生事件所需的邏輯。

public class FileMessageHandler extends AbstractMessageHandler {
	FileExtendedBindingProperties fileExtendedBindingProperties;
	ProducerDestination destination;
	public FileMessageHandler(ProducerDestination destination, FileExtendedBindingProperties fileExtendedBindingProperties) {
		this.destination = destination;
		this.fileExtendedBindingProperties = fileExtendedBindingProperties;
	}
	@Override
	protected void handleMessageInternal(Message<?> message) {
		try {
			if (message.getPayload() instanceof byte[]) {
				Files.write(Paths.get(fileExtendedBindingProperties.getPath() + File.separator + destination.getName() + ".txt"), (byte[]) message.getPayload());
			} else {
				throw new RuntimeException("處理消息失敗");
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}

提供Binder的實現(xiàn)

提供自己的Binder抽象實現(xiàn):

  • 擴展AbstractMessageChannelBinder
  • 將自定義的 ProvisioningProvider 指定為 AbstractMessageChannelBinder 的通用參數(shù)
  • 重寫createProducerMessageHandlercreateConsumerEndpoint方法
public class FileMessageChannelBinder extends AbstractMessageChannelBinder
	<ExtendedConsumerProperties<FileConsumerProperties>, ExtendedProducerProperties<FileProducerProperties>, FileProvisioningProvider>
	implements ExtendedPropertiesBinder<MessageChannel, FileConsumerProperties, FileProducerProperties> {
	FileExtendedBindingProperties fileExtendedBindingProperties;
	public FileMessageChannelBinder(String[] headersToEmbed, FileProvisioningProvider provisioningProvider, FileExtendedBindingProperties fileExtendedBindingProperties) {
		super(headersToEmbed, provisioningProvider);
		this.fileExtendedBindingProperties = fileExtendedBindingProperties;
	}
	@Override
	protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<FileProducerProperties> producerProperties, MessageChannel errorChannel) throws Exception {
		FileMessageHandler fileMessageHandler = new FileMessageHandler(destination, fileExtendedBindingProperties);
		return fileMessageHandler;
	}
	@Override
	protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<FileConsumerProperties> properties) throws Exception {
		FileMessageProducerAdapter fileMessageProducerAdapter = new FileMessageProducerAdapter(destination, fileExtendedBindingProperties);
		return fileMessageProducerAdapter;
	}
	@Override
	public FileConsumerProperties getExtendedConsumerProperties(String channelName) {
		return fileExtendedBindingProperties.getExtendedConsumerProperties(channelName);
	}
	@Override
	public FileProducerProperties getExtendedProducerProperties(String channelName) {
		return fileExtendedBindingProperties.getExtendedProducerProperties(channelName);
	}
	@Override
	public String getDefaultsPrefix() {
		return fileExtendedBindingProperties.getDefaultsPrefix();
	}
	@Override
	public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
		return fileExtendedBindingProperties.getExtendedPropertiesEntryClass();
	}
}

創(chuàng)建Binder的配置

嚴(yán)格要求創(chuàng)建一個 Spring 配置來初始化你的綁定器實現(xiàn)的 bean

@EnableConfigurationProperties(FileExtendedBindingProperties.class)
@Configuration
public class FileMessageBinderConfiguration {
	@Bean
	@ConditionalOnMissingBean
	public FileProvisioningProvider fileMessageBinderProvisioner() {
		return new FileProvisioningProvider();
	}
	@Bean
	@ConditionalOnMissingBean
	public FileMessageChannelBinder fileMessageBinder(FileProvisioningProvider fileMessageBinderProvisioner, FileExtendedBindingProperties fileExtendedBindingProperties) {
		return new FileMessageChannelBinder(null, fileMessageBinderProvisioner, fileExtendedBindingProperties);
	}
	@Bean
	public FileProducerProperties fileConsumerProperties() {
		return new FileProducerProperties();
	}
}

詳細(xì)的代碼見https://gitee.com/xiaovcloud/spring-cloud-stream

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

相關(guān)文章

  • 利用POI讀取word、Excel文件的最佳實踐教程

    利用POI讀取word、Excel文件的最佳實踐教程

    Apache POI 是用Java編寫的免費開源的跨平臺的 Java API,Apache POI提供API給Java程式對Microsoft Office格式檔案讀和寫的功能。 下面這篇文章主要給大家介紹了關(guān)于利用POI讀取word、Excel文件的最佳實踐的相關(guān)資料,需要的朋友可以參考下。
    2017-11-11
  • java web實現(xiàn)網(wǎng)上手機銷售系統(tǒng)

    java web實現(xiàn)網(wǎng)上手機銷售系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了java web實現(xiàn)網(wǎng)上手機銷售系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • 新手初學(xué)Java-Map

    新手初學(xué)Java-Map

    Map簡介:將鍵映射到值的對象。一個映射不能包含重復(fù)的鍵;每個鍵最多只能映射到一個值。此接口取代 Dictionary 類,后者完全是一個抽象類,而不是一個接口
    2021-07-07
  • Java多線程編程中的線程死鎖的問題解決

    Java多線程編程中的線程死鎖的問題解決

    線程死鎖是多線程編程中的一個常見問題,它發(fā)生在多個線程互相等待對方釋放資源的情況下,導(dǎo)致程序無法繼續(xù)執(zhí)行,本文就來介紹一下Java多線程編程中的線程死鎖的問題解決,感興趣的可以了解一下
    2023-08-08
  • 使用GSON庫將Java中的map鍵值對應(yīng)結(jié)構(gòu)對象轉(zhuǎn)換為JSON

    使用GSON庫將Java中的map鍵值對應(yīng)結(jié)構(gòu)對象轉(zhuǎn)換為JSON

    GSON是由Google開發(fā)并開源的實現(xiàn)Java對象與JSON之間相互轉(zhuǎn)換功能的類庫,這里我們來看一下使用GSON庫將Java中的map鍵值對應(yīng)結(jié)構(gòu)對象轉(zhuǎn)換為JSON的示例:
    2016-06-06
  • Java 并發(fā)編程ArrayBlockingQueue的實現(xiàn)

    Java 并發(fā)編程ArrayBlockingQueue的實現(xiàn)

    這篇文章主要介紹了Java 并發(fā)編程ArrayBlockingQueue的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • 詳解Java線程的創(chuàng)建及休眠

    詳解Java線程的創(chuàng)建及休眠

    今天帶大家學(xué)習(xí)的是Java的相關(guān)知識,文章圍繞著Java線程的創(chuàng)建及休眠展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • SpringBoot項目執(zhí)行腳本 自動拉取最新代碼并重啟的實例內(nèi)容

    SpringBoot項目執(zhí)行腳本 自動拉取最新代碼并重啟的實例內(nèi)容

    在本篇文章里小編給大家整理的是一篇關(guān)于SpringBoot項目執(zhí)行腳本 自動拉取最新代碼并重啟的實例內(nèi)容,有需要的朋友們參考下。
    2019-12-12
  • springboot掃描自定義的servlet和filter代碼詳解

    springboot掃描自定義的servlet和filter代碼詳解

    本文是一篇根據(jù)作者工作經(jīng)歷總結(jié)出來的關(guān)于springboot掃描自定義的servlet和filter代碼詳解的文章,小編覺得非常不錯,這里給大家分享下,和朋友們一起學(xué)習(xí),進步。
    2017-10-10
  • SpringBoot?AOP統(tǒng)一處理Web請求日志的示例代碼

    SpringBoot?AOP統(tǒng)一處理Web請求日志的示例代碼

    springboot有很多方法處理日志,例如攔截器,aop切面,service中代碼記錄等,下面這篇文章主要給大家介紹了關(guān)于SpringBoot?AOP統(tǒng)一處理Web請求日志的相關(guān)資料,需要的朋友可以參考下
    2023-02-02

最新評論

正蓝旗| 安福县| 永城市| 宜城市| 澄迈县| 海伦市| 长顺县| 莆田市| 灵台县| 花垣县| 精河县| 兴宁市| 鱼台县| 搜索| 张掖市| 阿拉尔市| 兰坪| 乌拉特前旗| 正镶白旗| 河池市| 齐河县| 嘉义县| 涡阳县| 康马县| 杭锦后旗| 水富县| 寿阳县| 张家界市| 岑巩县| 神池县| 柘荣县| 广州市| 玛沁县| 洛隆县| 虹口区| 姚安县| 德化县| 祁连县| 吴桥县| 华容县| 元江|