Feign負載均衡(五)


一、Feign定義

Feigin是服務消費者,Feign是一個聲明式的偽Http客戶端,它使得寫Http客戶端變得更簡單。使用Feign,只需要創建一個接口並注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的編碼器和解碼器。feign集成了Ribbon,利用Ribbon維護了MicroServiceCloud-Dept的服務列表信息,並且通過輪詢實現了客服端的負載均衡.而與Ribbon不同的是,通過feign只需要定義服務綁定接口聲明式的方法,優雅而簡單的實現了服務調用

簡而言之:是一個聲明式的web服務客戶端,使得Web服務端變得非常容易,只需要創建一個接口,然后在上面添加注解即可就是:接口+注解,獲取調用我們的微服務---接口編程

Feign接口編程

二、Feign操作

1、修改microservicecloud-api

pom文件添加依賴

<!-- feign遠程調用 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

新建一個DeptClientService 接口

@FeignClient(name = "MICROSERVICECLOUD-DEPT")//name是一個服務名稱,在注冊中上面
public interface DeptClientService { @RequestMapping(value = "/dept/findAll",method = RequestMethod.GET) public List<Dept> findAll(); }

2、創建microservicecloud-consumer-dept-feign工程

pom文件

 <dependencies>
        <!-- 引入自己定義的api通用包,可以使用Dept部門Entity -->
        <dependency>
            <groupId>com.yehui</groupId>
            <artifactId>microservicecloud-api</artifactId>
            <version>${project.version}</version>
            <scope>compile</scope>
        </dependency>
        <!--eureka-server服務端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

yml文件

server: port: 8087 eureka: client: register-with-eureka: true service-url: defaultZone: http://localhost:7002/eureka/,http://localhost:7003/eureka/,http://localhost:7001/eureka/
    fetch-registry: true spring: application: name: ConSumeAppStartDeptfeign

創建一個controller

@RestController public class DeptController { @Autowired private DeptClientService deptClientService; @RequestMapping("/dept/list") public List<Dept> findAll() { return deptClientService.findAll(); } }

創建啟動類

@SpringBootApplication @EnableFeignClients(basePackages = "com.yehui.feign")//掃描feignClient提供接口的包
public class ConSumeAppStartDeptfeign { public static void main(String[] args) { SpringApplication.run(ConSumeAppStartDeptfeign.class); } }

啟動測試:

  啟動3個eureka集群

  啟動3個微服務8001/8002/8003

 啟動Feign自己啟動

   Feign自帶負載均衡配置頂:

       Feign通過接口的方法調用Rest服務(之前是Ribbon+RestTemplate),該請求發送給Eureka服務器(),通過Feign直接找到服務接口,由於在進行服務調用的時候融合了Ribbon技術,所以也支持負載均衡作用

測試訪問路徑http://localhost:8087/dept/list

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM