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

2022-10-14 09:37:13 浏览数 (2)

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

这里使用的是OpenFeign

代码语言:javascript复制
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);
}
代码语言:javascript复制
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;
    }
}
代码语言:javascript复制
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("查询失败");
    }
}

0 人点赞