在 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);