Note
- 直接注入BinderAwareChannelResolver的bean实例即可
- 通过PathVariable属性dest值模拟通道名称
- boby作为消息体
- contentType作为消息的头信息
服务验证
1、启动receiver、sender两个工程;
2、多次通过curl请求api如下(curl -H "Content-Type: application/json" -X POST -d "{\"username\":\"song\",\"age\":12}" http://localhost:9000/dynamic*-channel)
/************************************方式二************************************/ @RequestMapping(path = "/", method = RequestMethod.POST, consumes = "application/json") @ResponseStatus(HttpStatus.ACCEPTED) public void handleRequest(@RequestBody User body, @RequestHeader(HttpHeaders.CONTENT_TYPE) Object contentType, @RequestHeader(name = "dest", required = false) String dest) { Map<String, Object> headers = new HashMap<>(2); headers.put(MessageHeaders.CONTENT_TYPE, contentType); if (!StringUtils.isEmpty(dest)) { headers.put("dest", dest); } sendMessage(body, headers); } private void sendMessage(User body, Map<String, Object> headers) { routerChannel().send(MessageBuilder.createMessage(body, new MessageHeaders(headers))); } @Bean(name = "router-channel") public MessageChannel routerChannel() { return new DirectChannel(); } @Bean @ServiceActivator(inputChannel = "router-channel") public ExpressionEvaluatingRouter router() { ExpressionEvaluatingRouter router = new ExpressionEvaluatingRouter(new SpelExpressionParser().parseExpression("headers[dest]")); //作用于通过spel表达式没有获取到对应的通道信息 router.setDefaultOutputChannelName("dynamic1-channel"); router.setChannelResolver(resolver); return router; }