Heim > Java > javaLernprogramm > Hauptteil

Ankündigung des neuen Conductor Java Client v4

Patricia Arquette
Freigeben: 2024-10-14 16:08:31
Original
223 Leute haben es durchsucht

Announcing the New Conductor Java Client v4

Oleh: Miguel Prieto


Awal tahun ini, Python SDK telah melakukan facelift yang besar. Kini SDK Konduktor lain sedang menjalani pemulihan yang ketara, dan kami sangat teruja untuk mengumumkan Java Client v4, yang menampilkan peningkatan reka bentuk yang ketara, peningkatan prestasi dan kebergantungan yang dioptimumkan.

Dalam Java Client v4 kami, kami telah mengurangkan jejak pergantungan dengan menambah baik reka bentuknya. Kami telah menambah penapis, acara dan pendengar untuk mengalih keluar kebergantungan langsung. Keputusan reka bentuk ini dibuat selepas pertimbangan yang teliti untuk menjadikan pelanggan lebih mudah digunakan, dilanjutkan dan diselenggara.

Baca terus untuk mengetahui lebih lanjut!


Mengapa kita melakukan ini?

Kami telah mendengar maklum balas anda dan sedang berusaha untuk meningkatkan pengalaman pembangun. Orkes dan komuniti OSS Konduktor sedang menguruskan dua projek klien/SDK Java yang berasingan, yang kedua-duanya, seperti kebanyakan dalam industri kami, telah mengumpul beberapa hutang teknikal. Kami memutuskan masa yang sesuai untuk menangani hutang ini.

Beberapa perkara utama yang ingin kami atasi dengan segera ialah:

  1. Satu pelanggan Java Konduktor (untuk memerintah mereka semua)
    Matlamatnya adalah untuk menyatukan kedua-dua projek sedia ada menjadi satu penyelesaian yang bersatu, lebih terurus, mengambil elemen terkuat daripada setiap projek. Ini seharusnya diterjemahkan kepada kemas kini yang lebih pantas, sokongan yang lebih baik dan pengalaman pembangunan yang lebih padu.

  2. Pengoptimuman pergantungan
    Sebagai sebahagian daripada pembersihan kod, kami telah mengalih keluar beberapa kebergantungan:

    • Pergantungan pada kod hujung belakang—Klien OSS Java dan projek SDK sebelumnya adalah sebahagian daripada repo OSS Konduktor dan bergantung pada konduktor-common. Walaupun ini memastikan model bahagian belakang/pelanggan sentiasa disegerakkan, ini juga bermakna beberapa kod dan kebergantungan yang berkaitan dengan bahagian belakang telah bocor kepada pelanggan.
    • Pergantungan pada artifak yang tidak digunakan lagi.
    • Pergantungan pada bahan yang anda tidak perlukan.

    Dengan mengalih keluar kebergantungan berkod keras, pengguna dan penyumbang boleh melanjutkan pelanggan tanpa dikunci ke dalam perpustakaan atau alatan tertentu.

  3. Lebih modulariti
    Kami telah menyusun semula projek untuk meningkatkan modulariti, menjadikan pelanggan lebih fleksibel dan lebih mudah untuk disesuaikan.

    Dengan pendekatan modular ini, anda boleh menyepadukan alat pemantauan, pengelogan atau penemuan pilihan anda melalui acara, pendengar dan penapis. Ini bukan sahaja memudahkan penyesuaian tetapi juga menjadikan pangkalan kod lebih boleh diselenggara dan kalis masa hadapan, memperkasakan pembangun untuk membina dan menskalakan sambungan mereka sendiri mengikut keperluan.

  4. Pembersihan/pemfaktoran semula kod
    Dengan pangkalan kod yang lebih bersih, pembangunan masa hadapan harus lebih pantas dan kurang terdedah kepada ralat, menjadikannya lebih mudah untuk sumbangan komuniti juga.

  5. Contoh yang lebih baik
    Kami telah memperkenalkan modul dalam projek khusus untuk contoh. Walaupun ia masih dalam proses, modul ini akan berfungsi sebagai sumber utama untuk contoh praktikal dunia sebenar sama ada anda sedang memulakan atau mencari kes penggunaan lanjutan.

