简体   繁体   中英

How to create a console application that uses NetFlix DGS Client

I want to use the excellent-looking DGS Framework from NetFlix to make client calls against a GraphQL service.

All the examples I find assume that I'm building a service and the Java GraphQL Client is introduced as something of an afterthought.

The application from which I want to call the service is just a console application . It needs no web server, no dgsQueryExecutor or schema. Yet, when I run my application, it bombs out with loads of runtime errors about these being needed.

I'm a relative newbie in the Java/Maven/SpringBoot world and am still struggling with the concept of things starting up without my asking them; and of removing dependencies.

Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>io.m.t</groupId>
    <artifactId>t-l-g-m</artifactId>
    <version>${revision}</version>

    <properties>
        <revision>1.0.0-SNAPSHOT</revision>
        <java.version>11</java.version>
        <maven.compiler.release>${java.version}</maven.compiler.release>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.4</version>
        </dependency>

        <dependency>
            <groupId>com.netflix.graphql.dgs</groupId>
            <artifactId>graphql-dgs-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.netflix.graphql.dgs</groupId>
                <artifactId>graphql-dgs-platform-dependencies</artifactId>
                <!-- The DGS BOM/platform dependency. This is the only place you set version of DGS -->
                <version>4.5.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

And this is my main class (note: it doesn't actually do anything yet, I just want it to run without errors).

package io.m.t.l.g;

import io.m.t.l.g.config.DatabaseConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

/**
 * 1. Act as main class for spring boot application
 * 2. Also implements CommandLineRunner, so that code within run method
 * is executed before application startup but after all beans are effectively created
 */
@SpringBootApplication
@Slf4j
public class MyConsoleApplication implements CommandLineRunner {

    public static void main(String[] args) {
        log.info("STARTING THE APPLICATION");
        new SpringApplicationBuilder(MyConsoleApplication.class)
                .web(WebApplicationType.NONE)
                .run(args);
        // NOTE: different from the usual to prevent Tomcat from starting (not needed in console app)
        //SpringApplication.run(MyConsoleApplication.class, args);
        log.info("APPLICATION FINISHED");
    }

    /**
     * This method will be executed after the application context is loaded and
     * right before the Spring Application main method is completed.
     */
    @Override
    public void run(String... args) {

        log.info("For now, I just want to get to this line without runtime errors.");
    }        
}

Spring Boot console app with Netflix DGS client:

package org.example;

import com.netflix.graphql.dgs.client.GraphQLClient;
import com.netflix.graphql.dgs.client.GraphQLResponse;
import com.netflix.graphql.dgs.client.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;


@Configuration
@SpringBootApplication
public class Application implements CommandLineRunner {
    private static final Logger LOG = LoggerFactory.getLogger(Application.class);
    private static final String ENDPOINT = "https://graphql-weather-api.herokuapp.com/";

    @Bean
    GraphQLClient graphQLClient() {
        RestTemplate restTemplate = new RestTemplate(); // underlying http client for blocking calls
        // for reactive calls use MonoGraphQLClient

        return GraphQLClient.createCustom(ENDPOINT,
                (url, headers, body) -> {
                    HttpHeaders httpHeaders = new HttpHeaders();
                    headers.forEach(httpHeaders::addAll);
                    ResponseEntity<String> exchange =
                            restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(body, httpHeaders), String.class);
                    return new HttpResponse(exchange.getStatusCodeValue(), exchange.getBody());
                });
    }

    @Autowired
    private GraphQLClient client;

    public static void main(String[] args) {
        LOG.info("started");
        SpringApplication.run(Application.class, args);
        LOG.info("finished");
    }

    @Override
    public void run(String... args) {
        GraphQLResponse response = client.executeQuery("query { getCityById(id: \"2729907\") { name } }");
        String name = response.extractValueAsObject("getCityById[0].name", String.class);
        LOG.info("got city name: " + name);
    }
}

application.yml:

spring.main.web-application-type: NONE

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>gqlclient</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
    </parent>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <!-- required for RestTemplate -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-reactor-netty</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.netflix.graphql.dgs</groupId>
            <artifactId>graphql-dgs-client</artifactId>
            <version>4.9.24</version>
        </dependency>
    </dependencies>
</project>

Hope it helps.
I'd also suggest next fetching the remote schema and using it for type generation (type-safe queries and dtos).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM