场景说明: 因项目业务需要让用户配置API接口地址(http)来作为数据源,项目之前已经引入了openfeign,不想引入其他第三方依赖,所以想通过openfeign做动态url调用
依赖
springboot 2.6.5需要3.0+
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.1</version>
</dependency>
启用openfeign
@EnableFeignClients启用feign
@SpringBootApplication
@EnableFeignClients
public class SpringBootOpenfeignApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootOpenfeignApplication.class, args);
}
}
接口
通过URI参数传入http接口地址,调用时会自动将uri参数作为请求地址,url必须填写,只是占位,因为url必须要传
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import java.net.URI;
@FeignClient(name = "API-SERVICE", url = "url-placeholder")
public interface ApiClient {
@PostMapping(value = "")
String getData(URI uri);
}
调用
@RestController
public class PostController {
@Resource
private ApiClient apiClient;
@GetMapping()
public Object get() {
String url = "http://api.k780.com/?app=weather.history&weaId=1&date=20150720&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
return apiClient.getData(URI.create(url));
}
}