Rumah, rumah manis

Klien Konduktor Rasmi dan SDK kini ditempatkan di https://github.com/conductor-sdk, kecuali Klien Java OSS/SDK, yang merupakan sebahagian daripada repo OSS Konduktor https://github.com /orkes-io/orkes-conductor-client/tree/main.

Melangkah ke hadapan, semua Pelanggan Konduktor dan SDK akhirnya akan ditempatkan dalam direktori konduktor-klien yang sama dalam repo konduktor-oss/konduktor. Pergi ke sana untuk mencari kod sumber untuk Java Client/SDK v4.

Apa yang baharu dalam Java Client v4?

1. Kebergantungan yang dioptimumkan

Java Client v4 memperkenalkan set pergantungan yang lebih diperkemas dan cekap berbanding dengan dua projek yang digantikannya.

Kami telah mengalih keluar semua kebergantungan yang tidak digunakan, tidak digunakan lagi dan tidak perlu, dengan ketara mengurangkan pencemaran laluan kelas. Pengoptimuman ini bukan sahaja meminimumkan risiko konflik antara perpustakaan tetapi juga harus meningkatkan prestasi keseluruhan dan kebolehselenggaraan. Dengan memudahkan pepohon pergantungan, v4 menyediakan pelanggan yang lebih bersih dan ringan yang lebih mudah untuk digunakan dan disepadukan dengan lebih lancar ke dalam projek anda.

2. TaskRunner Baharu

TaskRunner telah difaktorkan semula. Ia menggantikan TaskPollExecutor, kerana kedua-duanya berkongsi tanggungjawab teras yang sama: mengurus kumpulan benang yang digunakan oleh pekerja untuk mengundi, melaksanakan dan mengemas kini tugas.

Dengan itu, kami telah mengalih keluar kebergantungan langsung pada Netflix Eureka dan Spectator, memperkenalkan mekanisme dipacu peristiwa dan menambahkan PollFilter—panggilan balik yang menentukan sama ada pengundian harus berlaku. Selain itu, pengendalian ralat dan pengurusan konkurensi telah dipertingkatkan.

If you’re using Eureka and Spectator, no need to worry—events and filters are provided for seamless integration with these great tools and libraries.

3. Extensibility using events, listeners, and filters

Java Client v4 introduces enhanced extensibility through events, listeners, and filters. These can be used for various purposes, including metrics tracking, logging, auditing, and triggering custom actions based on specific conditions.

For example, you can use a Lambda Function as a PollFilter to check the instance status as reported by Eureka. If the instance is marked as UP—meaning Eureka considers it healthy and available—the worker will proceed to poll for tasks.

Additionally, a listener can be registered to handle PollCompleted events. In this scenario, the listener logs event details and uses Prometheus to track the duration of the polling process, attaching the task type as a label for detailed metrics tracking. This approach not only adds flexibility but also improves observability and control over the client's behavior.

var runnerConfigurer = new TaskRunnerConfigurer
        .Builder(taskClient, List.of(new HelloWorldWorker()))
        .withThreadCount(10)
        .withPollFilter((String taskType, String domain) -> {
            return eurekaClient.getInstanceRemoteStatus().equals(InstanceStatus.UP);
        })
        .withListener(PollCompleted.class, (e) -> {
            log.info("Poll Completed {}", e);
            var timer = prometheusRegistry.timer("poll_completed", "type", e.getTaskType());
            timer.record(e.getDuration());
        })
        .build();

runnerConfigurer.init();
Nach dem Login kopieren

The client also has some specialized interfaces like MetricsCollector, which is built on top of these events and listeners. We’ll be providing concrete implementations of Metrics Collectors soon.

4. OkHttp3 v4 — the right amount of features OOTB

OkHttp3 v4 is one of the most popular and well-regarded HTTP clients for Java. By upgrading to it, our Java Client/SDK v4 now supports HTTP2 and Gzip out-of-the-box, allowing you to make swifter HTTP requests or data transfers. While there are other excellent options, OkHTTP was chosen for its simplicity, performance, and reliability.

