интеграция Spring: как мне вызвать интеграцию Spring из Spring Controller?

#spring #tcp #spring-integration #integration

#весна #tcp #spring-интеграция #интеграция

Вопрос:

пожалуйста, вы можете мне помочь?
Весь исходный код здесь.
(https://github.com/mcvzone/integration-tcp-test.git )

Спасибо.

1. Я создал XML-файл контекста spring integration-tcp-client.

     <int:gateway id="gw"
                 service-interface="com.example.demo.module.SimpleGateway"
                 default-request-channel="input"/>

    <int-ip:tcp-connection-factory id="client"
                                   type="client"
                                   host="localhost"
                                   port="1234"
                                   single-use="true"
                                   so-timeout="10000"/>

    <int:channel id="input"/>

    <int-ip:tcp-outbound-gateway id="outGateway"
                                 request-channel="input"
                                 reply-channel="clientBytes2StringChannel"
                                 connection-factory="client"
                                 request-timeout="10000"
                                 reply-timeout="10000"/>

    <int:object-to-string-transformer id="clientBytes2String"
                                      input-channel="clientBytes2StringChannel"/>
 

2. И я создал RestController.

 @RestController
public class TcpController {
    
    final GenericXmlApplicationContext context;
    final SimpleGateway simpleGateway;
    
    public TcpController(){
        this.context = new GenericXmlApplicationContext();
        context.load("classpath:META-INF/spring/integration/tcpClientServerDemo-context.xml");
        context.registerShutdownHook();
        context.refresh();
        
        this.simpleGateway = context.getBean(SimpleGateway.class);
    }
    
    @RequestMapping("/tcp/test")
    public String test(String name) {
        //SimpleGateway simpleGateway = context.getBean(SimpleGateway.class);
        String result = simpleGateway.send(name);
        System.out.println("result : "   result);
        return resu<
    }

}
 

3. Я запускаю spring boot и открываю порт 1234 (новый ServerSocket (1234)) и вызываю url.(http://localhost:8080/tcp/test )
4. Результатом является ошибка.

 java.lang.IllegalArgumentException: unable to determine a Message or payload parameter on method
.
.
.
at com.sun.proxy.$Proxy60.send(Unknown Source) ~[na:na]
at com.example.demo.TcpController.test(TcpController.java:25) ~[classes/:na]
 

Комментарии:

1. Не могли бы вы показать больше трассировки стека, пожалуйста?

2. Также покажите SimpleGateway код.

3. Смотрите мой ответ с некоторыми пояснениями.

Ответ №1:

Он начал работать, когда я изменил ваш код на этот:

 @RequestMapping("/tcp/test")
public String test(@RequestBody String name) {
 

Обратите внимание @RequestBody на параметр метода. По умолчанию Spring MVC не знает, к чему из запроса сопоставить аргумент для этого параметра. Итак, это оставлено как null .

С другой стороны, когда аргументом для этого вызова шлюза является null , Spring Integration не может создать a Message<?> для отправки, потому что полезная нагрузка не может быть null . Поэтому вы получаете такое исключение.

Вероятно, мы можем пересмотреть это сообщение об исключении, чтобы конечным пользователям было более очевидно, что происходит. Не стесняйтесь поднимать проблему GH по этому вопросу!

Комментарии:

1. Вот некоторые исправления, чтобы сделать его более понятным: github.com/spring-projects/spring-integration/pull/3500

2. Спасибо. github.com/spring-projects/spring-integration/pull/3500 это хорошо.