Search in sources :

Example 6 with JobWorker

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();
}
Also used : ProcessInstanceIntent(io.camunda.zeebe.protocol.record.intent.ProcessInstanceIntent) IncidentRecordValue(io.camunda.zeebe.protocol.record.value.IncidentRecordValue) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Bpmn(io.camunda.zeebe.model.bpmn.Bpmn) HashMap(java.util.HashMap) RecordingExporter(io.camunda.zeebe.test.util.record.RecordingExporter) Record(io.camunda.zeebe.protocol.record.Record) IncidentIntent(io.camunda.zeebe.protocol.record.intent.IncidentIntent) Duration(java.time.Duration) Map(java.util.Map) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) BpmnModelInstance(io.camunda.zeebe.model.bpmn.BpmnModelInstance) Optional(java.util.Optional) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) Awaitility(org.awaitility.Awaitility) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) IncidentRecordValue(io.camunda.zeebe.protocol.record.value.IncidentRecordValue) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker)

Example 7 with JobWorker

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();
    }));
}
Also used : ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Future(java.util.concurrent.Future) AppCfg(io.camunda.zeebe.config.AppCfg) BlockingDeque(java.util.concurrent.BlockingDeque) FinalCommandStep(io.camunda.zeebe.client.api.command.FinalCommandStep) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) WorkerCfg(io.camunda.zeebe.config.WorkerCfg) BlockingQueue(java.util.concurrent.BlockingQueue) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) Instant(java.time.Instant) ZeebeClientBuilder(io.camunda.zeebe.client.ZeebeClientBuilder) WorkerCfg(io.camunda.zeebe.config.WorkerCfg) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Future(java.util.concurrent.Future)

Example 8 with JobWorker

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");
        }
    }
}
Also used : ZeebeClient(io.camunda.zeebe.client.ZeebeClient) ZeebeClientBuilder(io.camunda.zeebe.client.ZeebeClientBuilder) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker)

Example 9 with JobWorker

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();
}
Also used : ErrorType(io.camunda.zeebe.protocol.record.value.ErrorType) BindMode(org.testcontainers.containers.BindMode) ProcessInstanceIntent(io.camunda.zeebe.protocol.record.intent.ProcessInstanceIntent) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ZeebeContainer(io.zeebe.containers.ZeebeContainer) Bpmn(io.camunda.zeebe.model.bpmn.Bpmn) DeploymentEvent(io.camunda.zeebe.client.api.response.DeploymentEvent) AfterAll(org.junit.jupiter.api.AfterAll) BeforeAll(org.junit.jupiter.api.BeforeAll) ZeebePaths(io.zell.zdb.ZeebePaths) Duration(java.time.Duration) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BpmnModelInstance(io.camunda.zeebe.model.bpmn.BpmnModelInstance) FileUtil(io.camunda.zeebe.util.FileUtil) Container(org.testcontainers.junit.jupiter.Container) IncidentState(io.zell.zdb.state.incident.IncidentState) ProcessState(io.zell.zdb.state.process.ProcessState) ProcessInstanceEvent(io.camunda.zeebe.client.api.response.ProcessInstanceEvent) BlacklistState(io.zell.zdb.state.blacklist.BlacklistState) Testcontainers(org.testcontainers.junit.jupiter.Testcontainers) InstanceState(io.zell.zdb.state.instance.InstanceState) GeneralState(io.zell.zdb.state.general.GeneralState) File(java.io.File) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) BpmnElementType(io.camunda.zeebe.protocol.record.value.BpmnElementType) TempDir(org.junit.jupiter.api.io.TempDir) InstanceDetails(io.zell.zdb.state.instance.InstanceDetails) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker) ZeebeClient(io.camunda.zeebe.client.ZeebeClient) CountDownLatch(java.util.concurrent.CountDownLatch) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 10 with JobWorker

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);
            });
        }
    }
}
Also used : JobWorkerBuilderStep1(io.camunda.zeebe.client.api.worker.JobWorkerBuilderStep1) JobWorker(io.camunda.zeebe.client.api.worker.JobWorker)

Aggregations

JobWorker (io.camunda.zeebe.client.api.worker.JobWorker)14 ZeebeClient (io.camunda.zeebe.client.ZeebeClient)13 BpmnModelInstance (io.camunda.zeebe.model.bpmn.BpmnModelInstance)7 ZeebeClientBuilder (io.camunda.zeebe.client.ZeebeClientBuilder)6 Bpmn (io.camunda.zeebe.model.bpmn.Bpmn)6 Duration (java.time.Duration)6 Instant (java.time.Instant)5 Awaitility (org.awaitility.Awaitility)5 ProcessInstanceIntent (io.camunda.zeebe.protocol.record.intent.ProcessInstanceIntent)4 Map (java.util.Map)4 Test (org.junit.jupiter.api.Test)4 FinalCommandStep (io.camunda.zeebe.client.api.command.FinalCommandStep)3 AppCfg (io.camunda.zeebe.config.AppCfg)3 WorkerCfg (io.camunda.zeebe.config.WorkerCfg)3 Record (io.camunda.zeebe.protocol.record.Record)3 IncidentIntent (io.camunda.zeebe.protocol.record.intent.IncidentIntent)3 IncidentRecordValue (io.camunda.zeebe.protocol.record.value.IncidentRecordValue)3 RecordingExporter (io.camunda.zeebe.test.util.record.RecordingExporter)3 ZeebeContainer (io.zeebe.containers.ZeebeContainer)3 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)3