I have an integration flow that sinks DML queries at the end.
I have a config file to log transactions:
logging.level.org.springframework.transaction.interceptor=TRACE
logging.level.org.springframework.transaction.support=DEBUG
The sinkSql method is called but there is no transaction log.
If I just call e.transactional(true) I get an error because there are two transaction managers (one is from the source database).
#Bean(name = SYBASE_TRAN_MANAGER)
public PlatformTransactionManager transactionManager(#Qualifier(SYBASE_DS) final DataSource sybaseDataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(sybaseDataSource);
return dataSourceTransactionManager;
}
#Bean
public TransactionInterceptor sybaseTransactionInterceptor(#Qualifier(SYBASE_TRAN_MANAGER) final TransactionManager tm) {
return new TransactionInterceptorBuilder(true)
.transactionManager(tm)
.isolation(Isolation.READ_COMMITTED)
.propagation(Propagation.REQUIRES_NEW)
.readOnly(false)
.build();
}
#Bean
public IntegrationFlow sinkSqlFlow(final TransactionInterceptor sybaseTransactionInterceptor) {
return IntegrationFlows.from(SYBASE_SINK_SQL)
.enrichHeaders(h -> h.header(MessageHeaders.ERROR_CHANNEL, SYBASE_ERROR))
.handle(this::sinkSql, e -> e.transactional(sybaseTransactionInterceptor))
.get();
}
public void sinkSql(final Message<?> message) {
//jdbcTemplate logic here
}
Not sure why is the question since TransactionAspectSupport does just this plain fallback if we don't provide an explicit TransactionManager to the interceptor configuration:
if (defaultTransactionManager == null) {
defaultTransactionManager = this.beanFactory.getBean(TransactionManager.class);
this.transactionManagerCache.putIfAbsent(
DEFAULT_TRANSACTION_MANAGER_KEY, defaultTransactionManager);
}
where that getBean(Class aClass) indeed is going to fail if several beans of type is present in the application context. So, what you did so far with a sybaseTransactionInterceptor bean definition is OK.
You can use an overloaded Java DSL method though:
/**
* Specify a {#link TransactionInterceptor} {#link Advice} with the provided
* {#code PlatformTransactionManager} and default
* {#link org.springframework.transaction.interceptor.DefaultTransactionAttribute}
* for the {#link MessageHandler}.
* #param transactionManager the {#link TransactionManager} to use.
* #param handleMessageAdvice the flag to indicate the target {#link Advice} type:
* {#code false} - regular {#link TransactionInterceptor}; {#code true} -
* {#link org.springframework.integration.transaction.TransactionHandleMessageAdvice}
* extension.
* #return the spec.
*/
public S transactional(TransactionManager transactionManager, boolean handleMessageAdvice) {
Although having your sink contract as void sinkSql(final Message<?> message), there is no need in that true: the transaction is going to be applied for a handleMessage() method which is really the end of your flow anyway.
Related
This question pertains directly to another question: Spring-Integration AbstractRequestHandlerAdvice with webflux/reactive: does this introduce a synchronous process?
The return result retrieved by the call from the advice handler to an http:outbound-gateway is either a Message<?> or a MessageBuilder (or perhaps only the latter).
public class MyLogger extends AbstractRequestHandlerAdvice {
// ...
#Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message(
{
// ... logging before the call ...
Object result = callback.execute();
// ... logging after the call ...
return result;
}
}
When migrating to webflux and hence to webflux:outbound-gateway, the advice handler is now retrieving a MonoMapFuseable type in the result. Is it possible to read the information from MonoMapFuseable in order to log the return payload without consuming definitively the result? I'm a bit of a loss at how to do this.
Thanks for any insights.
I am not a reactor expert, but you should be able to call share() on the returned mono; then subscribe to that mono to get a copy of the result.
/**
* Prepare a {#link Mono} which shares this {#link Mono} result similar to {#link Flux#shareNext()}.
* This will effectively turn this {#link Mono} into a hot task when the first
* {#link Subscriber} subscribes using {#link #subscribe()} API. Further {#link Subscriber} will share the same {#link Subscription}
* and therefore the same result.
* It's worth noting this is an un-cancellable {#link Subscription}.
* <p>
* <img class="marble" src="doc-files/marbles/shareForMono.svg" alt="">
*
* #return a new {#link Mono}
*/
public final Mono<T> share() {
I just tried it with this...
#Bean
ApplicationRunner runner() {
return args -> {
One<Object> one = Sinks.one();
Mono<Object> mono = one.asMono();
Mono<Object> mono1 = mono.share();
Mono<Object> mono2 = mono.share();
subsMono(mono1, 1);
subsMono(mono2, 2);
subsMono(mono, 0);
one.emitValue("foo", null);
};
}
private void subsMono(Mono mono, int i) {
mono.doOnNext(obj -> System.out.println(obj.toString() + i))
.subscribe();
}
foo1
foo2
foo0
From the Spring Integration documentation (https://docs.spring.io/spring-integration/docs/5.1.7.RELEASE/reference/html/#delayer) it is not clear to me what the messageGroupId in the DelayHandler means exactly and which value I have to set there exactly (is it arbitrary?). This value does not exist in the xml configuration, but does in the Java configuration.
#ServiceActivator(inputChannel = "input")
#Bean
public DelayHandler delayer() {
DelayHandler handler = new DelayHandler("delayer.messageGroupId"); // THIS constructor parameter is not clear to me
handler.setDefaultDelay(3_000L);
handler.setDelayExpressionString("headers['delay']");
handler.setOutputChannelName("output");
return handler;
}
It is explained in the JavaDocs of that constructor:
/**
* Create a DelayHandler with the given 'messageGroupId' that is used as 'key' for
* {#link MessageGroup} to store delayed Messages in the {#link MessageGroupStore}.
* The sending of Messages after the delay will be handled by registered in the
* ApplicationContext default
* {#link org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler}.
* #param messageGroupId The message group identifier.
* #see #getTaskScheduler()
*/
public DelayHandler(String messageGroupId) {
It is not required because the groupId is based on the required id attribute:
String id = element.getAttribute(ID_ATTRIBUTE);
if (!StringUtils.hasText(id)) {
parserContext.getReaderContext().error("The 'id' attribute is required.", element);
}
...
builder.addConstructorArgValue(id + ".messageGroupId");
It is really mentioned and explained a little bit in the docs: https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#delayer-namespace.
The value indeed is arbitrary, but it must be unique per your application, so different delayers don't steal messages from each other.
I defined my poller with a service activator with adviceChain like this:
#ServiceActivator(inputChannel = EVENT_CHANNEL,
adviceChain = {"globalLockAdvice"},
poller = #Poller(
maxMessagesPerPoll = "${event.poller.maxMessagesPerPoll:1}",
fixedDelay = "${event.poller.fixedDelay:1000}",
receiveTimeout = "${event.poller.receiveTimeout:1000}"))
public void handleEventMessage(Message<String> message) throws MessagingException {
...
}
#Component
public class GlobalLockAdvice implements ReceiveMessageAdvice {
private final LockConfiguration lockConfiguration;
public GlobalLockAdvice(LockConfiguration lockConfiguration) {
this.lockConfiguration = lockConfiguration;
}
#Override
public boolean beforeReceive(Object source) {
return lockConfiguration.isLeader();
}
#Override
public Message<?> afterReceive(Message<?> result, Object source) {
return result;
}
}
But beforeReceive is not called.
When debugging I see 'target' is a ServiceActivator class, resulting in skipping calling the beforeReceive:
#FunctionalInterface
public interface ReceiveMessageAdvice extends MethodInterceptor {
#Override
#Nullable
default Object invoke(MethodInvocation invocation) throws Throwable {
Object target = invocation.getThis();
if (!(target instanceof MessageSource) && !(target instanceof PollableChannel)) {
return invocation.proceed();
}
...
What am I doing wrong?
The advice chain on the service activator advises the message handler, not the channel polled by the poller.
To add an advice chain to the poller, you must define the poller as a PollerMetadata bean instead of using the #Poller annotation attributes. #Poller("metadata").
See the javadocs for #Poller.
/**
* Provides the {#link org.springframework.integration.scheduling.PollerMetadata} options
* for the Messaging annotations for polled endpoints. It is an analogue of the XML
* {#code <poller/>} element, but provides only simple attributes. If the
* {#link org.springframework.integration.scheduling.PollerMetadata} requires more options
* (e.g. Transactional and other Advices) or {#code initialDelay} etc, the
* {#link org.springframework.integration.scheduling.PollerMetadata} should be configured
* as a generic bean and its bean name can be specified as the {#code value} attribute of
* this annotation. In that case, the other attributes are not allowed.
* <p>
* Non-reference attributes support Property Placeholder resolutions.
Given I have IntegrationFlow and inbound adapter for AMQP queue:
#Bean
public IntegrationFlow readMessagesFlow(
ConnectionFactory rabbitConnectionFactory,
ObjectMapper jacksonObjectMapper) {
return IntegrationFlows.from(
Amqp.inboundAdapter(rabbitConnectionFactory, QUEUE)
.messageConverter(new Jackson2JsonMessageConverter(jacksonObjectMapper))
)
.log(INFO, AMQP_LOGGER_CATEGORY)
.get();
}
When some external system sends a message with JSON body, I found they use __TypeId__=THEIR_INTERNAL_CLASS.
I would like to map JSON body to my own class.
Currently, it fails on ClassCastException because of THEIR_INTERNAL_CLASS not being available.
How can I tell Jackson2JsonMessageConverter to use my own class?
This is one way how to do it:
Jackson2JsonMessageConverter messageConverter = new Jackson2JsonMessageConverter(jacksonObjectMapper);
DefaultClassMapper defaultClassMapper = new DefaultClassMapper();
defaultClassMapper.setDefaultType(MyOwnClass.class);
messageConverter.setClassMapper(defaultClassMapper);
and use messageConverter in Amqp.inboundAdapter
See this method of converter:
/**
* Set the precedence for evaluating type information in message properties.
* When using {#code #RabbitListener} at the method level, the framework attempts
* to determine the target type for payload conversion from the method signature.
* If so, this type is provided in the
* {#link MessageProperties#getInferredArgumentType() inferredArgumentType}
* message property.
* <p> By default, if the type is concrete (not abstract, not an interface), this will
* be used ahead of type information provided in the {#code __TypeId__} and
* associated headers provided by the sender.
* <p> If you wish to force the use of the {#code __TypeId__} and associated headers
* (such as when the actual type is a subclass of the method argument type),
* set the precedence to {#link Jackson2JavaTypeMapper.TypePrecedence#TYPE_ID}.
* #param typePrecedence the precedence.
* #see DefaultJackson2JavaTypeMapper#setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence)
*/
public void setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence typePrecedence) {
and here are docs on the matter: https://docs.spring.io/spring-amqp/docs/2.2.11.RELEASE/reference/html/#json-message-converter
I have a spring integration flow for post message:
#Bean
public IntegrationFlow httpPost() {
return IntegrationFlows
.from("requestChannel")
.handle(Http.outboundGateway("http://uri")
.httpMethod(HttpMethod.POST)
.extractPayload(true))
.get();
}
How to change code to make http://uri dynamic or parametrized?
/**
* Create an {#link HttpMessageHandlerSpec} builder for request-reply gateway
* based on provided {#code Function} to evaluate target {#code uri} against request message.
* #param uriFunction the {#code Function} to evaluate {#code uri} at runtime.
* #param <P> the expected payload type.
* #return the HttpMessageHandlerSpec instance
*/
public static <P> HttpMessageHandlerSpec outboundGateway(Function<Message<P>, ?> uriFunction) {
return outboundGateway(new FunctionExpression<>(uriFunction));
}
so
.handle(Http.outboundGateway(message -> message.getHeaders().get("someHeaderWithURI"))
Alternativelt, you can use a SpEL expression.