gpt4 book ai didi

java - 在 Spring Cloud Stream 3.x 中不推荐使用 EnableBinding

转载 作者:行者123 更新时间:2023-12-03 09:38:09 27 4
gpt4 key购买 nike

我正在将 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";
};
}
当我使用这样的供应商时,它会每秒生成一条消息,因为它也在教程中突出显示。我不希望它每秒都发布。我希望它在我想要的时候发布。它说我应该调用它的 get() 方法,但我不知道如何。教程使用不推荐使用的函数来实现这样的功能。如何在没有弃用函数的情况下实现这种行为,或者如何使用 EnableBinder 批注而不表示它已弃用?

最佳答案

您可以在 https://github.com/HabeebCycle/spring-cloud-stream-implemention 查看我的演示项目的 repo
它展示了如何使用 RabbitMQ 和 Kafka 为供应商和消费者实现云流,以及这两种服务的端到端测试。
对于您的情况:
在您的供应商 bean 中执行以下操作:

@Bean
public Supplier<DataEvent<String, User>> savedMessage() {
return () -> {
return null;
};
}
Spring在函数包中提供了StreamBridge,可以用来发送事件。
假设您有一个保存到数据库中的服务层。首先要做的是创建一个通过构造函数绑定(bind)注入(inject)的 Autowiring StreamBridge 并使用它来发送您的消息,如下所示。请注意,供应商的名称应该是您的输出的绑定(bind)名称,如文档中所述。
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.
}
对于消费者实现,请查看我上面的 repo 。
这里也有一个实现,虽然是用 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/

关于java - 在 Spring Cloud Stream 3.x 中不推荐使用 EnableBinding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65441549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com