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

时间:2020-12-24 17:36:44

标签: java spring

我将 Kafka 用于微服务项目。每当我将记录保存到数据库时,我都想调用一个事件。我一直在看有关 Spring Cloud Stream 的教程。他们都在使用@EnableBinding、@Input、@Output 注释。当我尝试使用它们时,它说它们已被弃用。我正在使用 spring 初始值设定项。发行说明说我应该使用供应商、消费者和函数,而不是像 Input、Output 和 Process 这样的旧方法。

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

当我使用这样的供应商时,它每秒生成一条消息,因为它也在教程中突出显示。我不希望它每秒钟都发布一次。我希望它在我想要的时候发布。它说我应该调用它的 get() 方法,但我不知道如何调用。教程使用不推荐使用的函数来实现这样的功能。如何在没有弃用函数的情况下实现此类行为,或者如何使用 EnableBinder 注释而不说它已弃用?

1 个答案:

答案 0 :(得分:4)

您可以在 https://github.com/HabeebCycle/spring-cloud-stream-implemention

查看我的存储库中的演示项目

它展示了如何使用 RabbitMQ 和 Kafka 为供应商和消费者实现云流,以及如何对这两种服务进行端到端测试。

对于您的情况: 在您的供应商 bean 中执行以下操作:

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

Spring 在函数包中提供了 StreamBridge 可以用来发送事件。 假设您有一个保存到数据库中的服务层。首先要做的是创建一个由构造函数绑定注入的自动装配的 StreamBridge,并使用它来发送您的消息,如下所示。请注意,供应商的名称应该是您的输出的绑定名称,如文档中所述。

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/