如何使用应用于 POJO 的 SPEL 表达式作为 routingKey?

How to use a SPEL expression that is applied on a POJO for the routingKey?

我的源APP:

@InboundChannelAdapter(value = RequestSource.CHANNEL_NAME)
public Event eventMessageSource() throws Exception {
    final Random r = new Random();
    Event event = generateSampleEvent(EventType.values()[r.nextInt(EventType.values().length - 1)]);
    System.out.println("---- Putting now ==> " + event);
    return event;
}

我的application.properties:

logging.level.=INFO
server.port=0
logging.file=events.log
server.port=0
spring.cloud.stream.bindings.requestChannel.destination=events-exchange
spring.cloud.stream.bindings.requestChannel.content-type=application/json
spring.cloud.stream.bindings.requestChannel.binder=rabbit
spring.cloud.stream.bindings.requestChannel.group=eventconsumersgroup
spring.cloud.stream.rabbit.bindings.requestChannel.producer.routing-key-expression=payload.eventType

例外情况是:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'eventType' cannot be found on object of type 'byte[]' - maybe not public?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:224)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.access[=12=]0(PropertyOrFieldReference.java:46)

我不应该使用 application/json 来使用 SPEL 吗?我在这里缺少正确的属性集吗?

在评估路由键表达式之前,负载已经转换为 byte[]

您可以使用消息headers。

@InboundChannelAdapter(value = RequestSource.CHANNEL_NAME)
public Message<Event> eventMessageSource() throws Exception {
    final Random r = new Random();
    Event event = generateSampleEvent(EventType.values()[r.nextInt(EventType.values().length - 1)]);
    System.out.println("---- Putting now ==> " + event);
    return new GenericMessage<>(event, Collections.singletonMap("type", event.getType());
}

然后表达式是headers.typeheaders['type'].