五、SpringCloud之Feign負載均衡
阿新 • • 發佈:2018-12-30
Feign是一個宣告式Web服務客戶端,能讓編寫web客戶端更加簡單,建立一個介面並在上面添加註解去使用Feign,它支援Feign註解和JAX-RS註解。Feign也支援可插拔式的編碼器和解碼器,Feign 預設整合了Eureka和Ribbon實現客戶端負載均衡。
Feign核心是使得編寫Java Http客戶端變得更容易,使用介面和註解(類似Mybatis中Dao和@Mapper)來完成對服務提供者介面的繫結,從而簡化操作。Feign集成了Ribbon,可以利用Ribbo實現負載均衡。
官方文件:
以下內容是基於上一節的工程,使用Feign 實現服務間通訊。
(1)、模仿microservice-dept-consumer-80 新建一個消費者module模組 microservice-dept-consumer-feign
pom.xml
<!-- Feign依賴 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
(2)、修改配置檔案
server:
context-path: /
port: 80
spring:
application:
name: microservice-dept-consumer-feign #服務名
eureka:
client:
register-with-eureka: false #false表示不向註冊中心註冊自己,因為本身應用就是註冊中心
service-url:
#叢集配置
defaultZone: http://eureka-server-5001.com:5001/eureka/,http://eureka-server-5002.com:5002/eureka/,http://eureka-server-5003.com:5003/eureka/
(3)、修改api模組microservice-common
,新建DeptClientService.java
介面
/**
* 宣告feign介面
* @author dave
*
*/
@FeignClient(value = "MICROSERVICE-DEPT") // 指定呼叫哪個服務
public interface DeptClientService {
@GetMapping("/depts")
public List<Dept> depts();
@GetMapping("/dept/{id}")
public Dept dept(@PathVariable(value = "id") Integer id);
@PostMapping("/dept")
public Dept insert(@RequestBody Dept dept);
@PutMapping("/dept")
public Dept update(@RequestBody Dept dept);
@DeleteMapping("/dept/{id}")
public boolean delete(@PathVariable(value = "id") Integer id);
}
(4)建立Controller類DeptConsumerController.java
@RequestMapping("/consumer")
@RestController
public class DeptConsumerController {
@Autowired
private DeptClientService deptClientService; //使用Feign介面
@GetMapping("/depts")
public List<Dept> depts() {
return deptClientService.depts();
}
@GetMapping("/dept/{id}")
public Dept dept(@PathVariable(value = "id") Integer id) {
return deptClientService.dept(id);
}
@PostMapping("/dept")
public Dept insert(@RequestBody Dept dept) {
return deptClientService.insert(dept);
}
@PutMapping("/dept")
public Dept update(@RequestBody Dept dept) {
return deptClientService.update(dept);
}
@DeleteMapping("/dept/{id}")
public boolean delete(@PathVariable(value = "id") Integer id) {
try {
deptClientService.delete(id);
return true;
} catch (Exception e) {
return false;
}
}
}
(5)建立主啟動類DeptConsumerFeignApplication.java
,開啟Feign
@EnableFeignClients //開啟Feign
@EnableEurekaClient
@SpringBootApplication
public class DeptConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(DeptConsumerFeignApplication.class, args);
}
}
(6)分別啟動Eureka sever、服務提供者 和 microservice-dept-consumer-feign,訪問介面預設會使用輪詢策略。