<Spring Cloud>入門三 Feign
阿新 • • 發佈:2019-01-13
1.Feign
之前使用的是Ribbon+RestTemplate呼叫,通過的是微服務的名字進行呼叫,實現負載均衡
但是為了滿足介面程式設計,提供了Feign
2.實現
2.1引入座標
在 ms-common-api 和 ms-consumer-dept-80-feign 引入座標
<!--feign 客戶端負載均衡--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2.2 在 ms-common-api 實現呼叫
package org.maple.service; import org.maple.entity.Dept; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; /** * @author mapleins * @Date 2019-01-12 23:10 * @Desc 通過介面和註解 面向介面程式設計訪問微服務 **/ @FeignClient("ms-provider-dept")public interface DeptClientService { @PostMapping("/dept/add") boolean add(@RequestBody Dept dept); @GetMapping("/dept/get/{id}") Dept get(@PathVariable("id") Long id); @GetMapping("/dept/list") List<Dept> list(); }
2.3修改 dept-80-feign的啟動類
package org.maple; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @author mapleins * @Date 2019-01-09 20:26 * @Desc **/ @SpringBootApplication @EnableEurekaClient @EnableFeignClients(basePackages = {"org.maple.service"}) //掃描ms-common-api中的service包 public class App_Consumer_Dept_80_Feign { public static void main(String[] args) { SpringApplication.run(App_Consumer_Dept_80_Feign.class, args); } }
2.4 controller層
這樣就相當於不是去呼叫微服務去程式設計,而是通過controller呼叫service層,實現介面程式設計,並且自帶ribbon的輪詢演算法
package org.maple.controller; import org.maple.entity.Dept; import org.maple.service.DeptClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author mapleins * @Date 2019-01-09 20:10 * @Desc **/ @RestController public class DeptController_Consumer { @Autowired private DeptClientService service; @GetMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id){ return service.get(id); } @GetMapping("/consumer/dept/list") public List<Dept> list(){ return service.list(); } @PostMapping("/consumer/dept/add") public boolean add(Dept dept){ return service.add(dept); } }