Comenzando con la integración de primavera
Instalación o Configuración
La mejor manera de comenzar a usar Spring-Integration en su proyecto es con un sistema de gestión de dependencias, como gradle.
dependencies {
compile 'org.springframework.integration:spring-integration-core:4.3.5.RELEASE'
}
A continuación se muestra un ejemplo muy simple que utiliza la puerta de enlace, service-activator terminales de mensajes.
//these annotations will enable Spring integration and scan for components
@Configuration
@EnableIntegration
@IntegrationComponentScan
public class Application {
//a channel has two ends, this Messaging Gateway is acting as input from one side of inChannel
@MessagingGateway
interface Greeting {
@Gateway(requestChannel = "inChannel")
String greet(String name);
}
@Component
static class HelloMessageProvider {
//a service activator act as a handler when message is received from inChannel, in this example, it is acting as the handler on the output side of inChannel
@ServiceActivator(inputChannel = "inChannel")
public String sayHello(String name) {
return "Hi, " + name;
}
}
@Bean
MessageChannel inChannel() {
return new DirectChannel();
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
Greeting greeting = context.getBean(Greeting.class);
//greeting.greet() send a message to the channel, which trigger service activitor to process the incoming message
System.out.println(greeting.greet("Spring Integration!"));
}
}
Mostrará la cadena ¡Hola, Spring Integration!
en la consola.
Por supuesto, Spring Integration también proporciona una configuración de estilo xml. Para el ejemplo anterior, puede escribir el siguiente archivo de configuración xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<int:gateway default-request-channel="inChannel"
service-interface="spring.integration.stackoverflow.getstarted.Application$Greeting"/>
<int:channel id="inChannel"/>
<int:service-activator input-channel="inChannel" method="sayHello">
<bean class="spring.integration.stackoverflow.getstarted.Application$HelloMessageProvider"/>
</int:service-activator>
</beans>
Para ejecutar la aplicación usando el archivo de configuración xml, debe cambiar el código new AnnotationConfigApplicationContext(Application.class)
en la clase Application
a new ClassPathXmlApplicationContext("classpath:getstarted.xml")
. Y ejecute esta aplicación nuevamente, puede ver el mismo resultado.
Adaptador de canal de entrada y salida genérico
El adaptador de canal es uno de los puntos finales de mensajes en Spring Integration. Se utiliza para el flujo de mensajes unidireccionales. Hay dos tipos de adaptador de canal:
Adaptador de entrada: lado de entrada del canal. Escuche o lea activamente el mensaje.
Adaptador de salida: lado de salida del canal. Enviar mensaje a la clase Java o al sistema o protocolo externo.
-
Código fuente.
public class Application { static class MessageProducer { public String produce() { String[] array = {"first line!", "second line!", "third line!"}; return array[new Random().nextInt(3)]; } } static class MessageConsumer { public void consume(String message) { System.out.println(message); } } public static void main(String[] args) { new ClassPathXmlApplicationContext("classpath:spring/integration/stackoverflow/ioadapter/ioadapter.xml"); } }
-
Archivo de configuración de estilo XML:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd"> <int:channel id="channel"/> <int:inbound-channel-adapter id="inAdapter" channel="channel" method="produce"> <bean class="spring.integration.stackoverflow.ioadapter.Application$MessageProducer"/> <int:poller fixed-rate="1000"/> </int:inbound-channel-adapter> <int:outbound-channel-adapter id="outAdapter" channel="channel" method="consume"> <bean class="spring.integration.stackoverflow.ioadapter.Application$MessageConsumer"/> </int:outbound-channel-adapter> </beans>
-
Flujo de mensajes
inAdapter
: an inbound channel adapter. InvokeApplication$MessageProducer.produce
method every 1 second (<int:poller fixed-rate="1000"/>
) and send the returned string as message to the channelchannel
.channel
: channel to transfer message.outAdapter
: an outbound channel adapter. Once message reached on channelchannel
, this adapter will receive the message and then send it toApplication$MessageConsumer.consume
method which print the message on the console.- So you can observe that these random choose string will displayed on the console every 1 second.
Ejemplo de eco simple con Spring-Integration-Stream
Código Java:
public class StdioApplication {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("classpath:spring/integration/stackoverflow/stdio/stdio.xml");
}
}
Archivo de configuración XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/stream
http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<int:channel id="channel"/>
<int-stream:stdin-channel-adapter id="stdin" channel="channel">
<int:poller fixed-rate="1000"/>
</int-stream:stdin-channel-adapter>
<int-stream:stdout-channel-adapter id="stdout" channel="channel"/>
</beans>
Este es un ejemplo de eco. Cuando ejecuta esta aplicación Java, puede ingresar una cadena y luego se mostrará en la consola.