跳转到内容

Get started with the Apache Kafka integration

此内容尚不支持你的语言。

Apache Kafka logo

Apache Kafka is a distributed streaming platform that enables you to build real-time data pipelines and streaming applications. The Aspire Apache Kafka integration enables you to connect to existing Kafka instances or create new instances from Aspire with the confluentinc/confluent-local container image.

In this introduction, you’ll see how to install and use the Aspire Apache Kafka integrations in a simple configuration. If you already have this knowledge, see Apache Kafka hosting integration for full reference details.

To begin, install the Aspire Kafka hosting integration in your Aspire AppHost project:

Aspire CLI — 添加 Aspire.Hosting.Kafka 包
aspire add kafka

Aspire CLI 是交互式的;按提示选择合适的搜索结果:

Aspire CLI — 输出示例
Select an integration to add:
> kafka (Aspire.Hosting.Kafka)
> Other results listed as selectable options...

Next, in the AppHost project, create instances of Kafka resources and pass them to the consuming client projects:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var kafka = builder.AddKafka("kafka");
builder.AddProject<Projects.ExampleProject>()
.WithReference(kafka);
builder.Build().Run();

When Aspire adds a container image to the AppHost, it creates a new Kafka server instance on your local machine.

To get started with the Aspire Apache Kafka client integration, install the package:

.NET CLI — Add Aspire.Confluent.Kafka package
dotnet add package Aspire.Confluent.Kafka

In the Program.cs file of your client-consuming project, call the AddKafkaProducer extension method to register an IProducer<TKey, TValue> for use via the dependency injection container:

builder.AddKafkaProducer<string, string>("kafka");

You can then retrieve the IProducer<TKey, TValue> instance using dependency injection:

internal sealed class Worker(IProducer<string, string> producer) : BackgroundService
{
// Use producer...
}