With the OkHttp upgrade, we also decided to remove one abstraction layer, Jersey. Jersey is more feature-rich but also more heavyweight compared to a simple HTTP client like OkHttp. Some of these features (such as dependency injection, filters, and exception mappers) can be overkill if you just want to make basic HTTP requests.

5. Ease of migration from OSS to Orkes

The client promotes seamless integration between OSS Conductor and Orkes Conductor, empowering users with the flexibility to switch as their needs evolve, while maintaining support for the open-source community first.

The Orkes Client module simply extends the Conductor Client by adding authentication through a HeaderSupplier.

For OSS users who have created workers with Client v4 but want to give Orkes Conductor a shot, they just need to add the orkes-conductor-client dependency to their project and instantiate the client with OrkesAuthentication as a Header Supplier. Switching back to OSS is as simple as removing that Header Supplier.

var client = ConductorClient.builder()
                .basePath(BASE_PATH)
                .addHeaderSupplier(new OrkesAuthentication(KEY, SECRET))
                .build();
return new TaskClient(client); // Use this TaskClient with TaskRunner to initialize workers
Nach dem Login kopieren

Find out the 6 differences between Conductor OSS and Orkes Conductor.

6. Improved examples and documentation

We’ve started consolidating examples into a dedicated module, with improvements that cover key areas like authorization, managing workflow and task definitions, scheduling workflows, and more. While this module is still a work in progress, we’ll continuously add and refine examples to provide better guidance and cover real-world use cases.

Our goal is to enable developers to use our Client/SDK effectively and explore best practices as the module evolves.

Getting started with Java Client v4

Here’s how you can get started using Java Client v4:

Step 1: Spin up Conductor

Use Conductor OSS or Orkes Conductor:

  • Conductor OSS—Run it from source or use Docker.
  • Orkes Conductor—Try out Orkes Playground or sign up for a free trial.

Step 2: Add conductor-client dependency to your project

For Gradle-based projects:

implementation 'org.conductoross:conductor-client:4.0.0'
implementation 'io.orkes:orkes-conductor-client:4.0.0' // required if using Orkes Conductor
Nach dem Login kopieren

For Maven-based projects:

<dependency>
    <groupId>org.conductoross</groupId>
    <artifactId>conductor-client</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>io.orkes</groupId>
    <artifactId>orkes-conductor-client</artifactId>
    <version>4.0.0</version>
</dependency> <!-- Required if using Orkes Conductor –->
Nach dem Login kopieren

Step 3: Create a ConductorClient instance

import com.netflix.conductor.client.http.ConductorClient;

// … boilerplate or other code omitted
var client = new ConductorClient("http://localhost:8080/api");
Nach dem Login kopieren

If you are using Orkes Conductor, you will need to create an application and grab your credentials. With your key id and secret, create a ConductorClient instance:

import com.netflix.conductor.client.http.ConductorClient;
import io.orkes.conductor.client.http.OrkesAuthentication;

var client = ConductorClient.builder()
           .basePath("https://play.orkes.io/api")
           .addHeaderSupplier(new OrkesAuthentication(KEY, SECRET))
           .build();
Nach dem Login kopieren

or

import io.orkes.conductor.client.ApiClient;

var client = ApiClient.builder() // ApiClient extends ConductorClient
                 .basePath("https://play.orkes.io/api")
                .credentials(KEY, SECRET)
                .build();
Nach dem Login kopieren

Step 4: Create a workflow

You can create a workflow in Conductor using this JSON:

{
  "name": "hello_workflow",
  "description": "Hello Workflow!",
  "version": 1,
  "tasks": [
    {
      "name": "hello_task",
      "taskReferenceName": "hello_task_ref",
      "type": "SIMPLE",
      "inputParameters": {}
    }
  ],
  "inputParameters": [],
  "outputParameters": {

  },
  "schemaVersion": 2,
  "restartable": true,
  "workflowStatusListenerEnabled": false,
  "ownerEmail": "example@orkes.io",
  "timeoutPolicy": "ALERT_ONLY",
  "timeoutSeconds": 0
}
Nach dem Login kopieren

