前言

openFeign 是作为微服务之间调用的解决方案,每个微服务项目是必不可少的。固定的fegin接口调用只能调用某个固定URI地址,遇见服务调用不同地址需求就无法支持,所以需要动态Feign接口调用。
ex:获取资源信息去A或在B服务器获取。

一. 动态Feign逻辑处理

1. 全局开启Feign接口动态调用

@SpringBootApplication
@EnableFeignClients
public class UnionApplication {
    public static void main(String[] args) {
        SpringApplication.run(UnionApplication.class, args);
    }
}

2. Feign配置

FeignClient中 url 为空。

import feign.Headers;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;

import java.net.URI;
import java.util.Map;


@FeignClient(name = "cyf-feign",url = "EMPTY")
public interface CyfFeignClient {
    /**
     * @param host
     * @param getParkingInfoBo
     * @return
     */
    @RequestLine("POST /parking/getParkingById")
    @Headers({
            "Content-Type: application/json",
            "Accept: application/json"
    })
    Map getParkingInfo(URI host , @RequestBody GetParkingInfoBo getParkingInfoBo);

3. 注入FeignClient

@Slf4j
@Service
@Import(FeignClientsConfiguration.class)
public class CyfServiceImpl {

  private CyfFeignClient cyfFeignClient;

  @Autowired
  public CyfServiceImpl(Decoder decoder, Encoder encoder) {
      cyfFeignClient = Feign.builder()
              .encoder(encoder)
              .decoder(decoder)
              .target(Target.EmptyTarget.create(CyfFeignClient.class));
  }
  

  public void compileCyf() {
  		//动态url地址 
        String uri = "http://" + parkPayConfig.getIp() + ":" + parkPayConfig.getPort();
       Map parkingInfo = cyfFeignClient.getParkingInfo(URI.create(uri), getParkingInfoBo);
  }
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