2017-01-15 3 views
0

Я определил проблему конфигурации в своем приложении, которая должна попытаться отправить запрос службе третьего партнера и должна дождаться ответа. Тип содержимого запроса и ответа - json.Spring http outbound gateway хочет использовать PollableChannel вместо DirectChannel

Проблема, что я нашел в классе MessagingGatewaySupport, где я нашел ожидание для ответа канала, который должен быть PollableChannel, но мне нужно использовать DirectChannel вместо Pollable:

protected Object receive() { 
this.initializeIfNecessary(); 
MessageChannel replyChannel = getReplyChannel(); 
Assert.state(replyChannel != null && (replyChannel instanceof PollableChannel), 
     "receive is not supported, because no pollable reply channel has been configured"); 
return this.messagingTemplate.receiveAndConvert(replyChannel, null); 
} 

Я действительно думаю, что я есть ошибка в моей конфигурации, которая заключается в следующем:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:int="http://www.springframework.org/schema/integration" xmlns:int-http="http://www.springframework.org/schema/integration/http" xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http-4.3.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-4.3.xsd"> 

<jee:jndi-lookup id="repositoryUrl" jndi-name="repositoryUrl"/> 
<jee:jndi-lookup id="wsMaxTotalConnections" jndi-name="wsMaxTotalConnections" default-value="50"/> 
<jee:jndi-lookup id="wsMaxPerRoute" jndi-name="wsDefaultMaxPerRoute" default-value="50"/> 
<jee:jndi-lookup id="wsConnectionTimeout" jndi-name="wsDefaultConnectionTimeout" default-value="10000"/> 
<jee:jndi-lookup id="wsReadTimeout" jndi-name="wsDefaultReadTimeout" default-value="5000"/> 

<int:gateway id="requestGateway" service-interface="com.example.Repository" default-request-channel="requestChannel" 
    default-reply-channel="responseChannel"/> 

<int:channel id="requestChannel"/> 
<int:channel id="responseChannel"/> 

<int-http:outbound-gateway request-channel="requestChannel" url="#{repositoryUrl}" http-method="POST" expected-response-type="java.lang.String" 
    request-factory="httpComponentsClientHttpRequestFactory" message-converters="jsonMessageConverter"/> 

<bean id="jsonMessageConverter" class="com.example.JsonMessageConverter"> 
    <constructor-arg> 
     <bean class="com.example.DataType"/> 
    </constructor-arg> 
</bean> 

<bean id="httpComponentsClientHttpRequestFactory" class="com.example.ApplicationHttpComponentsClientHttpRequestFactory"> 
    <property name="maxTotalConnections" ref="wsMaxTotalConnections"/> 
    <property name="defaultMaxPerRoute" ref="wsMaxPerRoute"/> 
    <property name="connectionTimeout" ref="wsConnectionTimeout"/> 
    <property name="readTimeout" ref="wsReadTimeout"/> 
</bean> 

класса JsonMessageConverter:

public class JsonMessageConverter implements HttpMessageConverter<Object> { 
private static final Logger logger = LoggerFactory.getLogger(JsonMessageConverter.class); 

private Object clazz; 

private List<MediaType> supportedMediaTypes = Collections.emptyList(); 

public Object getClazz() 
{ 
    return clazz; 
} 

public void setClazz(Object clazz) 
{ 
    this.clazz = clazz; 
} 

public JsonMessageConverter(Object clazz) 
{ 
    this.clazz = clazz; 
} 

@Override 
public boolean canRead(Class<?> clazz, MediaType mediaType) 
{ 
    return this.clazz.getClass().equals(clazz); 
} 

@Override 
public boolean canWrite(Class<?> clazz, MediaType mediaType) 
{ 
    return false; 
} 

@Override 
public List<MediaType> getSupportedMediaTypes() 
{ 
    return supportedMediaTypes; 
} 

@Override 
public Object read(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException 
{ 
    Object response = new Object(); 

    logger.trace("Received message in :{} ", inputMessage.getBody().toString()); 

    try 
    { 
     Gson gson = new Gson(); 
     String inputStreamString = inputMessage.getBody().toString(); 

     response = gson.fromJson(inputStreamString, this.clazz.getClass()); 
    } 
    catch (Exception e) 
    { 
     throw new HttpMessageConversionException("Failed to convert response to: " + clazz, e); 
    } 

    logger.trace("Received message out :{} ", response); 

    return response; 

} 

@Override 
public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException 
{ 
    Gson gson = new Gson(); 

    logger.trace("Sent message in :{} ", t); 

    String json = gson.toJson(t); 

    outputMessage.getBody().write(json.getBytes()); 

    logger.trace("Sent message out :{} ", json); 
} 

}

Родственный часть за исключением:

java.lang.IllegalStateException: receive is not supported, because no pollable reply channel has been configured 
at org.springframework.util.Assert.state(Assert.java:392) 
at org.springframework.integration.gateway.MessagingGatewaySupport.receive(MessagingGatewaySupport.java:391) 
at org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:468) 
at org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:429) 
at org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:420) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) 
at com.sun.proxy.$Proxy28.getSoccerSeasons(Unknown Source) 
at com.example.ServiceImpl.getData(ServiceImpl.java:26) 

версия Весна интеграции является 4.3.6. Может кто-нибудь мне помочь? Я пробовал много примеров, но я не нашел ни одного, который работал бы хорошо.

Заранее за вашу помощь.

+0

Зачем вам нужен DirectChannel? – RMachnik

+0

Я новичок в интеграции весной, но у меня нет ссылок на другое решение. – detrist

+0

Существует большая разница между 'DirectChannel' и' Pollable'. Пожалуйста, перейдите по ссылке: http://docs.spring.io/spring-integration/reference/html/messaging-channels-section.html – RMachnik

ответ

1

Необходимо показать свой интерфейс com.example.Repository.

Похоже, что метод, который вы вызываете, не имеет параметров. Вам нужно отправить что-то, чтобы получить ответ.

См. the documentation about gateway methods with no parameters.

При вызове методов на интерфейсе шлюза, у которого нет аргументов, поведение по умолчанию заключается в получении сообщения от PollableChannel.

В то же время вы можете вызвать методы без аргументов, чтобы вы могли фактически взаимодействовать с другими компонентами, расположенными ниже по потоку, которые не требуют параметров, предоставленных пользователем, например. вызывая вызовы без аргументов SQL или хранимые процедуры.

Чтобы получить семантику отправки и получения, вы должны предоставить полезную нагрузку. Для создания полезной нагрузки ...

+0

Спасибо, ваш быстрый ответ, это была моя проблема. Большое спасибо. – detrist

Смежные вопросы