定义 api-config.yml
添加服务声明配置
api:
path:
version: v1
service:
property:
name: pai-park-property # 用于解决服务名变化
url: # 用于本地开发时直接指定,如: http://localhost:8080
path: api # 用于配合contextPath配置
version: v1 # 用于指定版本,经实战验证下来不是太好用,因为一个工程中可能会有多个版本并存,这一个改就全改了,不再建议使用动态变理,可以直接编码进去
定义请求参数类
package cn.flyrise.pai.enterprise.feign.vo;
import java.util.Map;
public class EsbRequest {
private Map<String,Object> body;
private String serviceCode;
private String serviceScene;
public Map<String, Object> getBody() {
return body;
}
public void setBody(Map<String, Object> body) {
this.body = body;
}
public String getServiceCode() {
return serviceCode;
}
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
public String getServiceScene() {
return serviceScene;
}
public void setServiceScene(String serviceScene) {
this.serviceScene = serviceScene;
}
}
定义FeignClient接口
package cn.flyrise.pai.enterprise.feign;
import cn.flyrise.common.core.domain.Reply;
import cn.flyrise.pai.enterprise.feign.fallback.RemoteEsbClientFallbackFactory;
import cn.flyrise.pai.enterprise.feign.vo.EsbRequest;
import cn.hutool.json.JSONObject;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import static cn.flyrise.common.core.constant.SecurityConstants.FROM;
@FeignClient(
value = "pai-park-property",
contextId = "remoteEsbApi",
url = "${api.service.property.url:}",
path = "${api.service.property.path:}/esb/${api.service.contract.version:v1}",
fallbackFactory = RemoteEsbClientFallbackFactory.class
)
public interface IEsbClient {
@PostMapping("base")
public Reply<JSONObject> base(@RequestBody EsbRequest request, @RequestHeader(FROM) String from);
}
失败回调
package cn.flyrise.pai.enterprise.feign.fallback;
import cn.flyrise.common.core.domain.Reply;
import cn.flyrise.pai.enterprise.feign.IEsbClient;
import cn.flyrise.pai.enterprise.feign.vo.EsbRequest;
import cn.hutool.json.JSONObject;
public class RemoteEsbClientFallbackFactory implements IEsbClient {
@Override
public Reply<JSONObject> base(EsbRequest request, String from) {
return Reply.fail("500", "ESB访问异常");
}
}
SpringBoot Application启动类引用配置,并启用FeignClient
@EnablePaiFeignClients("cn.flyrise.*")
@PropertySource(value = {"classpath:api-config.yaml"}, factory = YamlPropertySourceFactory.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
调用示例
import static cn.flyrise.common.core.constant.SecurityConstants.FROM_IN;
@Resource
private IEsbClient esbClient;
public void test(){
final EsbRequest request = new EsbRequest();
request.setBody(new HashMap<>());
request.setServiceScene("xxx");
request.setServiceCode("xxx");
esbClient.base(request, FROM_IN);
}
更多内容参考 Feign示例 : https://api.flyrise.cn:9099/docs/open-docs/open-docs-1ctul9gkp9v0f
文档更新时间: 2024-10-29 18:39 作者:姚连洲