Home Java javaTutorial Harnessing Automatic Setup and Integration with Quarkus Dev Services for Efficient Development

Harnessing Automatic Setup and Integration with Quarkus Dev Services for Efficient Development

Sep 03, 2024 pm 01:11 PM

JPrime 2024 concluded successfully!!

The organizers of JPrime 2024 have once again gone to great lengths to offer a diverse range of topics, ensuring there's something for everyone.

However, today's article isn't triggered by one of Michael Simons' lectures on "The Evolution of Integration Testing within Spring and Quarkus" although it was highly insightful. He explored integration testing strategies, focusing on the setup in Spring Boot.

The author clearly emphasized that the issues he highlighted are effectively addressed in Quarkus through the utilization of Dev Services (Figure 1). This highlights another reason why I view Spring Boot with skepticism for certain applications- its complexities are starkly contrasted by the streamlined solutions in Quarkus, particularly with the use of Dev Services.

Harnessing Automatic Setup and Integration with Quarkus Dev Services for Efficient Development

Figure 1 – JPrime 2024

It was remarkable to witness the astonishment Dev Services sparked among the new attendees. However, it's important to note that Dev Services is not a recent feature in Quarkus; it has been an integral part of the framework for quite some time. Let’s delve deeper into Quarkus Dev Services and explore its enduring benefits.

Quarkus Dev Services

In Quarkus, Dev Services facilitate the automatic provisioning of unconfigured services in both development and testing modes. Essentially, if you include an extension without configuring it, Quarkus will automatically initiate the relevant service—often utilizing Testcontainers in the background—and configure your application to use this service efficiently.

  1. Automatic Service Detection and Launch

    Quarkus Dev Services automates the detection and launching of necessary services like databases, message brokers, and other backend services. This function taps into the application’s dependencies specified in pom.xml or build.gradle. For instance, adding a database driver automatically triggers Dev Services to spin up a corresponding containerized instance of that database if it's not already running. The technology used here primarily involves Testcontainers, which allows for the creation of lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.

  2. Dynamic Configuration Injection

    Once the required services are instantiated, Quarkus Dev Services dynamically injects the relevant service connection details into the application's configuration at runtime. This is done without any manual intervention, using a feature known as Continuous Testing that reroutes the standard database, or other service URLs, to the auto-provisioned Testcontainers. Configuration properties such as URLs, user credentials, and other operational parameters are seamlessly set, allowing the application to interact with these services as though they were manually configured.

  3. Service-Specific Behaviors

    Dev Services is tailored for various types of services:

    • Databases: Automatically provides a running database tailored to your application's needs, whether it's PostgreSQL, MySQL, MongoDB, or any other supported database. Dev Services ensures that a corresponding Testcontainer is available during development.
    • Messaging Systems: For applications that use messaging systems like Kafka or AMQP, Quarkus Dev Services starts the necessary brokers using Docker and connects them with the application.
    • Custom Dev Services: Developers can extend the functionality by creating custom Quarkus extensions that leverage the Dev Services framework. This allows for tailored setups that are project-specific, offering even greater flexibility and control.
  4. Network Handling and Service Isolation

    Each service spun up by Quarkus Dev Services runs in its isolated environment. This is crucial for ensuring that there are no port conflicts, data residue, or security issues between different development tests. Despite this isolation, services are networked appropriately using Docker, ensuring that they can communicate with each other as needed, imitating a real-world deployment atmosphere.

  5. Lifecycle Management

    Quarkus manages the complete lifecycle of these dynamically provisioned services. When you start your application in development mode, the necessary services are started up automatically. When you stop the Quarkus application, these services are also terminated. This management includes handling data persistency as required, allowing developers to pick up right where they left off without any setup delays.

Example Usage

Consider you’re using a PostgreSQL database with Quarkus. If no existing PostgreSQL configuration is detected, Quarkus will kickstart a PostgreSQL Docker container and connect your application automatically.

These services are enabled by default in development and test modes but can be disabled if necessary via the application.properties:

quarkus.datasource.devservices.enabled=false

Let's expand on the scenario where Quarkus is using a PostgreSQL database and how the Dev Services facilitate this with minimum fuss.

If Quarkus detects that no PostgreSQL configuration is active (not running or not configured explicitly), it will automatically start up a PostgreSQL container using Docker. This is set up behind the scenes through Dev Services.

