Java Code Examples for org.springframework.cloud.stream.annotation.StreamListener

The following examples show how to use org.springframework.cloud.stream.annotation.StreamListener. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@StreamListener(BillingMessageChannels.BOOKING_ORDER_INPUT)
public void consumeBookingOrder(BookingOrder bookingOrder) {
  LOG.info("Received BookingOrder: {}", bookingOrder);
  // TODO: Add logic if booking order is already processed or in process
  long randomId = RANDOM.nextLong();
  if (randomId < 0) {
    LOG.info("\n\n\nGenerate failed billing event for negative randomId for testing\n\n\n");
    billingEventHandler.produceBillingEvent(null, bookingOrder.getName().toString());
  } else {
    String id = String.valueOf(randomId);
    LocalDate nowDate = LocalDate.now();
    LocalTime nowTime = LocalTime.now();
    try {
      Billing billing = new Billing(id, "bill-" + id,
          bookingOrder.getRestaurantId().toString(), bookingOrder.getName().toString(),
          bookingOrder.getTableId().toString(), bookingOrder.getUserId().toString(),
          nowDate, nowTime);
      billingService.add(billing);
      billingEventHandler.produceBillingEvent(billing, bookingOrder.getName().toString());
    } catch (Exception ex) {
      billingEventHandler.produceBillingEvent(null, bookingOrder.getName().toString());
    }
  }
}
 
Example 2
@StreamListener(BookingMessageChannels.BILLING_INPUT)
public void consumeBilling(BillingBookingResponse billingResponse) {
  try {
    HeaderName<String> headerName = HeaderName.forName("billingStatus");
    Map<HeaderName<?>, Object> headers = ImmutableMap
        .of(headerName, billingResponse.getStatus().toString());

    MessageStream messageStream = SagaConfig.messageStreamMap.get(billingResponse.getBookingId().toString());
    LOG.info("\n\n\n   Received billing event: {}\n   messageStream: {}\n\n", billingResponse, messageStream);
    messageStream.addMessage(new BillingVO(billingResponse.getBillId().toString(),
            billingResponse.getName().toString(),
            billingResponse.getRestaurantId().toString(), billingResponse.getBookingId().toString(),
            billingResponse.getTableId().toString(), "User", LocalDate.now(), LocalTime.now()),
        headers);
  } catch (Exception ex) {
    ex.printStackTrace();
    LOG.error(ex.getMessage());
  }
}
 
Example 3
/**
 * Log the change event received from the organization service and update 
 * the Redis cache.
 * 
 * @param  orgChange
 *         The organization change event.
 */
@StreamListener(Sink.INPUT)
public void loggerSink(OrganizationChangeModel orgChange) {
	logger.info("Received an event for organization id {}", orgChange.getOrganizationId());
	        
    switch(orgChange.getAction()){
        case "GET":
            logger.debug("Received a GET event from the organization service for organization id {}", orgChange.getOrganizationId());
            break;
        case "SAVE":
            logger.debug("Received a SAVE event from the organization service for organization id {}", orgChange.getOrganizationId());
            break;
        case "UPDATE":
            logger.debug("Received a UPDATE event from the organization service for organization id {}", orgChange.getOrganizationId());
            organizationRedisRepository.deleteOrganization(orgChange.getOrganizationId());
            break;
        case "DELETE":
            logger.debug("Received a DELETE event from the organization service for organization id {}", orgChange.getOrganizationId());
            organizationRedisRepository.deleteOrganization(orgChange.getOrganizationId());
            break;
        default:
            logger.error("Received an UNKNOWN event from the organization service of type {}", orgChange.getType());
            break;
    }
}
 
Example 4
@StreamListener( Sink.INPUT )
public void processNotification( final String json ) {
    log.debug( "processNotification : enter" );

    Tuple event = TupleBuilder.fromString( json );

    Assert.hasText( event.getString( "eventType" ), "eventType not set" );
    Assert.hasText( event.getString( "boardUuid" ), "boardUuid not set" );
    Assert.hasText( event.getString( "occurredOn" ), "occurredOn not set" );

    String eventType = event.getString( "eventType" );
    if( eventType.equals( "BoardInitialized" ) ) {
        log.debug( "processNotification : exit, no board should exist in cache if 'BoardInitialized' event is received" );

        return;
    }

    this.service.uncacheTarget( UUID.fromString( event.getString( "boardUuid" ) ) );

    log.debug( "processNotification : exit" );
}
 
