0

我正在向 Azure 事件中心发送一条消息,但收到的消息在标头值的开头包含“�$”。代码:

import com.azure.core.credential.TokenCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.messaging.eventhubs.EventData;
import com.azure.messaging.eventhubs.EventDataBatch;
import com.azure.messaging.eventhubs.EventHubClientBuilder;
import com.azure.messaging.eventhubs.EventHubProducerClient;
import com.microsoft.azure.spring.integration.eventhub.converter.EventHubMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

   newMessageHeaders.put("junk", "mock");
    MessageHeaders messageHeaders = new MessageHeaders(newMessageHeaders);
    Message<String> message = new Message<String>() {
      @Override
      public String getPayload() {
        return "MockPayload";
      }

      @Override
      public MessageHeaders getHeaders() {
        return messageHeaders;
      }
    };
    System.setProperty("AZURE_CLIENT_SECRET", "secret");
    System.setProperty("AZURE_CLIENT_ID", "client");
    System.setProperty("AZURE_TENANT_ID", "tenant");
    TokenCredential credential = new DefaultAzureCredentialBuilder().build();
    EventHubProducerClient eventHubProducerClient = new EventHubClientBuilder()
            .credential("namespaceName.servicebus.windows.net", "mockTopic", credential)
            .buildProducerClient();
    EventHubMessageConverter messageConverter= new EventHubMessageConverter();
    eventHubProducerClient.getEventHubName();
    eventHubProducerClient.getEventHubProperties();
    EventData eventData = messageConverter.fromMessage(message,EntryData.class);
    EventDataBatch batch = eventHubProducerClient.createBatch();
    batch.tryAdd(eventData);
    eventHubProducerClient.send(batch);
    eventHubProducerClient.close();

在 azure hub 事件中心接收到的消息在标题下接收到的值为“�$mock”

4

1 回答 1

2

查看:EventHubMessageConverter.fromString,它使用Char.defaultCharset()where-as,如果您调用EventData.getBodyAsString(),我们将其返回 UTF-8 解码。

这可能是编码器不匹配。您正在指定一个字符串作为有效负载,这里的逻辑AbstractAzureMessageConverter: L113-L115调用它fromString来编码为Char.defaultCharset().

几个解决方案:

  1. 将有效负载作为一组字节传递,您可以在其中指定字节的编码/解码。
  2. Char.defaultCharset()如果您决定将其作为字符串传递,请使用反序列化所有输入参数。使用它的缺点是 defaultCharset 会根据系统的语言环境而变化。
于 2021-07-16T16:13:46.580 回答