To interact with the database through an ORM layer, consider using Quarkus Panache, which simplifies Hibernate ORM operations. Here’s how to set up your environment:

  1. Add Dependencies

    Firstly, include the necessary dependencies in your pom.xml:

    <dependency>
     <groupId>io.quarkus</groupId>
     <artifactId>quarkus-hibernate-orm-panache</artifactId>
    </dependency>
    <dependency>
     <groupId>io.quarkus</groupId>
     <artifactId>quarkus-jdbc-postgresql</artifactId>
    </dependency>
    
  2. Define the Entity

    Next, define your entity, such as CityEntity:

    @Entity
    @Table(name = "cities")
    public class CityEntity {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    
    @Column(name = "public_id")
    private String publicId;
    
    @OneToOne
    private StateEntity state;
    
    @Column(nullable = false, name = "created_at")
    private Instant createdAt;
    
    @Column(nullable = false, name = "last_modified")
    private Instant lastModified;
    
    @PrePersist
    protected void onCreate() {
     createdAt = Instant.now();
     lastModified = createdAt;
    }
    
    @PreUpdate
    protected void onUpdate() {
     lastModified = Instant.now();
    }
    }
    
  3. Create the Repository

    Implement the repository which will directly interact with th database:

    @ApplicationScoped
    public class CityRepository implements 
    PanacheRepository<CityEntity> {
    }
    
  4. Service Layer

    Define the service layer that utilizes the repository:

    @ApplicationScoped
    public class CityServiceImpl implements CityService {
    
      @Inject
      CityRepository cityRepository;
    
      @Override
      public long countCities() {
       return cityRepository.count();
      }
    }
    
    public interface CityService {
     long countCities();
    }
    
  5. Resource Endpoint

    @Path("/cities")
    @Tag(name = "City Resource", description = "City APIs")
    public class CityResource {
    
      @Inject
      CityService cityService;
    
      @GET
      @Path("/count")
      @Operation(summary = "Get the total number of cities", 
       description = "Returns the total count of cities in the 
       system.")
      @APIResponse(responseCode = "200", description = "Successful 
      response", content = @Content(mediaType = "application/json", 
      schema = @Schema(implementation = Long.class)))
      public long count() {
       return cityService.countCities();
      }
     }
    

When you run your Quarkus application (mvn quarkus:dev), observe the automatic startup of the PostgreSQL container (Figure 2). This seamless integration exemplifies the power of Quarkus Dev Services, making development and testing significantly simpler by automating the configuration and connection setup to external services needed for your application.

Harnessing Automatic Setup and Integration with Quarkus Dev Services for Efficient Development

Figure 2 – Application logs

Platform Dev Services

Quarkus Dev Services streamline the development and testing phases by handling the configuration and management of various services, allowing developers to focus more on the actual application. Quarkus supports a wide range of Dev Services, including:

  • AMQP
  • Apicurio Registry
  • Databases
  • Kafka
  • Keycloak
  • Kubernetes
  • MongoDB
  • RabbitMQ
  • Pulsar
  • Redis
  • Vault
  • Infinispan
  • Elasticsearch
  • Observability
  • Neo4j
  • WireMock
  • Microcks
  • Keycloak
  • and many more, each designed to enhance your development environment seamlessly

Conclusion

Quarkus Dev Services represents a paradigm shift in how developers approach setting up and integrating external services during the development and testing phases. The automation of environment setup not only accelerates the development process but also reduces the potential for configuration errors, making it easier for teams to focus on creating robust, feature-rich applications.

One of the standout advantages of Quarkus Dev Services is the emphasis on developer productivity. By removing the need to manually manage service dependencies, developers can immediately begin work on business logic and application features. This streamlined workflow is particularly beneficial in microservices architectures where multiple services might require simultaneous development and integration

In conclusion, embracing Quarkus Dev Services could significantly impact your development team's effectiveness and project outcomes. The simplicity and power of Quarkus encourage experimentation,
quicker iterations, and ultimately a faster development cycle. This kind of technological leverage is what modern businesses need to thrive in the digital era.

The above is the detailed content of Harnessing Automatic Setup and Integration with Quarkus Dev Services for Efficient Development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the `enum` type in Java? What is the `enum` type in Java? Jul 02, 2025 am 01:31 AM

Enums in Java are special classes that represent fixed number of constant values. 1. Use the enum keyword definition; 2. Each enum value is a public static final instance of the enum type; 3. It can include fields, constructors and methods to add behavior to each constant; 4. It can be used in switch statements, supports direct comparison, and provides built-in methods such as name(), ordinal(), values() and valueOf(); 5. Enumeration can improve the type safety, readability and flexibility of the code, and is suitable for limited collection scenarios such as status codes, colors or week.

What is the interface segregation principle? What is the interface segregation principle? Jul 02, 2025 am 01:24 AM

