使用OpenFeign+Validator优雅对接第三方接口

例如对接百度的根据ip查询地理信息的接口

这里使用的是OpenFeign

import com.xxx.xxx.thirdparty.dto.baidu.BaiduIpInfoDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "baiduApiClient", url = "https://api.map.baidu.com")
public interface BaiduApiClient {

    // baidu access token 使用el表达式填入
    @GetMapping("/location/ip?ak=${baidu.map.ak}&coor=bd09ll")
    BaiduIpInfoDTO locationIp(@RequestParam("ip") String ip);
}
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.NotNull;


@Data
public class BaiduIpInfoDTO {

    private String address;

    private Content content;

    @NotNull
    @Range(max = 0)
    private Integer status;

    @Data
    public static class AddressDetail {

     
        private String adcode;

        private String city;

        @JsonProperty("city_code")
        private Integer cityCode;

        private String district;

        private String province;

        private String street;

        @JsonProperty("street_number")
        private String streetNumber;
    }

    @Data
    public static class Point {
        private String x;

        private String y;
    }

    @Data
    public static class Content {
        private String address;
        @JsonProperty("address_detail")
        private AddressDetail addressDetail;
        private Point point;
    }
}
public class BaiduRest {

    @Autowired
    BaiduApiClient baiduApiClient;

    @Override
    public FeignResponse getIpInfo(String ipAddress) {
        BaiduIpInfoDTO dto = baiduApiClient.locationIp(ipAddress);
        // 通过校验字段信息判断是否查询成功 BaiduApiClient也可以配置Fallback
        return FluentValidatorUtils.checkBeanField(dto).isSuccess() ?
                FeignResponse.ok(dto) : FeignResponse.fail("查询失败");
    }
}
本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
使用OpenFeign+Validator优雅对接第三方接口
例如对接百度的根据ip查询地理信息的接口 这里使用的是OpenFeign import com.xxx.xxx.thirdparty.dto.baidu.BaiduIpInfoDTO; import org.springframework.clo……
<<上一篇
下一篇>>