SpringCloud 支持Schema的轉(zhuǎn)換器

2023-11-27 13:57 更新

AvroSchemaMessageConverter支持通過使用預(yù)定義的架構(gòu)或通過使用類中可用的架構(gòu)信息(反射地或包含在SpecificRecord中)來對消息進(jìn)行序列化和反序列化。如果提供自定義轉(zhuǎn)換器,則不會(huì)創(chuàng)建默認(rèn)的AvroSchemaMessageConverter bean。以下示例顯示了一個(gè)自定義轉(zhuǎn)換器:

要使用自定義轉(zhuǎn)換器,您只需將其添加到應(yīng)用程序上下文中,就可以選擇指定一個(gè)或多個(gè)與其關(guān)聯(lián)的MimeTypes。默認(rèn)MimeTypeapplication/avro

如果轉(zhuǎn)換的目標(biāo)類型是GenericRecord,則必須設(shè)置架構(gòu)。

以下示例顯示如何通過在沒有預(yù)定義架構(gòu)的情況下注冊Apache Avro MessageConverter在接收器應(yīng)用程序中配置轉(zhuǎn)換器。在此示例中,請注意,啞劇類型值為avro/bytes,而不是默認(rèn)的application/avro。

@EnableBinding(Sink.class)
@SpringBootApplication
public static class SinkApplication {

  ...

  @Bean
  public MessageConverter userMessageConverter() {
      return new AvroSchemaMessageConverter(MimeType.valueOf("avro/bytes"));
  }
}

相反,以下應(yīng)用程序使用預(yù)定義的架構(gòu)(在類路徑上找到)注冊一個(gè)轉(zhuǎn)換器:

@EnableBinding(Sink.class)
@SpringBootApplication
public static class SinkApplication {

  ...

  @Bean
  public MessageConverter userMessageConverter() {
      AvroSchemaMessageConverter converter = new AvroSchemaMessageConverter(MimeType.valueOf("avro/bytes"));
      converter.setSchemaLocation(new ClassPathResource("schemas/User.avro"));
      return converter;
  }
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)