Example 5
Source Project: inventory-hub-java-on-azure   Source File: InventoryHub.java    License: MIT License 6 votes vote down vote up
@StreamListener(target=Sink.INPUT)
public void receiveTransaction(String transactionMessage) {

       System.out.println("message is: " + transactionMessage);

       try
       {
           transaction = objectMapper.readValue(
               new String(transactionMessage.getBytes(), "UTF8"), Transaction.class);

           TransactionsController.transactions.addFirst(transaction);

           System.out.println("=== event data ===\n" + transaction.toString());

       } catch (Exception e)
       {
           System.out.println("Processing failed for an event: " + e.toString());
		e.printStackTrace();
       }

   }
 
Example 6
@Override
@StreamListener(Processor.INPUT)
@Output(Processor.OUTPUT)
public Flux<UsersStatisticVM> updateStatistic(Flux<MessageResponse> messagesFlux) {
    return messagesFlux.map(MessageMapper::toDomainUnit)
                       .transform(messageRepository::saveAll)
                       .retryBackoff(Long.MAX_VALUE, Duration.ofMillis(500))
                       .onBackpressureLatest()
                       .concatMap(e -> this.doGetUserStatistic(), 1)
                       .onErrorContinue((t, e) -> {});
}
 
Example 7
Source Project: training   Source File: ReservationServiceApplication.java    License: Apache License 2.0 5 votes vote down vote up
@StreamListener
public void incomingMessages(@Input(Sink.INPUT) Flux<String> rnPublisher) {
	rnPublisher
			.map(rn -> new Reservation(null, rn))
			.flatMap(this.rr::save)
			.subscribe(r -> System.out.println("received and saved " + r.getId() + " with " + r.getReservationName() + "."));
}
 
Example 8
Source Project: spring-cloud-gray   Source File: MessageAckListener.java    License: Apache License 2.0 5 votes vote down vote up
@StreamListener(TestSourceInput.INPUT)
    public void receive(Object msg, @Header(AmqpHeaders.CHANNEL) Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        log.info("Received3:" + msg);
        boolean request = false;//true=重新发送
//        channel.basicReject(deliveryTag, request);
        channel.basicAck(deliveryTag, false);
    }
 
Example 9
@StreamListener(Sink.INPUT)
public void receive(Message message) {
    //模拟消费异常
    String consumeError = (String)message.getHeaders().get("consumeError");
    if ("1".equals(consumeError)) {
        System.err.println("============Exception:积分进程挂了,消费消息失败");
        //模拟插入订单后服务器挂了,没有commit事务消息
        throw new RuntimeException("积分服务器挂了");
    }

    System.out.println("============收到订单信息,增加积分:" + message);
}
 
Example 10
Source Project: spring-cloud-study   Source File: LogMessageListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过 MyProcessor.MESSAGE_INPUT 接收消息
 * 然后通过 SendTo 将处理后的消息发送到 MyProcessor.LOG_FORMAT_OUTPUT
 * @param message
 * @return
 */
@StreamListener(MyProcessor.MESSAGE_INPUT)
@SendTo(MyProcessor.LOG_FORMAT_OUTPUT)
public String processLogMessage(String message) {
    log.info("接收到原始消息:" + message);
    return "「" + message +"」";
}
 