Or use our SDK module to create workflows as code. For that, you need to add the following dependency to your project:

For Gradle-based projects:

implementation 'org.conductoross:java-sdk::4.0.0'
Nach dem Login kopieren

For Maven-based projects:

<dependency>
    <groupId>org.conductoross</groupId>
    <artifactId>java-sdk</artifactId>
    <version>4.0.0</version>
</dependency>
Nach dem Login kopieren

With the dependency added, you can execute the following code to register the workflow:

import com.netflix.conductor.sdk.workflow.def.WorkflowBuilder;
import com.netflix.conductor.sdk.workflow.def.tasks.SimpleTask;
import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor;

// … boilerplate or other code omitted
var executor = new WorkflowExecutor("http://localhost:8080/api");
var workflow = new WorkflowBuilder<Void>(executor)
        .name("hello_workflow")
        .version(1)
        .description("Hello Workflow!")
        .ownerEmail("examples@orkes.io")
        .add(new SimpleTask("hello_task", "hello_task_ref"))
        .build();
workflow.registerWorkflow(true, true);
executor.shutdown();
Nach dem Login kopieren

Step 5: Start a workflow

Now that you have registered a workflow, you can start it with code:

import com.netflix.conductor.client.http.ConductorClient;
import com.netflix.conductor.client.http.WorkflowClient;
import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest;

var client = new ConductorClient("http://localhost:8080/api");
var workflowClient = new WorkflowClient(client);
var workflowId = workflowClient.startWorkflow(new StartWorkflowRequest()
        .withName("hello_workflow")
        .withVersion(1));

System.out.println("Started workflow " + workflowId);
Nach dem Login kopieren

Step 6: Run a worker

You need a worker polling for “hello_workflow” tasks and executing them to complete the workflow you started in Step 5.

For that, you can run this example:

import com.netflix.conductor.client.automator.TaskRunnerConfigurer;
import com.netflix.conductor.client.http.ConductorClient;
import com.netflix.conductor.client.http.TaskClient;
import com.netflix.conductor.client.worker.Worker;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskResult;

import java.util.List;

public class HelloWorker implements Worker {

    @Override
    public TaskResult execute(Task task) {
        var taskResult = new TaskResult(task);
        taskResult.setStatus(TaskResult.Status.COMPLETED);
        taskResult.getOutputData().put("message", "Hello World!");
        return taskResult;
    }

    @Override
    public String getTaskDefName() {
        return "hello_task";
    }

    public static void main(String[] args) {
        var client = new ConductorClient("http://localhost:8080/api");
        var taskClient = new TaskClient(client);
        var runnerConfigurer = new TaskRunnerConfigurer
                .Builder(taskClient, List.of(new HelloWorker()))
                .withThreadCount(10)
                .build();
        runnerConfigurer.init();
    }
}
Nach dem Login kopieren

These complete examples can be found here.

Note: If you want to run these code snippets in Orkes Conductor, remember to authenticate.

What’s next?: Roadmap

We aim for full parity between OSS server models and SDKs, so stay tuned for more changes to Conductor’s Java SDK and improved documentation. To stay up-to-date with our progress, check out the Conductor OSS Project Board. To request features or report bugs, create a ticket in our GitHub repository or contact us on Slack.

We’ll also soon tackle other supported languages: JavaScript, C#, Go, and Clojure. In the meantime, happy coding! Don’t forget to follow the Conductor OSS project and support us by giving a ⭐.


Orkes Cloud is a fully managed and hosted Conductor service that can scale seamlessly to meet your needs. When you use Conductor via Orkes Cloud, your engineers don’t need to worry about setting up, tuning, patching, and managing high-performance Conductor clusters. Try it out with our 14-day free trial for Orkes Cloud.

Das obige ist der detaillierte Inhalt vonAnkündigung des neuen Conductor Java Client v4. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!