
之前寫了篇《Feign在實際項目中的應用實踐總結》
Feign在實際項目中的應用實踐總結 - 沐風之境 - 博客園?www.cnblogs.com總結了在一般項目中如何使用Feign這個提升開發效率的利器。最近在看Feign的文檔的時候發現了之前遺漏的一些點,所以寫了這篇文章進行補充。
pom.xml
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
JavaConfig
@Slf4j
@Configuration
@EnableFeignClients
public class FeignConfig {@Resourceprivate SimpleDiscoveryProperties simpleDiscoveryProperties;// 在K8s環境中不需要服務注冊中心可以自定義一個DiscoveClient的Bean,作為簡單的一個服務列表@Beanpublic DiscoveryClient discoveryClient() {log.info(JSON.toJSONString(simpleDiscoveryProperties)); // 這里打印了加載的配置參數return new SimpleDiscoveryClient(simpleDiscoveryProperties);}
}
配置(在里面寫服務的路由配置):
spring:cloud:loadbalancer:ribbon:enabled: falsediscovery:client:simple:instances:feign-attempt-client:- uri: http://localhost:8080
為什么要使用本地的服務列表?
服務部署在K8s環境中,可以使用k8s提供的DNS解析和負載均衡功能。所以不需要再引入一個服務注冊中心組建導致復雜性的增加。
使用
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;@FeignClient(name = "feign-attempt-client")
public interface FeignServerClient {@GetMapping("/feign/server/hello-world/hello")String hello();
}
運行單元測試
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import static org.junit.jupiter.api.Assertions.*;@SpringBootTest
class FeignServiceClientTest {@Resourceprivate FeignServiceClient feignServiceClient;@Testvoid hello() {final String res = feignServiceClient.hello(); // HTTP請求返回字符串“Hi!”assertEquals(res, "Hi!");}
}
運行細節
加載的服務路由配置,可以看到instances的對象加載了我們定義的feign-attempt-client服務,它包含了一個服務實例。為什么只要定義個服務實例呢?因為我們服務是部署在K8s上的。k8s會幫我們做多實例的負載均衡的工作
{"instances": {"feign-attempt-client": [{"host": "localhost","metadata": {},"port": 8080,"secure": false,"serviceId": "feign-attempt-client","uri": "http://localhost:8080"}]},"local": {"host": "172.16.8.55","metadata": {},"port": 8080,"secure": false,"serviceId": "application","uri": "http://172.16.8.55:8080"},"order": 0
}