Example 11
Source Project: Dodder   Source File: TorrentDownloadServiceApplication.java    License: MIT License 5 votes vote down vote up
@StreamListener("download-message-in")
public void handleMessage(DownloadMsgInfo msgInfo) {
	//submit to blocking executor
	try {
		blockingExecutor.execute(new DownloadTask(msgInfo));
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
 
Example 12
Source Project: Dodder   Source File: TorrentStoreServiceApplication.java    License: MIT License 5 votes vote down vote up
@StreamListener("torrent-message-in")
public void handleTorrent(Message<Torrent> message) {
	try {
		Acknowledgment acknowledgment = message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class);
		Torrent torrent = message.getPayload();
		log.debug("Save torrent to MongoDB, info hash is {}", torrent.getInfoHash());
		torrentService.upsert(torrent);
		//no error, execute acknowledge
		if (acknowledgment != null) {
			acknowledgment.acknowledge();
		}
	} catch (Exception e) {
		log.error("Insert or update torrent error: {}", e);
	}
}
 
Example 13
Source Project: Dodder   Source File: TorrentStoreServiceApplication.java    License: MIT License 5 votes vote down vote up
@StreamListener("index-message-in")
public void indexTorrent(Message<Torrent> message) {
	try {
		Acknowledgment acknowledgment = message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class);
		Torrent torrent = message.getPayload();
		log.debug("Index torrent to elasticsearch, info hash is {}", torrent.getInfoHash());
		torrentService.index(torrent);
		//no error, execute acknowledge
		if (acknowledgment != null) {
			acknowledgment.acknowledge();
		}
	} catch (Exception e) {
		log.error("Index torrent error: {}", e);
	}
}
 
