查看原文
其他

【SFA官方翻译】:Micronaut Mastery:HTTP客户端的特定配置属性使用

影宸风洛 SpringForAll社区 2020-10-17

原文链接:https://dzone.com/articles/micronaut-mastery-using-specific-configuration-pro

作者:Hubert Klein Ikkink

译者:Emma

学习如何在微服务应用程序中使用Micronaut和Java注入简单的HTTP客户端。

Micronaut的(许多)强大功能之一是HTTP客户端。我们使用@Client注解注入一个低级HTTP客户端。或者我们基于接口定义声明性HTTP客户端,Micronaut将为其生成实现。@Client注解支持配置参数,以引用具有HTTP客户端配置属性的配置类。配置类扩展了HttpClientConfiguration以支持例如超时和连接池的配置。我们也可以添加自己的配置属性,并在我们的应用程序中使用它们。

在下面的示例中,我们使用声明性HTTP客户端访问OpenWeatherMap API。首先,我们编写一个扩展HttpClientConfiguration的类。这个类为我们提供了HTTP客户端配置属性,我们还添加了一些属性来定义调用REST API所需的OpenWeatherMap URI,路径和访问密钥。最后,我们为想要用于HTTP客户端的配置属性添加@Retryable注解。

  1. // File: src/main/java/mrhaki/micronaut/WeatherClientConfiguration.java

  2. package weather;

  3. import io.micronaut.context.annotation.ConfigurationProperties;

  4. import io.micronaut.http.client.HttpClientConfiguration;

  5. import io.micronaut.runtime.ApplicationConfiguration;

  6. import java.net.URI;

  7. import java.time.Duration;

  8. import static weather.WeatherClientConfiguration.PREFIX;

  9. /**

  10. * Custom HTTP client configuration set via application

  11. * properties prefixed with "weather.client".

  12. */

  13. @ConfigurationProperties(PREFIX)

  14. public class WeatherClientConfiguration extends HttpClientConfiguration {

  15.    public static final String PREFIX = "weather.client";

  16.    /**

  17.     * HTTP client connection pool configuration.

  18.     */

  19.    private final WeatherClientConnectionPoolConfiguration connectionPoolConfiguration;

  20.    /**

  21.     * OpenWeatherMap URI.

  22.     */

  23.    private URI url;

  24.    /**

  25.     * Path for requests sent to OpenWeatherMap.

  26.     */

  27.    private String path;

  28.    /**

  29.     * Key needed to access OpenWeatherMap API.

  30.     */

  31.    private String apiKey;

  32.    public WeatherClientConfiguration(

  33.            final ApplicationConfiguration applicationConfiguration,

  34.            final WeatherClientConnectionPoolConfiguration connectionPoolConfiguration) {

  35.        super(applicationConfiguration);

  36.        this.connectionPoolConfiguration = connectionPoolConfiguration;

  37.    }

  38.    public URI getUrl() {

  39.        return url;

  40.    }

  41.    public void setUrl(final URI url) {

  42.        this.url = url;

  43.    }

  44.    public String getPath() {

  45.        return path;

  46.    }

  47.    public void setPath(final String path) {

  48.        this.path = path;

  49.    }

  50.    public String getApiKey() {

  51.        return apiKey;

  52.    }

  53.    public void setApiKey(final String apiKey) {

  54.        this.apiKey = apiKey;

  55.    }

  56.    @Override

  57.    public ConnectionPoolConfiguration getConnectionPoolConfiguration() {

  58.        return connectionPoolConfiguration;

  59.    }

  60.    @ConfigurationProperties(ConnectionPoolConfiguration.PREFIX)

  61.    public static class WeatherClientConnectionPoolConfiguration extends ConnectionPoolConfiguration {

  62.    }

  63.    /**

  64.     * Extra configuration propertie to set the values

  65.     * for the @Retryable annotation on the WeatherClient.

  66.     */

  67.    @ConfigurationProperties(WeatherClientRetryConfiguration.PREFIX)

  68.    public static class WeatherClientRetryConfiguration {

  69.        public static final String PREFIX = "retry";

  70.        private Duration delay;

  71.        private int attempts;

  72.        public Duration getDelay() {

  73.            return delay;

  74.        }

  75.        public void setDelay(final Duration delay) {

  76.            this.delay = delay;

  77.        }

  78.        public int getAttempts() {

  79.            return attempts;

  80.        }

  81.        public void setAttempts(final int attempts) {

  82.            this.attempts = attempts;

  83.        }

  84.    }

  85. }

