1 Temmuz 2021 Perşembe

SpringCloud Stream StreamBridge Sınıfı - Controller'dan Topic'e Erişim İçindir

Giriş
Şu satırı dahil ederiz
import org.springframework.cloud.stream.function.StreamBridge;
send metodu
Gönderilecek topic ismi ve mesaj nesnesini alır
Örnek
Şeklen şöyle


Şöyle yaparız
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  cloud:
    stream:
      bindings:
        orderSubmissionOutput:
          destination: orderSubmitted.exchange
Açıklaması şöyle
The framework will automatically create the topic exchange “orderSubmitted.exchange” on RabbitMQ upon application initialization.
Şöyle yaparız
@RestController
@RequestMapping("/orders")
public class OrderRestController {

  static final String ORDER_SUBMISSION_OUTPUT = "orderSubmissionOutput";
    
  @Autowired
  private StreamBridge streamBridge;

  @PostMapping
  public ResponseEntity<Order> submitOrder(@RequestBody @Valid Order order) {
    Order orderToBeSubmitted = order.withSubmissionDate(Instant.now());
    streamBridge.send(ORDER_SUBMISSION_OUTPUT, orderToBeSubmitted);
    return ResponseEntity.ok(orderToBeSubmitted);
  }
}

Örnek
Şöyle yaparız. values-topic isimli topic'e string yazar.
@Slf4j
@RestController
public class ValueController {

  private StreamBridge streamBridge;

  public ValueController(StreamBridge streamBridge) {
    this.streamBridge = streamBridge;
  }

  @GetMapping("values/{value}")
  public ResponseEntity<String> values(@PathVariable String value) {
    log.info("Sending value {} to topic", value);
    streamBridge.send("values-topic", value);
    return ResponseEntity.ok("ok");
  }
}
Açıklaması şöyle
As you can see, there is no code or configuration in the Producer microservice that links it to RabbitMQ. The addition of the RabbitMQ binder in the dependency did all the bindings for us. This makes it very easy to switch the underlying messaging provider.
Örnek
Şöyle yaparız
@Component
public class KafkaProducer {

  @Autowired
  private StreamBridge streamBridge;

  @Scheduled(cron = "*/2 * * * * *")
  public void sendMessage(){
    streamBridge.send("producer-out-0",new Message("jack from Stream bridge"));
  }
}



Hiç yorum yok:

Yorum Gönder