Example 14
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Recommendation> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Recommendation recommendation = event.getData();
        LOG.info("Create recommendation with ID: {}/{}", recommendation.getProductId(), recommendation.getRecommendationId());
        recommendationService.createRecommendation(recommendation);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete recommendations with ProductID: {}", productId);
        recommendationService.deleteRecommendations(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 15
@StreamListener
public void listen(
    @Input(MessagesSource.INPUT) Flux<MessageResponse> messages,
 @Input(StatisticSource.INPUT) Flux<UsersStatisticVM> statistic
) {
    messages.map(MessageMapper::toViewModelUnit)
            .subscribeWith(messagesStream);
 statistic.subscribeWith(statisticStream);
}
 
Example 16
Source Project: training   Source File: ReservationServiceApplication.java    License: Apache License 2.0 5 votes vote down vote up
@StreamListener
public void incomingMessages(@Input(Sink.INPUT) Flux<String> rnPublisher) {
	rnPublisher
			.map(rn -> new Reservation(null, rn))
			.flatMap(this.rr::save)
			.subscribe(r -> System.out.println("received and saved " + r.getId() + " with " + r.getReservationName() + "."));
}
 
Example 17
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Recommendation> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Recommendation recommendation = event.getData();
        LOG.info("Create recommendation with ID: {}/{}", recommendation.getProductId(), recommendation.getRecommendationId());
        recommendationService.createRecommendation(recommendation);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete recommendations with ProductID: {}", productId);
        recommendationService.deleteRecommendations(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 18
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Review> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Review review = event.getData();
        LOG.info("Create review with ID: {}/{}", review.getProductId(), review.getReviewId());
        reviewService.createReview(review);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete reviews with ProductID: {}", productId);
        reviewService.deleteReviews(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 19
Source Project: ddd-with-spring   Source File: IncomingMessageListener.java    License: Apache License 2.0 5 votes vote down vote up
@StreamListener(CreditAgencyChannels.APPLICATION_SUBMITTED)
public void receiveApplicationSubmission(@Payload ApplicationSubmittedEvent applicationSubmittedEvent) {

	System.out.println("received " + applicationSubmittedEvent.getFirstApplicant().toString());
	Applicant applicant = applicationSubmittedEvent.getFirstApplicant();
	personRatingQueryService.ratePerson(applicant.getFirstName(),
			applicant.getLastName(),
			applicant.getAddress().getStreet(),
			applicant.getAddress().getPostCode(),
			applicant.getAddress().getCity());
}
 
Example 20
Source Project: springboot-kafka-avro   Source File: KafkaStreamsApp.java    License: MIT License 5 votes vote down vote up
@StreamListener
@SendTo(USERS_FILTERED)
KStream<String, User> processUsers(@Input(USERS) KStream<String, User> inputStream) {
  return inputStream
      .filter((key, user) -> user.getAge() < 40)
      .mapValues(user -> new User(user.getName().toUpperCase(), user.getAge()))
      .peek((key, user) -> log.info("New entry in filtered stream => Key = " + key + " Value = " + user));
}
 
Example 21
@StreamListener(Sink.INPUT)
public void receiveOrderlyMsg(String receiveMsg) {
	if (count.getAndIncrement() <= 5) {
           throw new RuntimeException("Oops: " + receiveMsg);
	}
	else {
		log.info("receiveOrderlyMsg: " + receiveMsg);
	}
}
 
Example 22
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Recommendation> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Recommendation recommendation = event.getData();
        LOG.info("Create recommendation with ID: {}/{}", recommendation.getProductId(), recommendation.getRecommendationId());
        recommendationService.createRecommendation(recommendation);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete recommendations with ProductID: {}", productId);
        recommendationService.deleteRecommendations(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 23
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Review> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Review review = event.getData();
        LOG.info("Create review with ID: {}/{}", review.getProductId(), review.getReviewId());
        reviewService.createReview(review);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete reviews with ProductID: {}", productId);
        reviewService.deleteReviews(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 24
Source Project: rocketmq-binder-demo   Source File: SendToService.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * @SendTo is useful with @StreamListener
    */

@StreamListener(Sink.INPUT)
@SendTo(SendToApplication.TEMP_INPUT)
public String receive(String receiveMsg) {
	System.out.println("receive: " + receiveMsg);
	return "handle by SendTo(" + receiveMsg + ")";
}
 
Example 25
@StreamListener(Sink.INPUT)
public void receiveConcurrentlyMsg(String receiveMsg) {
    log.info("invoke: " + count.get());
	if (count.getAndIncrement() <= 5) {
           throw new RuntimeException("Oops: " + receiveMsg);
	}
	else {
		log.info("receiveOrderlyMsg: " + receiveMsg);
	}
}
 
Example 26
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Recommendation> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Recommendation recommendation = event.getData();
        LOG.info("Create recommendation with ID: {}/{}", recommendation.getProductId(), recommendation.getRecommendationId());
        recommendationService.createRecommendation(recommendation);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete recommendations with ProductID: {}", productId);
        recommendationService.deleteRecommendations(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 27
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Recommendation> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Recommendation recommendation = event.getData();
        LOG.info("Create recommendation with ID: {}/{}", recommendation.getProductId(), recommendation.getRecommendationId());
        recommendationService.createRecommendation(recommendation);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete recommendations with ProductID: {}", productId);
        recommendationService.deleteRecommendations(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 28
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Review> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Review review = event.getData();
        LOG.info("Create review with ID: {}/{}", review.getProductId(), review.getReviewId());
        reviewService.createReview(review);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete reviews with ProductID: {}", productId);
        reviewService.deleteReviews(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 29
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Product> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Product product = event.getData();
        LOG.info("Create product with ID: {}", product.getProductId());
        productService.createProduct(product);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete recommendations with ProductID: {}", productId);
        productService.deleteProduct(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}
 
Example 30
@StreamListener(target = Sink.INPUT)
public void process(Event<Integer, Recommendation> event) {

    LOG.info("Process message created at {}...", event.getEventCreatedAt());

    switch (event.getEventType()) {

    case CREATE:
        Recommendation recommendation = event.getData();
        LOG.info("Create recommendation with ID: {}/{}", recommendation.getProductId(), recommendation.getRecommendationId());
        recommendationService.createRecommendation(recommendation);
        break;

    case DELETE:
        int productId = event.getKey();
        LOG.info("Delete recommendations with ProductID: {}", productId);
        recommendationService.deleteRecommendations(productId);
        break;

    default:
        String errorMessage = "Incorrect event type: " + event.getEventType() + ", expected a CREATE or DELETE event";
        LOG.warn(errorMessage);
        throw new EventProcessingException(errorMessage);
    }

    LOG.info("Message processing done!");
}