接下来,我们使用@Client注解编写声明性HTTP客户端作为Java接口。我们引用自定义配置并使用配置属性来设置访问OpenWeatherMap API的URI和路径。

  1. // File: src/main/java/mrhaki/micronaut/WeatherClient.java

  2. package weather;

  3. import io.micronaut.http.annotation.Get;

  4. import io.micronaut.http.client.Client;

  5. import io.micronaut.retry.annotation.Retryable;

  6. import io.reactivex.Single;

  7. import java.util.Map;

  8. // Declarative HTTP client with URL and path

  9. // fetched from the application configuration.

  10. // HTTP client configuration like pooled connections,

  11. // timeouts are defined using WeatherClientConfiguration.

  12. @Client(

  13.        value = "${weather.client.url}",

  14.        path = "${weather.client.path}",

  15.        configuration = WeatherClientConfiguration.class)

  16. // Retry accessing OpenWeatherMap REST API if error occurs.

  17. @Retryable(

  18.        attempts = "${weather.client.retry.attempts}",

  19.        delay = "${weather.client.retry.delay}")

  20. interface WeatherClient {

  21.    /**

  22.     * Get weather description for the town of Tilburg, NL.

  23.     * The APPID query parameter is filled in with the apiKey

  24.     * argument value.

  25.     *

  26.     * @param apikey OpenWeatherMap API key to access REST API.

  27.     * @return Response data from REST API.

  28.     */

  29.    @Get("weather?q=Tilburg,nl&APPID={apikey}")

  30.    Single<Map<String, Object>> tilburg(String apikey);

  31. }

最后,我们编写了一个控制器,它使用声明性HTTP客户端WeatherClient来获取荷兰蒂尔堡镇的天气描述:

  1. // File: src/main/java/mrhaki/micronaut/WeatherController.java

  2. package weather;

  3. import io.micronaut.http.MediaType;

  4. import io.micronaut.http.annotation.Controller;

  5. import io.micronaut.http.annotation.Get;

  6. import io.reactivex.Single;

  7. import java.util.List;

  8. import java.util.Map;

  9. /**

  10. * Controller to expose data from the

  11. * OpenWeatherMap REST API.

  12. */

  13. @Controller("/weather")

  14. public class WeatherController {

  15.    private final WeatherClient client;

  16.    private final WeatherClientConfiguration configuration;

  17.    public WeatherController(

  18.            final WeatherClient client,

  19.            final WeatherClientConfiguration configuration) {

  20.        this.client = client;

  21.        this.configuration = configuration;

  22.    }

  23.    /**

  24.     * Get weather data for town Tilburg, NL and get the

  25.     * weather description to return.

  26.     *

  27.     * @return Weather description as text.

  28.     */

  29.    @Get(value = "/tilburg", produces = MediaType.TEXT_PLAIN)

  30.    public Single<String> weatherInTilburg() {

  31.        return client.tilburg(configuration.getApiKey())

  32.                     .map(response -> getWeatherDescription(response));

  33.    }

  34.    /**

  35.     * Get weather description from response data.

  36.     *

  37.     * @param data Response data from OpenWeatherMap API.

  38.     * @return Textual description of weather.

  39.     */

  40.    private String getWeatherDescription(final Map<String, Object> data) {

  41.        final List<Object> weatherList = (List<Object>) data.get("weather");

  42.        final Map<String, Object> weather = (Map<String, Object>) weatherList.get(0);

  43.        final String description = (String) weather.get("description");

  44.        return description;

  45.    }

  46. }

在application.yml配置文件中,我们设置配置属性的值:

  1. # File: src/main/resources/application.yml

  2. ...

  3. weather:

  4.  client:

  5.    url: http://api.openweathermap.org/

  6.    path: /data/2.5/

  7.    api-key: 39caa...

  8.    read-timeout: 500ms

  9.    retry:

  10.      attempts: 2

  11.      delay: 5s

当我们运行我们的应用程序并使用HTTPie访问URL http:// localhost:8080 / weather / tilburg时,我们会得到天气描述:

  1. $ http :8080/weather/tilburg

  2. HTTP/1.1 200 OK

  3. Content-Length: 13

  4. Content-Type: text/plain;charset=UTF-8

  5. moderate rain

用Micronaut 1.0.0.M4编写。

推荐: 【SFA官方翻译】:Spring中的组件扫描

上一篇:译:【SFA译】:让你的团队为微服务做准备——第2部分

关注公众号


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存