当前位置: 首页>>代码示例>>Java>>正文


Java SubscribableChannel.subscribe方法代码示例

本文整理汇总了Java中org.springframework.messaging.SubscribableChannel.subscribe方法的典型用法代码示例。如果您正苦于以下问题:Java SubscribableChannel.subscribe方法的具体用法?Java SubscribableChannel.subscribe怎么用?Java SubscribableChannel.subscribe使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.springframework.messaging.SubscribableChannel的用法示例。


在下文中一共展示了SubscribableChannel.subscribe方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: run

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@Override
public void run(ApplicationArguments args) throws Exception {
	logger.info("Consumer running with binder {}", binder);
	SubscribableChannel consumerChannel = new ExecutorSubscribableChannel();
	consumerChannel.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			messagePayload = (String) message.getPayload();
			logger.info("Received message: {}", messagePayload);
		}
	});
	String group = null;

	if (args.containsOption("group")) {
		group = args.getOptionValues("group").get(0);
	}

	binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel,
			new ConsumerProperties());
	isBound = true;
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-consul,代码行数:22,代码来源:TestConsumer.java

示例2: createConsumerEndpoint

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@Override
protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ConsumerProperties properties)
		throws Exception {
	ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
	SubscribableChannel siBinderInputChannel = ((SpringIntegrationConsumerDestination)destination).getChannel();

	IntegrationMessageListeningContainer messageListenerContainer = new IntegrationMessageListeningContainer();
	IntegrationBinderInboundChannelAdapter adapter = new IntegrationBinderInboundChannelAdapter(messageListenerContainer);

	String groupName = StringUtils.hasText(group) ? group : "anonymous";
	ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, groupName, properties);
	if (properties.getMaxAttempts() > 1) {
		adapter.setRetryTemplate(buildRetryTemplate(properties));
		adapter.setRecoveryCallback(errorInfrastructure.getRecoverer());
	}
	else {
		adapter.setErrorMessageStrategy(errorMessageStrategy);
		adapter.setErrorChannel(errorInfrastructure.getErrorChannel());
	}

	siBinderInputChannel.subscribe(messageListenerContainer);

	return adapter;
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-stream,代码行数:25,代码来源:SpringIntegrationChannelBinder.java

示例3: receive

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@StreamListener
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output1,
		@Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT) final MessageChannel output2) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			if (message.getHeaders().get("output").equals("output1")) {
				output1.send(org.springframework.messaging.support.MessageBuilder
						.withPayload(message.getPayload().toString().toUpperCase()).build());
			}
			else if (message.getHeaders().get("output").equals("output2")) {
				output2.send(org.springframework.messaging.support.MessageBuilder
						.withPayload(message.getPayload().toString().toLowerCase()).build());
			}
		}
	});
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-stream,代码行数:19,代码来源:StreamListenerHandlerMethodTests.java

示例4: test

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@Test
public void test() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	Properties properties = new Properties();
	properties.put("prefix","foo");
	properties.put("suffix","bar");
	context.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("options", properties));
	context.register(TestConfiguration.class);
	context.refresh();

	MessageChannel input = context.getBean("input", MessageChannel.class);
	SubscribableChannel output = context.getBean("output", SubscribableChannel.class);

	final AtomicBoolean handled = new AtomicBoolean();
	output.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			handled.set(true);
			assertEquals("foohellobar", message.getPayload());
		}
	});
	input.send(new GenericMessage<String>("hello"));
	assertTrue(handled.get());
}
 
开发者ID:spring-projects,项目名称:spring-xd-samples,代码行数:25,代码来源:ModuleConfigurationTest.java

示例5: sendAndReceive

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@Test
public void sendAndReceive() {

	SubscribableChannel channel = new ExecutorSubscribableChannel(this.executor);
	channel.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
			replyChannel.send(new GenericMessage<String>("response"));
		}
	});

	String actual = this.template.convertSendAndReceive(channel, "request", String.class);
	assertEquals("response", actual);
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:16,代码来源:GenericMessagingTemplateTests.java

示例6: receive

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@StreamListener
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			output.send(MessageBuilder.withPayload(message.getPayload().toString().toUpperCase()).build());
		}
	});
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-stream,代码行数:11,代码来源:StreamListenerWithAnnotatedInputOutputArgsTests.java

示例7: testProducerErrorChannel

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void testProducerErrorChannel() throws Exception {
	KinesisTestBinder binder = getBinder();

	final RuntimeException putRecordException = new RuntimeException("putRecordRequestEx");
	final AtomicReference<Object> sent = new AtomicReference<>();
	AmazonKinesisAsync amazonKinesisMock = mock(AmazonKinesisAsync.class);
	BDDMockito.given(amazonKinesisMock.putRecordAsync(any(PutRecordRequest.class), any(AsyncHandler.class)))
			.willAnswer((Answer<Future<PutRecordResult>>) invocation -> {
				PutRecordRequest request = invocation.getArgument(0);
				sent.set(request.getData());
				AsyncHandler<?, ?> handler = invocation.getArgument(1);
				handler.onError(putRecordException);
				return mock(Future.class);
			});

	new DirectFieldAccessor(binder.getBinder()).setPropertyValue("amazonKinesis", amazonKinesisMock);

	ExtendedProducerProperties<KinesisProducerProperties> producerProps = createProducerProperties();
	producerProps.setErrorChannelEnabled(true);
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			createProducerBindingProperties(producerProps));
	Binding<MessageChannel> producerBinding = binder.bindProducer("ec.0", moduleOutputChannel, producerProps);

	ApplicationContext applicationContext = TestUtils.getPropertyValue(binder.getBinder(),
			"applicationContext", ApplicationContext.class);
	SubscribableChannel ec = applicationContext.getBean("ec.0.errors", SubscribableChannel.class);
	final AtomicReference<Message<?>> errorMessage = new AtomicReference<>();
	final CountDownLatch latch = new CountDownLatch(1);
	ec.subscribe(message -> {
		errorMessage.set(message);
		latch.countDown();
	});

	String messagePayload = "oops";
	moduleOutputChannel.send(new GenericMessage<>(messagePayload.getBytes()));

	assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
	assertThat(errorMessage.get()).isInstanceOf(ErrorMessage.class);
	assertThat(errorMessage.get().getPayload()).isInstanceOf(AwsRequestFailureException.class);
	AwsRequestFailureException exception = (AwsRequestFailureException) errorMessage.get().getPayload();
	assertThat(exception.getCause()).isSameAs(putRecordException);
	assertThat(((PutRecordRequest) exception.getRequest()).getData()).isSameAs(sent.get());
	producerBinding.unbind();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-stream-binder-aws-kinesis,代码行数:47,代码来源:KinesisBinderTests.java

示例8: sendAndReceiveTimeout

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@Test
public void sendAndReceiveTimeout() throws InterruptedException {

	final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
	final CountDownLatch latch = new CountDownLatch(1);

	this.template.setReceiveTimeout(1);
	this.template.setThrowExceptionOnLateReply(true);

	SubscribableChannel channel = new ExecutorSubscribableChannel(this.executor);
	channel.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			try {
				Thread.sleep(500);
				MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
				replyChannel.send(new GenericMessage<String>("response"));
				failure.set(new IllegalStateException("Expected exception"));
			}
			catch (InterruptedException e) {
				failure.set(e);
			}
			catch (MessageDeliveryException ex) {
				String expected = "Reply message received but the receiving thread has exited due to a timeout";
				String actual = ex.getMessage();
				if (!expected.equals(actual)) {
					failure.set(new IllegalStateException("Unexpected error: '" + actual + "'"));
				}
			}
			finally {
				latch.countDown();
			}
		}
	});

	assertNull(this.template.convertSendAndReceive(channel, "request", String.class));
	assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));

	if (failure.get() != null) {
		throw new AssertionError(failure.get());
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:43,代码来源:GenericMessagingTemplateTests.java

示例9: testDlqGuts

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
private void testDlqGuts(boolean withRetry) throws Exception {
	AbstractKafkaTestBinder binder = getBinder();

	ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();
	producerProperties.getExtension().setHeaderPatterns(new String[]{MessageHeaders.CONTENT_TYPE});

	DirectChannel moduleOutputChannel = createBindableChannel("output",
			createProducerBindingProperties(producerProperties));
	ExtendedConsumerProperties<KafkaConsumerProperties> consumerProperties = createConsumerProperties();

	consumerProperties.setMaxAttempts(withRetry ? 2 : 1);
	consumerProperties.setBackOffInitialInterval(100);
	consumerProperties.setBackOffMaxInterval(150);
	consumerProperties.getExtension().setEnableDlq(true);
	consumerProperties.getExtension().setAutoRebalanceEnabled(false);

	DirectChannel moduleInputChannel = createBindableChannel("input", createConsumerBindingProperties(consumerProperties));

	QueueChannel dlqChannel = new QueueChannel();
	FailingInvocationCountingMessageHandler handler = new FailingInvocationCountingMessageHandler();
	moduleInputChannel.subscribe(handler);

	long uniqueBindingId = System.currentTimeMillis();

	String producerName = "dlqTest." + uniqueBindingId + ".0";
	Binding<MessageChannel> producerBinding = binder.bindProducer(producerName,
			moduleOutputChannel, producerProperties);
	Binding<MessageChannel> consumerBinding = binder.bindConsumer(producerName,
			"testGroup", moduleInputChannel, consumerProperties);

	ExtendedConsumerProperties<KafkaConsumerProperties> dlqConsumerProperties = createConsumerProperties();
	dlqConsumerProperties.setMaxAttempts(1);

	ApplicationContext context = TestUtils.getPropertyValue(binder.getBinder(), "applicationContext",
			ApplicationContext.class);
	SubscribableChannel boundErrorChannel = context
			.getBean(producerName + ".testGroup.errors-0", SubscribableChannel.class);
	SubscribableChannel globalErrorChannel = context.getBean("errorChannel", SubscribableChannel.class);
	final AtomicReference<Message<?>> boundErrorChannelMessage = new AtomicReference<>();
	final AtomicReference<Message<?>> globalErrorChannelMessage = new AtomicReference<>();
	final AtomicBoolean hasRecovererInCallStack = new AtomicBoolean(!withRetry);
	boundErrorChannel.subscribe(message -> {
		boundErrorChannelMessage.set(message);
		String stackTrace = Arrays.toString(new RuntimeException().getStackTrace());
		hasRecovererInCallStack.set(stackTrace.contains("ErrorMessageSendingRecoverer"));
	});
	globalErrorChannel.subscribe(globalErrorChannelMessage::set);

	Binding<MessageChannel> dlqConsumerBinding = binder.bindConsumer(
			"error.dlqTest." + uniqueBindingId + ".0.testGroup", null, dlqChannel, dlqConsumerProperties);
	binderBindUnbindLatency();
	String testMessagePayload = "test." + UUID.randomUUID().toString();
	Message<byte[]> testMessage = MessageBuilder.withPayload(testMessagePayload.getBytes()).build();
	moduleOutputChannel.send(testMessage);

	Message<?> receivedMessage = receive(dlqChannel, 3);
	assertThat(receivedMessage).isNotNull();
	assertThat(receivedMessage.getPayload()).isEqualTo(testMessagePayload.getBytes());
	assertThat(handler.getInvocationCount()).isEqualTo(consumerProperties.getMaxAttempts());
	assertThat(receivedMessage.getHeaders().get(KafkaMessageChannelBinder.X_ORIGINAL_TOPIC))
			.isEqualTo(producerName.getBytes(StandardCharsets.UTF_8));
	assertThat(new String((byte[]) receivedMessage.getHeaders().get(KafkaMessageChannelBinder.X_EXCEPTION_MESSAGE)))
			.startsWith("failed to send Message to channel 'input'");
	assertThat(receivedMessage.getHeaders().get(KafkaMessageChannelBinder.X_EXCEPTION_STACKTRACE))
			.isNotNull();
	binderBindUnbindLatency();

	// verify we got a message on the dedicated error channel and the global (via bridge)
	assertThat(boundErrorChannelMessage.get()).isNotNull();
	assertThat(globalErrorChannelMessage.get()).isNotNull();
	assertThat(hasRecovererInCallStack.get()).isEqualTo(withRetry);

	dlqConsumerBinding.unbind();
	consumerBinding.unbind();
	producerBinding.unbind();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-stream-binder-kafka,代码行数:78,代码来源:KafkaBinderTests.java

示例10: subscribe

import org.springframework.messaging.SubscribableChannel; //导入方法依赖的package包/类
public void subscribe(String name, SubscribableChannel outboundBindTarget) {
	this.outputs.put(bindings.getInput(name), name);
	outboundBindTarget.subscribe(message -> this.append(name, message));
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-function,代码行数:5,代码来源:MessageController.java


注:本文中的org.springframework.messaging.SubscribableChannel.subscribe方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。