Interface Isolation Principle (ISP) requires that clients not rely on unused interfaces. The core is to replace large and complete interfaces with multiple small and refined interfaces. Violations of this principle include: an unimplemented exception was thrown when the class implements an interface, a large number of invalid methods are implemented, and irrelevant functions are forcibly classified into the same interface. Application methods include: dividing interfaces according to common methods, using split interfaces according to clients, and using combinations instead of multi-interface implementations if necessary. For example, split the Machine interfaces containing printing, scanning, and fax methods into Printer, Scanner, and FaxMachine. Rules can be relaxed appropriately when using all methods on small projects or all clients.

Asynchronous Programming Techniques in Modern Java Asynchronous Programming Techniques in Modern Java Jul 07, 2025 am 02:24 AM

Java supports asynchronous programming including the use of CompletableFuture, responsive streams (such as ProjectReactor), and virtual threads in Java19. 1.CompletableFuture improves code readability and maintenance through chain calls, and supports task orchestration and exception handling; 2. ProjectReactor provides Mono and Flux types to implement responsive programming, with backpressure mechanism and rich operators; 3. Virtual threads reduce concurrency costs, are suitable for I/O-intensive tasks, and are lighter and easier to expand than traditional platform threads. Each method has applicable scenarios, and appropriate tools should be selected according to your needs and mixed models should be avoided to maintain simplicity

Differences Between Callable and Runnable in Java Differences Between Callable and Runnable in Java Jul 04, 2025 am 02:50 AM

There are three main differences between Callable and Runnable in Java. First, the callable method can return the result, suitable for tasks that need to return values, such as Callable; while the run() method of Runnable has no return value, suitable for tasks that do not need to return, such as logging. Second, Callable allows to throw checked exceptions to facilitate error transmission; while Runnable must handle exceptions internally. Third, Runnable can be directly passed to Thread or ExecutorService, while Callable can only be submitted to ExecutorService and returns the Future object to

Best Practices for Using Enums in Java Best Practices for Using Enums in Java Jul 07, 2025 am 02:35 AM

In Java, enums are suitable for representing fixed constant sets. Best practices include: 1. Use enum to represent fixed state or options to improve type safety and readability; 2. Add properties and methods to enums to enhance flexibility, such as defining fields, constructors, helper methods, etc.; 3. Use EnumMap and EnumSet to improve performance and type safety because they are more efficient based on arrays; 4. Avoid abuse of enums, such as dynamic values, frequent changes or complex logic scenarios, which should be replaced by other methods. Correct use of enum can improve code quality and reduce errors, but you need to pay attention to its applicable boundaries.

Understanding Java NIO and Its Advantages Understanding Java NIO and Its Advantages Jul 08, 2025 am 02:55 AM

JavaNIO is a new IOAPI introduced by Java 1.4. 1) is aimed at buffers and channels, 2) contains Buffer, Channel and Selector core components, 3) supports non-blocking mode, and 4) handles concurrent connections more efficiently than traditional IO. Its advantages are reflected in: 1) Non-blocking IO reduces thread overhead, 2) Buffer improves data transmission efficiency, 3) Selector realizes multiplexing, and 4) Memory mapping speeds up file reading and writing. Note when using: 1) The flip/clear operation of the Buffer is easy to be confused, 2) Incomplete data needs to be processed manually without blocking, 3) Selector registration must be canceled in time, 4) NIO is not suitable for all scenarios.

How Java ClassLoaders Work Internally How Java ClassLoaders Work Internally Jul 06, 2025 am 02:53 AM

Java's class loading mechanism is implemented through ClassLoader, and its core workflow is divided into three stages: loading, linking and initialization. During the loading phase, ClassLoader dynamically reads the bytecode of the class and creates Class objects; links include verifying the correctness of the class, allocating memory to static variables, and parsing symbol references; initialization performs static code blocks and static variable assignments. Class loading adopts the parent delegation model, and prioritizes the parent class loader to find classes, and try Bootstrap, Extension, and ApplicationClassLoader in turn to ensure that the core class library is safe and avoids duplicate loading. Developers can customize ClassLoader, such as URLClassL

Exploring Different Synchronization Mechanisms in Java Exploring Different Synchronization Mechanisms in Java Jul 04, 2025 am 02:53 AM

Javaprovidesmultiplesynchronizationtoolsforthreadsafety.1.synchronizedblocksensuremutualexclusionbylockingmethodsorspecificcodesections.2.ReentrantLockoffersadvancedcontrol,includingtryLockandfairnesspolicies.3.Conditionvariablesallowthreadstowaitfor

See all articles