根据实际情况,动态创建FeignClient进行远程调用
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.feign.FeignContext;
import org.springframework.stereotype.Component;
import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
/**
*
* @author
* @date 2021/02/23
*/
@Component
// @Import(FeignClientsConfiguration.class)
public class TestFoo {
Decoder decoder;
Encoder encoder;
Client client;
Contract contract;
ErrorDecoder errorDecoder;
FeignContext context;
public TestClientInterface testClient;
/**
* 需要开启 @Import(FeignClientsConfiguration.class)
* @param client
* @param deocder
* @param encoder
* @param contract
* @param errorDecoder
*/
@Autowired
public TestFoo(Client client,Decoder deocder,Encoder encoder,Contract contract,ErrorDecoder errorDecoder) {
this.decoder = deocder;
this.encoder = encoder;
this.errorDecoder = errorDecoder;
this.contract = contract;
this.client = client;
this.testClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).errorDecoder(errorDecoder)
.contract(contract).target(TestClientInterface.class, "http://TEST-SERVICE");
}
public TestFoo(FeignContext context) {
this.context = context;
this.decoder = context.getInstance("TEST-SERVICE", Decoder.class);
this.encoder = context.getInstance("TEST-SERVICE", Encoder.class);
this.errorDecoder = context.getInstance("TEST-SERVICE", ErrorDecoder.class);
this.contract = context.getInstance("TEST-SERVICE", Contract.class);
this.client = context.getInstance("TEST-SERVICE", Client.class);
this.testClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).errorDecoder(errorDecoder)
.contract(contract).target(TestClientInterface.class, "http://TEST-SERVICE");
}
}
/**
*
* @author
* @date 2021/02/23
*/
@Component
public class DynamicFeignService {
private static final Map<String, TestClientInterface> FEIGN_CLIENT_CACHE = Maps.newConcurrentMap();
FeignContext context;
public DynamicFeignService(FeignContext context) {
this.context = context;
}
public synchronized TestClientInterface getFeignClientByServiceName(String serviceName) {
return FEIGN_CLIENT_CACHE.computeIfAbsent(serviceName, (sn) -> {
Decoder decoder = context.getInstance(serviceName, Decoder.class);
Encoder encoder = context.getInstance(serviceName, Encoder.class);
Contract contract = context.getInstance(serviceName, Contract.class);
Client client = context.getInstance(serviceName, Client.class);
ErrorDecoder errorDecoder = context.getInstance(serviceName, ErrorDecoder.class);
return Feign.builder()
.client(client)
.encoder(encoder)
.decoder(decoder)
.errorDecoder(errorDecoder)
.contract(contract)
.target(TestClientInterface.class, "http://" + sn);
});
}
}