MQTTnet은 MQTT 기반 통신을 위한 오픈 소스 고성능 .NET 라이브러리입니다. 이 문서에서는 Kubernetes 서비스 계정 토큰 및 MQTTnet을 사용하여 MQTT broker에 연결하는 방법을 설명합니다. 서비스 계정 토큰을 사용하여 클러스터 내 애플리케이션에 연결합니다.
샘플 코드
샘플 코드는 다음을 수행합니다.
MqttFactory
클래스를 사용하여 MQTT 클라이언트를 만듭니다.var mqttFactory = new MqttFactory(); var mqttClient = mqttFactory.CreateMqttClient();
Kubernetes Pod 사양은 컨테이너 파일 시스템에 서비스 계정을 탑재하고 파일 내용을 읽습니다. 탑재된 토큰은 잘 알려진 사용자 이름을
K8S-SAT
가진 암호로 사용됩니다.static string sat_auth_file = "/var/run/secrets/tokens/mqtt-client-token"; ... var satToken = File.ReadAllBytes(sat_auth_file);
MQTT 클라이언트 옵션은 클래스를
MqttClientOptions
사용하여 구성됩니다.MqttClientOptionsBuilder
클라이언트 설명서에서 권장되는 대로 옵션을 설정하는 기본 방법입니다.var mqttClientOptions = new MqttClientOptionsBuilder() .WithTcpServer(hostname, tcp_port) .WithProtocolVersion(MqttProtocolVersion.V500) .WithClientId("mqtt-client-dotnet") .WithAuthentication("K8S-SAT", satToken);
MQTT 클라이언트 옵션을 설정한 후 연결을 설정할 수 있습니다. 다음 코드에서는 서버에 연결하는 방법을 보여줍니다. 필요한 경우 유효한 CancellationToken으로 바꿀
CancellationToken.None
수 있습니다.var response = await mqttClient.ConnectAsync(mqttClientOptions.Build(), CancellationToken.None);
직접 속성을 사용하거나
MqttApplicationMessageBuilder
와 함께 사용하여 MQTT 메시지를 만듭니다. 이 클래스는 다른 페이로드 형식을 처리하기 위한 오버로드를 제공합니다. 작성기 API는 유창한 디자인을 사용합니다. 다음 코드는 애플리케이션 메시지를 작성하고 sampletopic이라는 토픽에 게시하는 방법을 보여 있습니다.var applicationMessage = new MqttApplicationMessageBuilder() .WithTopic("sampletopic") .WithPayload("samplepayload" + counter++) .Build(); await mqttClient.PublishAsync(applicationMessage, CancellationToken.None);
Pod 사양
Pod 구성의 serviceAccountName
필드는 사용 중인 토큰과 연결된 서비스 계정과 일치해야 합니다.
serviceAccountToken.expirationSeconds
또한 86400초로 설정되며 만료되면 디스크에서 토큰을 다시 로드해야 합니다. 이 논리는 이 샘플에서 구현되지 않습니다.
apiVersion: v1
kind: ServiceAccount
metadata:
name: mqtt-client
namespace: azure-iot-operations
---
apiVersion: v1
kind: Pod
metadata:
name: mqtt-client-dotnet
namespace: azure-iot-operations
spec:
serviceAccountName: mqtt-client
volumes:
# The SAT token authenticates the application with the MQTT broker
- name: mqtt-client-token
projected:
sources:
- serviceAccountToken:
path: mqtt-client-token
audience: aio-internal
expirationSeconds: 86400
# Certificate chain for the application to validate the MQTT broker
- name: aio-ca-trust-bundle
configMap:
name: azure-iot-operations-aio-ca-trust-bundle
containers:
- name: mqtt-client-dotnet
image: ghcr.io/azure-samples/explore-iot-operations/mqtt-client-dotnet:latest
volumeMounts:
- name: mqtt-client-token
mountPath: /var/run/secrets/tokens/
- name: aio-ca-trust-bundle
mountPath: /var/run/certs/aio-internal-ca-cert/
env:
- name: hostname
value: "aio-broker"
- name: tcpPort
value: "18883"
- name: useTls
value: "true"
- name: caFile
value: "/var/run/certs/aio-internal-ca-cert/ca.crt"
- name: satAuthFile
value: "/var/run/secrets/tokens/mqtt-client-token"
추가 정보 지침에 따라 샘플을 실행합니다.