簡體   English   中英

EnableBinding 在 Spring Cloud Stream 3.x 中被棄用

[英]EnableBinding is deprecated in Spring Cloud Stream 3.x

我正在將 Kafka 用於微服務項目。 每當我將記錄保存到數據庫時,我都想調用一個事件。 一直在看Spring Cloud Stream的教程,都是用@EnableBinding、@Input、@Output注解。 當我嘗試使用它們時,它說它們已被棄用。 我正在使用 spring initialzr。 發行說明說我應該使用 Supplier、Consumer 和 Function 而不是 Input、Output 和 Process 等舊方法。

@Bean
public Supplier<String> toUpperCase() {
    return () -> {
        return "hello from supplier";
    };
}

當我像這樣使用 Supplier 時,它每秒都會生成一條消息,因為它也在教程中突出顯示。 我不希望它每秒都被發布。 我希望它在我想要的時候發布。 它說我應該調用它的 get() 方法,但我不知道如何調用。 教程使用不推薦使用的函數來實現這樣的功能。 我如何在沒有棄用函數的情況下實現這種行為,或者我如何使用 EnableBinder 注釋而不表明它已被棄用?

您可以在https 查看我的演示項目的 repo://github.com/HabeebCycle/spring-cloud-stream-implemention

它展示了如何使用 RabbitMQ 和 Kafka 為供應商和消費者實施雲流,以及如何對這兩種服務進行端到端測試。

對於你的情況:在你的供應商 bean 中做這樣的事情:

@Bean
public Supplier<DataEvent<String, User>> savedMessage() {
    return () -> {
        return null;
    };
}

Spring提供function package中的StreamBridge可以用來發送事件。 假設您有一個保存到數據庫中的服務層。 要做的第一件事是創建一個由構造函數綁定注入的自動裝配的 StreamBridge,並使用它來發送您的消息,如下所示。 請注意,供應商的名稱應該是您的 output 的綁定名稱,如文檔中所述。

private final StreamBridge stream;
private final UserRepository repo;

// Store your topic/binding name as the supplier name as follows
private static final String SUPPLIER_BINDING_NAME = "savedMessage-out-0"

public UserService(UserRepository repo, StreamBridge stream) {
   this.repo = repo;
   this.stream = stream;
}

// Your save method
public void saveUser(User user) {
  // Do some checking...

  //save your record
  User user = repo.save(user);
  
  //check if user is saved or not null
  //create your message event (Assuming you have a DataEvent class)
  DataEvent<String, User> event = new DataEvent<>("User Saved", user);
  boolean sent = stream.send(SUPPLIER_BINDING_NAME, event));

  // Check the repo above for proper implementation.
}

對於消費者實施,請查看我上面的回購協議。

這里也有實現雖然寫在Kotlin https://piotrminkowski.com/2020/06/05/introduction-to-event-driven-microservices-with-spring-cloud-stream/

您還可以在 GitHub 此處查看 Spring 最近的項目https://github.com/spring-cloud/spring-cloud-stream-samples/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM