I have a Spring-Integration TCP server with request and response and it works correctly. Well now I have to add a new layer to my application.
I have to put my message to an eh-cache db and then send back the ACK. Currently I have only a tcp clients but in the future I will have other sources, as the schema below.
Now the question is:
Can I configure this behavior using Spring-Integration?
I know that I can take the message on my ‘importService’ and put it on my eh-cache writing a code in this way:
public MyMessage handler(MyMessage message) {
try {
myCache.put(mykey, message)
} catch (Exception e) {
logger.error("unable to update" + e);
}
return message;
}
but I think it is not properly correct, and I was just wondering if I can configure my spring configuration file and add another end-point in order to create a chain.
My current config-file is:
<int-ip:tcp-connection-factory id="serverTcpConFact" type="server" port="5566" using-nio="false" single-use="false"
so-receive-buffer-size="8192"
so-send-buffer-size="8192"
so-tcp-no-delay="true"
task-executor="myTaskExecutor"
deserializer="serializer"
serializer="serializer"/>
<int-ip:tcp-inbound-channel-adapter id="tcpInboundAdapter"
channel="tcpInbound"
connection-factory="serverTcpConFact" />
<int:channel id="tcpInbound" />
<int:service-activator
output-channel="tcpOutbound"
input-channel="tcpInbound"
ref="importService"
method="handler" />
<bean id="importService" class="com.MyImportService" />
<int:channel id="tcpOutbound" />
<int-ip:tcp-inbound-gateway id="mygateway"
request-channel="tcpInbound"
reply-channel="tcpOutbound"
reply-timeout="6"/>
<int-ip:tcp-outbound-channel-adapter id="tcpOutboundAdapter"
channel="tcpOutbound"
connection-factory="serverTcpConFact" />
I was looking the public examples but I didn’t find an eh-cache example and a chain example.
Thank you !!
Well, looks like it just enough to move you Cache logic to the ChannelInterceptor:
<int:channel id="tcpInbound">
<int:interceptors>
<bean class="com.my.proj.si.CachePutChannelInterceptor"
</int:interceptors>
</int:channel>
And use this interceptor from any place when you need to use Cache.
Related
I try to use Spring Integration and don't find in doc some info about chain threads. I have xml:
<task:executor
id="worker"
pool-size="5"
queue-capacity="5"
rejection-policy="CALLER_RUNS"/>
<int:channel id="inputChannel" datatype="javax.xml.bind.JAXBElement">
<int:dispatcher task-executor="worker"/>
</int:channel>
<int:chain input-channel="inputChannel" id="someChain">
<int-ws:header-enricher>
<int-ws:soap-action value="${someValue}"/>
</int-ws:header-enricher>
<int:header-enricher>
<int:header name="url" value="${someUri}"/>
</int:header-enricher>
<int-ws:outbound-gateway uri="${someUri}"
ignore-empty-responses="true"
requires-reply="true"
marshaller="someMarshaller"
interceptors="someMessageInterceptors">
<int-ws:request-handler-advice-chain>
<ref bean="integrationInterceptor" />
</int-ws:request-handler-advice-chain>
</int-ws:outbound-gateway>
</int:chain>
And my question: Will all endpoints in that chain work consequentially but all in separate threads? Will gateway response and request work in separate threads? Can i use ThreadLocal for save some info in one chain endpoint and use that info in next endpoint ot that chain?
Yes, each component in the chain will run on the same thread.
Yes, you can use ThreadLocals to convey data between components, but often message headers are used for that purpose instead.
I have already created a simple tcp server with spring integration which keeps a connection alive and responses to each request during the connection.
In that requestMethod, I'm also able to read the MessageHeder to get the connectionId.
Now I want to send messages from the server to the client.
As far as i understood the documentation i need to put the connectionid in the MessageHeader and then send the message. But I can't figure out how to do the latter one. I have the Message ready but how do i send/push it out?
Here is my xml-configuration:
<bean id="lfSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer"/>
<int-ip:tcp-connection-factory
id="socketserver"
type="server"
port="30124"
using-nio="true"
deserializer="lfSerializer"
serializer="lfSerializer"
single-use="false"/>
<int-ip:tcp-inbound-channel-adapter id="inboundServer"
channel="inputChannel"
connection-factory="socketserver"/>
<int-ip:tcp-outbound-channel-adapter id="outboundServer"
channel="outputChannel"
connection-factory="socketserver"
/>
<int:channel id="inputChannel">
<int:interceptors>
<int:wire-tap channel="logger"/>
</int:interceptors>
</int:channel>
<int:channel id="outputChannel">
<int:interceptors>
<int:wire-tap channel="logger"/>
</int:interceptors>
</int:channel>
<int:logging-channel-adapter id="logger" level="DEBUG" log-full-message="true"/>
<int:service-activator input-channel="inputChannel"
output-channel="outputChannel"
ref="echoService"
method="test"/>
<bean id="echoService"
class="com.examples.EchoService" />
I also tried to create a bean and another serviceactivator for output, then autowired that bean and called it's "send" method, but I don't know what to implement in that send-method to send out a message.
If it's a simple request/response scenario use an inbound gateway instead of channel adapters and the framework will take care of the correlation for you. This is used in the sample app. Simply have your POJO method return the reply payload.
If you want to send arbitrary messages to the client (i.e. NOT request/reply but, say, in, out, out, in, out, out, out etc) then, yes, you need to build the messages yourself, inserting the ip_connectionId header.
To send them, there are several options:
Inject outputChannel into your code
#Autowired
private MessageChannel outputChannel;
Use a MessagingTemplate to send to the channel (or simply call its send(Message<?> message) method directly).
Or
Use a MessagingGateway with a void return method and inject the gateway into your code.
EDIT:
Note, that if you want to start sending messages before receiving anything, you can obtain the connection id via the connection opened event.
I am using Spring Integration 4.1.2.
In the program flow, at the end of a process I need to send an email. I am using the following:
<int:payload-type-router input-channel="response.in">
<int:mapping type="java.lang.String" channel="response.out"/>
<int:mapping type="org.springframework.mail.SimpleMailMessage" channel="mail.out"/>
</int:payload-type-router>
<mail:outbound-channel-adapter channel="mail.out" mail-sender="mailSender"/>
This is working fine.
I want to also handle the situation when the mail server is down.
I've tried the following solution but it does not work.
<int:chain input-channel="errorChannel" output-channel="emailErrorChannel">
<int:transformer ref="errorUnwrapper" />
</int:chain>
And the unwrapper:
#MessageEndpoint
public class ErrorUnwrapper {
#Transformer
public Message<?> transform(final ErrorMessage errorMessage) {
Message<?> failedMessage = ((MessagingException) errorMessage.getPayload()).getFailedMessage();
return failedMessage;
}
}
But this is not working. I want to catch the exception and send a meaningful response back to the user instead of a stacktrace. And I want to do this within Spring Integration. Otherwise I'll have to write a Java mail service call with a service-activator instead of the SI mail extension.
Or is it a one-way component? I've just found this blog post doing the same. I've also read this but got nowhere.
You likely need to add the errorChannel to whatever starts you flow; you need to show us the rest of your configuration.
Alternatively, you can add an ExpressionEvaluatingAdvice to the mail adapter; see this sample for an example of using the advice.
We have a requirement where the external client are calling one of our spring integration inbound webservice gateway and we need to acknowledge them right away with a generic OK status. Meanwhile, the payload will be submitted to a channel for asynchronous processing and we don't need the response(email will be sent based on some business validation).
We tried using asynchronous gateway and executor channel(with task executor), but can't figure out how to make the gateway respond immediately. Both the cases it is working as a one way webservice with no response.
Configuration:
<context:component-scan base-package="com.myapp.springintegration" />
<channel id="helloWorldRequestChannel">
<dispatcher task-executor="taskExecutor"/>
</channel>
<channel id="helloWorldReplyChannel"/>
<task:executor id="taskExecutor" pool-size="2"/>
<gateway id="helloServiceGateway"
service-interface="com.myapp.springintegration.HelloService"
default-request-channel="helloWorldRequestChannel" default-reply-channel="helloWorldReplyChannel"/>
<service-activator input-channel="helloWorldRequestChannel" ref="helloServiceImpl" method="hello" />
I don't see any <int-ws:inbound-gateway> but the requirements may be implemented like this:
<int-ws:inbound-gateway request-channel="requestChannel"/>
<int:recipient-list-router input-channel="requestChannel">
<int:recipient channel="response" />
<int:recipient channel="process" />
</int:recipient-list-router>
<int:transformer input-channel="response" expression="'OK'"/>
<int:channel id="process">
<int:dispatcher task-executor="testExecutor"/>
</int:channel>
You send request to the recipient-list-router, that distributes your message to two other channels. The first one (response) just returns simple reply to the WS immediately. The second (process) shifts the message to the separate Thread, so the subscriber to that channel will do its work not blocking the WS Thread.
Hope I am clear.
How does I can achieve parallel processing in spring-integration with recipient-list-router.
My goal is the router has to be content based and sending messages to various channel on parallel processing just like multicast. I tried multicast in Camel with camel-spring-integration but couldn't configure it for content based
Please help if something cane be done
Thanks
If I'm understanding the question right, you just need to use publish subscribe channels as the output channels of the router. The router will direct the message to the right pubsub channel based on content, then all handlers subscribed to that channel will be executed in parallel, assuming the output channel task executor is configured to have multiple threads.
<int:publish-subscribe-channel id="channel1" task-executor="someExecutor"/>
<int:publish-subscribe-channel id="channel2" task-executor="someExecutor"/>
<int:recipient-list-router id="customRouter" input-channel="routingChannel">
<int:recipient channel="channel1" selector-expression="payload.equals('foo')"/>
<int:recipient channel="channel2" selector-expression="headers.containsKey('bar')"/>
</int:recipient-list-router>
The above recipient list router configuration is copied from section 5.1 of the Spring Integration reference manual.
I have achieved similar sort of requirements by extending the Spring-Integrations's RecipientListRouter as follows:
public class CententBasedRecipientListRouter extends RecipientListRouter {
#Override
protected void handleMessageInternal(final Message<?> message) {
......
}
}
in overridden method, you can implement any customized content based routing logic as per your requirements.
This custom router can be configured as follows:
<bean id="customRecipientListRouter" class="CententBasedRecipientListRouter">
<property name="channels">
<list>
<ref bean="parallelProcessingChannel1"/>
<ref bean="parallelProcessingChannel2"/>
<ref bean="parallelProcessingChannel3"/>
</list>
</property>
</bean>
<int:router ref="customRecipientListRouter"
input-channel="routingChannel"
default-output-channel="errorChannel" />
In order to achieve Parallel Processing, you can have Task Executor channels as follows:
<int:channel id="parallelProcessingChannel1">
<int:dispatcher task-executor="threadPoolExecutor"/>
</int:channel>