use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by camunda-cloud.
the class WorkloadGenerator method performSampleWorkload.
/**
* Given a client, deploy a process, start instances, work on service tasks, create and resolve
* incidents and finish the instance.
*/
public static void performSampleWorkload(final ZeebeClient client) {
client.newDeployResourceCommand().addProcessModel(SAMPLE_PROCESS, "sample_process.bpmn").send().join();
final Map<String, Object> variables = new HashMap<>();
variables.put("orderId", "foo-bar-123");
variables.put("largeValue", "x".repeat(8192));
variables.put("unicode", "Á");
variables.put("nullable", null);
final long processInstanceKey = client.newCreateInstanceCommand().bpmnProcessId("testProcess").latestVersion().variables(variables).send().join().getProcessInstanceKey();
// create job worker which fails on first try and sets retries to 0 to create an incident
final AtomicBoolean fail = new AtomicBoolean(true);
final JobWorker worker = client.newWorker().jobType("work").handler((handlerClient, job) -> {
if (fail.getAndSet(false)) {
// fail job
handlerClient.newFailCommand(job.getKey()).retries(0).errorMessage("failed").send().join();
} else {
handlerClient.newCompleteCommand(job.getKey()).send().join();
}
}).open();
client.newPublishMessageCommand().messageName("catch").correlationKey("foo-bar-123").send().join();
// wait for incident and resolve it
final Record<IncidentRecordValue> incident = Awaitility.await("the incident was created").timeout(Duration.ofMinutes(1)).until(() -> RecordingExporter.incidentRecords(IncidentIntent.CREATED).withProcessInstanceKey(processInstanceKey).withElementId("task").findFirst(), Optional::isPresent).orElseThrow();
client.newUpdateRetriesCommand(incident.getValue().getJobKey()).retries(3).send().join();
client.newResolveIncidentCommand(incident.getKey()).send().join();
// wrap up
Awaitility.await("the process instance was completed").timeout(Duration.ofMinutes(1)).until(() -> RecordingExporter.processInstanceRecords(ProcessInstanceIntent.ELEMENT_COMPLETED).filter(r -> r.getKey() == processInstanceKey).exists());
worker.close();
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by zeebe-io.
the class Worker method run.
@Override
public void run() {
final WorkerCfg workerCfg = appCfg.getWorker();
final String jobType = workerCfg.getJobType();
final long completionDelay = workerCfg.getCompletionDelay().toMillis();
final var variables = readVariables(workerCfg.getPayloadPath());
final BlockingQueue<Future<?>> requestFutures = new ArrayBlockingQueue<>(10_000);
final BlockingDeque<DelayedCommand> delayedCommands = new LinkedBlockingDeque<>(10_000);
final ZeebeClient client = createZeebeClient();
printTopology(client);
final JobWorker worker = client.newWorker().jobType(jobType).handler((jobClient, job) -> {
final var command = jobClient.newCompleteCommand(job.getKey()).variables(variables);
if (workerCfg.isCompleteJobsAsync()) {
delayedCommands.addLast(new DelayedCommand(Instant.now().plusMillis(completionDelay), command));
} else {
try {
Thread.sleep(completionDelay);
} catch (Exception e) {
e.printStackTrace();
}
requestFutures.add(command.send());
}
}).open();
final ResponseChecker responseChecker = new ResponseChecker(requestFutures);
responseChecker.start();
final var asyncJobCompleter = new DelayedCommandSender(delayedCommands, requestFutures);
if (workerCfg.isCompleteJobsAsync()) {
asyncJobCompleter.start();
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
worker.close();
client.close();
asyncJobCompleter.close();
responseChecker.close();
}));
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by camunda-cloud.
the class JobWorkerCreator method main.
public static void main(final String[] args) {
final String defaultAddress = "localhost:26500";
final String envVarAddress = System.getenv("ZEEBE_ADDRESS");
final ZeebeClientBuilder clientBuilder;
if (envVarAddress != null) {
/* Connect to Camunda Cloud Cluster, assumes that credentials are set in environment variables.
* See JavaDoc on class level for details
*/
clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(envVarAddress);
} else {
// connect to local deployment; assumes that authentication is disabled
clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(defaultAddress).usePlaintext();
}
final String jobType = "foo";
try (final ZeebeClient client = clientBuilder.build()) {
System.out.println("Opening job worker.");
try (final JobWorker workerRegistration = client.newWorker().jobType(jobType).handler(new ExampleJobHandler()).timeout(Duration.ofSeconds(10)).open()) {
System.out.println("Job worker opened and receiving jobs.");
// run until System.in receives exit command
waitUntilSystemInput("exit");
}
}
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project zdb by Zelldon.
the class ZeebeStateTest method setup.
@BeforeAll
public static void setup() throws Exception {
final ZeebeClient client = ZeebeClient.newClientBuilder().gatewayAddress(zeebeContainer.getExternalGatewayAddress()).usePlaintext().build();
deploymentEvent = client.newDeployCommand().addProcessModel(process, "process.bpmn").send().join();
returnedProcessInstance = client.newCreateInstanceCommand().bpmnProcessId("process").latestVersion().variables(Map.of("var1", "1", "var2", "12", "var3", "123")).send().join();
client.newPublishMessageCommand().messageName("msg").correlationKey("123").timeToLive(Duration.ofSeconds(1)).send().join();
client.newPublishMessageCommand().messageName("msg12").correlationKey("123").timeToLive(Duration.ofHours(1)).send().join();
jobLatch = new CountDownLatch(1);
final var jobWorker = client.newWorker().jobType("type").handler((jobClient, job) -> {
jobKey.set(job.getKey());
jobLatch.countDown();
}).open();
jobLatch.await();
jobWorker.close();
client.close();
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project micronaut-zeebe-client by camunda-community-hub.
the class ZeebeWorkerProcessor method registerJobHandler.
protected void registerJobHandler(ExecutableMethod<?, ?> method) {
AnnotationValue<ZeebeWorker> annotation = method.getAnnotation(ZeebeWorker.class);
if (methodSignatureMatchesJobHandler(method.getArguments())) {
Class<?> declaringType = method.getDeclaringType();
Object bean = beanContext.getBean(declaringType);
if (annotation != null) {
annotation.stringValue("type").ifPresent(type -> {
JobWorkerBuilderStep1.JobWorkerBuilderStep3 jobWorkerBuilderStep3 = zeebeClient.newWorker().jobType(type).handler((client, job) -> ((ExecutableMethod) method).invoke(bean, client, job));
annotation.stringValue("timeout").ifPresent(timeout -> {
jobWorkerBuilderStep3.timeout(Duration.parse(timeout));
});
annotation.intValue("maxJobsActive").ifPresent(jobWorkerBuilderStep3::maxJobsActive);
annotation.stringValue("requestTimeout").ifPresent(requestTimeout -> {
jobWorkerBuilderStep3.requestTimeout(Duration.parse(requestTimeout));
});
annotation.stringValue("pollInterval").ifPresent(pollInterval -> {
jobWorkerBuilderStep3.pollInterval(Duration.parse(pollInterval));
});
JobWorker jobWorker = jobWorkerBuilderStep3.open();
jobWorkers.add(jobWorker);
log.info("Zeebe client ({}#{}) subscribed to type '{}'", bean.getClass().getName(), method.getName(), type);
});
}
}
}
Aggregations