Skip to content

在 Spring 中使用

概述

Solpic通过简单的Bean配置就可以整合到Spring体系中,这里以SpringBoot为例。

引入依赖

确保项目中至少引入了spring-boot-starter依赖,例如:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>${spring-boot.version}</version>
</dependency>

引入Solpic依赖:

xml
<dependency>
    <groupId>cn.vlts</groupId>
    <artifactId>solpic-core</artifactId>
    <version>${solpic.version}</version>
</dependency>

配置和使用

一般情况下,一个JVM应用应该只需要一个HTTP客户端,可以考虑这样进行配置:

java
@SuppressWarnings("rawtypes")
@Configuration
public class SolpicAutoConfiguration {

    @Bean
    public HttpClient httpClient() {
        return Solpic.newHttpClientBuilder()
                .type(HttpClientType.JDK_HTTPCLIENT)
                .option(HttpOptions.HTTP_CLIENT_METRICS, true)
                .build();
    }

    @Bean
    public Codec codec() {
        return Solpic.loadCodec();
    }

    @Bean
    public SolpicTemplate solpicTemplate(HttpClient httpClient, Codec codec) {
        return Solpic.newSolpicTemplateBuilder().httpClient(httpClient).codec(codec).build();
    }

    @Bean
    public OneWaySolpicTemplate oneWaySolpicTemplate(HttpClient httpClient, Codec codec) {
        return Solpic.newOneWaySolpicTemplateBuilder().httpClient(httpClient).codec(codec).build();
    }
}

然后可以使用构造注入或者属性注入使用HttpClient或者SolpicTemplate,例如:

java
@Autowired
private SolpicTemplate solpicTemplate;

String r = solpicTemplate.getForObject("https://httpbin.org/get", String.class);

贡献者

页面历史

Released under the MIT License.