-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonProducer.java
More file actions
68 lines (56 loc) · 2.44 KB
/
JsonProducer.java
File metadata and controls
68 lines (56 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import com.danubemessaging.client.DanubeClient;
import com.danubemessaging.client.Producer;
import com.danubemessaging.client.SchemaRegistryClient;
import com.danubemessaging.client.schema.SchemaType;
import java.util.Map;
/**
* JSON producer example: registers a JSON schema in the schema registry and
* produces schema-tagged messages to a topic.
*
* Run the JSON consumer (JsonConsumer.java) in a separate terminal first.
*
* Prerequisites: Danube broker running on localhost:6650
* cd docker && docker compose up -d
*/
public class JsonProducer {
private static final String BROKER_URL = System.getenv().getOrDefault("DANUBE_BROKER_URL", "http://127.0.0.1:6650");
private static final String TOPIC = "/default/json_topic";
private static final String SUBJECT = "my-app-events";
private static final String JSON_SCHEMA = """
{
"type": "object",
"properties": {
"field1": {"type": "string"},
"field2": {"type": "integer"}
}
}""";
public static void main(String[] args) throws Exception {
DanubeClient client = DanubeClient.builder()
.serviceUrl(BROKER_URL)
.build();
// Register schema in schema registry
SchemaRegistryClient schemaClient = client.newSchemaRegistry();
var registration = schemaClient.registerSchema(
schemaClient.newRegistration()
.withSubject(SUBJECT)
.withSchemaType(SchemaType.JSON_SCHEMA)
.withSchemaDefinition(JSON_SCHEMA.getBytes()));
System.out.printf("Registered schema '%s' — id=%d version=%d%n",
SUBJECT, registration.schemaId(), registration.version());
// Create producer pinned to the latest schema for this subject
Producer producer = client.newProducer()
.withTopic(TOPIC)
.withName("prod_json")
.withSchemaLatest(SUBJECT)
.build();
producer.create();
System.out.println("Producer created");
for (int i = 0; i < 10; i++) {
String json = String.format("{\"field1\": \"value%d\", \"field2\": %d}", i, 2020 + i);
long msgId = producer.send(json.getBytes(), Map.of());
System.out.printf("Sent message #%d (id=%d): %s%n", i, msgId, json);
Thread.sleep(1000);
}
client.close();
}
}