在前面的博客裏已經集成了通過Ribbon去調用註冊中心裏已註冊好的服務,但這樣還是會使代碼不方便維護,原因如下圖:
Feign簡介
Feign是一個聲明式的Web Service客戶端,它使得編寫Web Serivce客戶端變得更加簡單。只需要使用Feign來創建一個接口並用註解來配置它既可完成,它具備可插拔的註解支持,包括Feign註解和JAX-RS註解,Feign也支持可插拔的編碼器和解碼器。SpringCloud爲Feign增加了對SpringMVC註解的支持,還整合了Ribbon和Eureka來提供均衡負載的HTTP客戶端實現。
這段話可能看起來比較懵逼,這裏說下實際使用,前面使用Ribbon來調用服務提供者,是通過restTemplate來調用的,缺點是,多個地方調用,同一個請求要寫多次,不方便統一維護,這時候Feign來了,就可以直接把請求統一搞一個service作爲FeignClient,然後其他調用Controller需要用到的,直接注入service,直接調用service方法即可;同時Feign整合了Ribbon和Eureka,所以要配置負載均衡的話,直接配置Ribbon即可,無其他特殊地方;當然Fiegn也整合了服務容錯保護,斷路器Hystrix
Feign應用
1、在common項目裏建一個service(實際項目肯定是多個service)作爲Feign客戶端,用Feign客戶端來調用服務器提供者,當然可以配置負載均衡;Feign客戶端定義的目的,就是爲了方便給其他項目調用
修改microservice-common模塊,在pom.xml引入Feign的依賴:
<!--引入Feign依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
定義一個FeignClient,同時指定調用的服務名稱MICROSERVICE-STUDENT
建StudentClientService接口:
package com.ue.service;
import com.ue.entity.Student;
import org.springframework.cloud.netflix.feign.FeignClient;
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.RequestMapping;
import java.util.List;
/**
* Student Feign接口客戶端
* @author Administrator
*/
@FeignClient(value="MICROSERVICE-STUDENT")
public interface StudentClientService {
/**
* 根據id查詢學生信息
* @param id
* @return
*/
@GetMapping(value="/student/get/{id}")
public Student get(@PathVariable("id") Integer id);
/**
* 查詢學生信息
* @return
*/
@GetMapping(value="/student/list")
public List<Student> list();
/**
* 添加或者修改學生信息
* @param student
* @return
*/
@PostMapping(value="/student/save")
public boolean save(Student student);
/**
* 根據id刪除學生信息
* @return
*/
@GetMapping(value="/student/delete/{id}")
public boolean delete(@PathVariable("id") Integer id);
@RequestMapping("/student/ribbon")
public String ribbon();
}
2、新建一個Feign消費者項目
參考microservice-student-consumer-80模塊建一個microservice-student-consumer-feign-80模塊,代碼都複製一份,包括pom.xml
pom依賴如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ue</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-consumer-feign-80</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 修改後立即生效,熱部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>com.ue</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--ribbon相關依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--引入Feign依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
</project>
SpringCloudConfig.java:
package com.ue.config;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* SpringCloud相關配置
* @author Administrator
*/
@Configuration
public class SpringCloudConfig {
/**
* 調用服務模版
* @return
*/
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
/**
* 自定義調用規則(服務提供者掉線後不再調用,解決輪詢問題)
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
}
}
yml配置:
server:
port: 80
context-path: /
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka2001.test.com:2001/eureka/,http://eureka2002.test.com:2002/eureka/,http://eureka2003.test.com:2003/eureka/
3、在啓動類里加註解
在啓動類里加個註解@EnableFeignClients支持Feign:
package com.ue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableEurekaClient
@EnableFeignClients(value = "com.ue.*")
public class MicroserviceStudentConsumerFeign80Application {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentConsumerFeign80Application.class, args);
}
}
4、修改controller
修改StudentConsumerController.java,因爲現在是用Fiegn,所以把restTemplate去掉,改成注入service,通過調用service方法來實現服務的調用:
package com.ue.controller;
import com.ue.entity.Student;
import com.ue.service.StudentClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author Administrator
*/
@RestController
@RequestMapping("/student")
public class StudentConsumerController {
@Autowired
private StudentClientService studentClientService;
@PostMapping(value = "/save")
private boolean save(Student student) {
return studentClientService.save(student);
}
@GetMapping(value = "/list")
public List<Student> list() {
return studentClientService.list();
}
@GetMapping(value = "/get/{id}")
public Student get(@PathVariable("id") Integer id) {
return studentClientService.get(id);
}
@GetMapping(value = "/delete/{id}")
public boolean delete(@PathVariable("id") Integer id) {
try {
studentClientService.delete(id);
return true;
} catch (Exception e) {
return false;
}
}
@RequestMapping("/ribbon")
public String ribbon(){
return studentClientService.ribbon();
}
}
5、測試負載均衡
依次啓動兩個註冊中心、三個生產端、一個消費端:
然後在瀏覽器地址欄輸入http://eureka2001.test.com:2001,可看到服務提供者的註冊情況:
然後訪問http://localhost/student/list,多刷新幾次看頁面上顯示的內容: