参考: https://www.jianshu.com/p/e99c4083935e
以下为自我实践
在单体项目也常常需要使用三方调用,类似的实现可以使用httpClient调用之类的,但是接口代理注入的方式来的优雅的许多,比如Feign,那么如何实现Springboot不依赖SpringCloud进行调用呢?
1.导入依赖
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>8.18.0</version>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
<version>8.18.0</version>
</dependency>
2.Feign接口
public interface AkshareFeign {
@RequestLine("GET /api/stock_em_account")
@Headers({"Content-Type: application/json;utf-8"})
Object getStockEmAccount();
}
3.自定义配置
@Configuration
public class WebConfig {
@Bean
AkshareFeign akshareFeign(MyDecoder myDecoder) {
// 自定义decoder
return Feign.builder().decoder(myDecoder).target(AkshareFeign.class, "http://127.0.0.2:8080");
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.FeignException;
import feign.Response;
import feign.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import feign.codec.Decoder;
import java.io.IOException;
import java.lang.reflect.Type;
/**
* @author luodada
*/
@Component
public class CustomDecoder implements Decoder {
@Autowired
private ObjectMapper mapper;
@Override
public Object decode(Response response, Type type) throws IOException, FeignException {
// 可扩展自定义解析
String result = Util.toString(response.body().asReader());
return mapper.readValue(result, Object.class);
}
}
以上。