我正在用Java开发一个Spring项目,它接收来自Google Pub/Sub订阅的消息。但是,我的代码无法解析这些传入消息。消息以JSON格式给出。示例消息如下:
{
"crudType": "Create",
"payload": {
"id": 14833,
"product": { "id": 14829, "name": "Product18" },
"color": { "id": 4, "name": "Green" },
"name": "Option 4"
}
}
我的消息消费者方法尝试将消息解析为一个名为CrudEvent
的兼容类,该类包含一个ProductOption
实体。这些类的属性与入站JSON消息的格式匹配。我也试过使用dto,但没有成功。
@ServiceActivator(inputChannel = Channels.PRODUCT_OPTION_INPUT)
public void handleProductOptionMessage(Message<CrudEvent<ProductOption>> message) throws Exception {
try {
// LoggerFactory.getLogger(Consumer.class).info(message.toString());
CrudEvent<ProductOption> event = message.getPayload();
LoggerFactory.getLogger(Consumer.class).info(event.toString());
ProductOption productOption = event.getPayload();
this.logger.info(productOption.toString());
// this.handleEvent(this.productOptionService, event, productOption);
this.ack(message);
} catch (Exception e) {
this.logger.error("Failed to handle product option message!");
throw e;
}
}
我的ProductOption实体编码如下:
package nl.omoda.stocktestservice.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import nl.omoda.stocktestservice.messaging.dto.ProductOptionDto;
@Entity
public class ProductOption {
@Id
private Long id;
@ManyToOne()
@JoinColumn(name = "productId")
private Product product;
private String name;
protected ProductOption() {}
public ProductOption(Long id, Product product, String name) {
this.id = id;
this.product = product;
this.name = name;
}
public ProductOption(ProductOptionDto dto) {
this(dto.getId(), new Product(dto.getProduct()), dto.getName());
}
@Override
public String toString() {
return "{" +
" id='" + getId() + "'" +
", product='" + getProduct() + "'" +
", name='" + getName() + "'" +
"}";
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Product实体几乎是相同的,除了它只有'id'和'name'属性。ProductOption实体中没有使用JSON中的颜色字段。
完整错误日志:
org.springframework.messaging.MessageHandlingException:
error occurred during processing message in 'MethodInvokingMessageProcessor' [org.springframework.integration.handler.MethodInvokingMessageProcessor@6927b9b0];
nested exception is java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class nl.omoda.stocktestservice.entity.Product
(java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; nl.omoda.stocktestservice.entity.Product is in unnamed module of loader 'app')
Spring似乎不支持包含泛型类型的Message。复制CrudEvent类型作为预先插入ProductOptions的版本修复了错误(我将其命名为ProductOptionCrudEvent)。
消息接收不支持泛型,这有点奇怪。