目錄
前言
本章的內容是在上章的Hystrix一個基礎上的一個擴充
重點的話本章是Hystrix與Feign的一個結合
上章情況
本章的大底思路
Hystrix服務集羣的搭建
服務名稱:microservice-student-provider-hystrix
pom.xml
和之前的不變
<?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>
<!--保持使用版本的一致1.0-SNAPSHOT-->
<parent>
<groupId>com.liwangwang</groupId>
<artifactId>springcloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-provider-hystrix</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--相當於全局的一個依賴關係,這個導入能確保整個項目使用的包版本一致
比如全局中的: spring-cloud-dependencies
spring-boot-dependencies
druid-spring-boot-starter
-->
<dependency>
<groupId>com.liwangwang</groupId>
<artifactId>microservice-common</artifactId>
</dependency>
<!--處理web請求-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--test測試的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--使用的數據庫關係映射框架是jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--使用的是mysql數據庫-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--使用tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!--druid數據源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</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.liwangwang</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- actuator監控引入,點擊後的追責 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--添加註冊中心Eureka相關配置,就是說這個是客戶端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--Hystrix相關依賴,用來處理服務處理異常情況-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
yml文件配置,注意更改名稱
---
server:
port: 1004
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/context?useUnicode=true&characterEncoding=utf8
username: root
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application: # 設置應用的基本信息(名稱
name: microservice-student
profiles: provider-hystrix-1004
eureka:
instance:
hostname: localhost #eureka客戶端主機實例名稱
appname: microservice-student #客戶端服務名
instance-id: microservice-student:1004 #客戶端實例名稱
prefer-ip-address: true #是否顯示IP
client:
service-url:
#設置與Eureka註冊中心交互的地址,是所有註冊中心
defaultZone: http://eureka2001.javawwl.com:2001/eureka/,http://eureka2002.javawwl.com:2002/eureka/,http://eureka2003.javawwl.com:2003/eureka/ #把服務註冊到eureka註冊中心
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 2000
info:
groupId: com.liwangwang.springcloud
artifactId: microservice-student-provider-1004
version: 1.0-SNAPSHOT
userName: http://www.javawwl.com
phone: 123456
---
server:
port: 1005
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/context?useUnicode=true&characterEncoding=utf8
username: root
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application: # 設置應用的基本信息(名稱
name: microservice-student
profiles: provider-hystrix-1005
eureka:
instance:
hostname: localhost #eureka客戶端主機實例名稱
appname: microservice-student #客戶端服務名
instance-id: microservice-student:1005 #客戶端實例名稱
prefer-ip-address: true #是否顯示IP
client:
service-url:
#設置與Eureka註冊中心交互的地址,是所有註冊中心
defaultZone: http://eureka2001.javawwl.com:2001/eureka/,http://eureka2002.javawwl.com:2002/eureka/,http://eureka2003.javawwl.com:2003/eureka/ #把服務註冊到eureka註冊中心
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 2000
info:
groupId: com.liwangwang.springcloud
artifactId: microservice-student-provider-1005
version: 1.0-SNAPSHOT
userName: http://www.javawwl.com
phone: 123456
---
server:
port: 1006
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/context?useUnicode=true&characterEncoding=utf8
username: root
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application: # 設置應用的基本信息(名稱
name: microservice-student
profiles: provider-hystrix-1006
eureka:
instance:
hostname: localhost #eureka客戶端主機實例名稱
appname: microservice-student #客戶端服務名
instance-id: microservice-student:1006 #客戶端實例名稱
prefer-ip-address: true #是否顯示IP
client:
service-url:
#設置與Eureka註冊中心交互的地址,是所有註冊中心
defaultZone: http://eureka2001.javawwl.com:2001/eureka/,http://eureka2002.javawwl.com:2002/eureka/,http://eureka2003.javawwl.com:2003/eureka/ #把服務註冊到eureka註冊中心
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 2000
info:
groupId: com.liwangwang.springcloud
artifactId: microservice-student-provider-1006
version: 1.0-SNAPSHOT
userName: http://www.javawwl.com
phone: 123456
main類
package com.liwangwang.microservicestudentproviderhystrix;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableCircuitBreaker
@EntityScan("com.liwangwang.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentProviderHystrixApplication.class, args);
}
}
重要Controller
package com.liwangwang.microservicestudentproviderhystrix.controller;
import com.liwangwang.microservicecommon.entity.Student;
import com.liwangwang.microservicestudentproviderhystrix.service.StudentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/student")
public class StudentProviderController {
@Value("${server.port}")
private String port;
@Autowired
private StudentService studentService;
@PostMapping(value="/save")
public boolean save(Student student){
try{
studentService.save(student);
return true;
}catch(Exception e){
return false;
}
}
@GetMapping(value="/list")
public List<Student> list(){
return studentService.list();
}
@GetMapping(value="/get/{id}")
public Student get(@PathVariable("id") Integer id){
return studentService.findById(id);
}
@GetMapping(value="/delete/{id}")
public boolean delete(@PathVariable("id") Integer id){
try{
studentService.delete(id);
return true;
}catch(Exception e){
return false;
}
}
@RequestMapping("/ribbon")
public String ribbon(){
return "工號【"+port+"】正在爲您服務";
}
/**
* 測試Hystrix服務降級
* @return
* @throws InterruptedException
*/
// @HystrixCommand(fallbackMethod="hystrixFallback")
@GetMapping(value="/hystrix")
public Map<String,Object> hystrix() throws InterruptedException{
Thread.sleep(200);
return studentService.hystrix();
}
// public Map<String,Object> hystrixFallback() throws InterruptedException{
// Map<String,Object> map=new HashMap<String,Object>();
// map.put("code", 500);
// map.put("info", "系統【"+port+"】繁忙,稍後重試");
// return map;
// }
}
啓動後,如此就是註冊成功
整合Hystrix與Feign
公共模塊(microservice-common)
pom.xml
沒有動什麼
<?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>
<!--保持使用版本的一致1.0-SNAPSHOT-->
<parent>
<groupId>com.liwangwang</groupId>
<artifactId>springcloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-common</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--處理web請求-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--test測試的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--使用的數據庫關係映射框架是jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--使用的是mysql數據庫-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--引入Feign依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
新創建一個StudentClientFallbackFactory ,
繼承於我們寫在客戶端要調用的service層(StudentClientService)
package com.liwangwang.microservicecommon.service;
import com.liwangwang.microservicecommon.entity.Student;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class StudentClientFallbackFactory implements FallbackFactory<StudentClientService> {
@Override
public StudentClientService create(Throwable throwable) {
return new StudentClientService() {
@Override
public Student get(Integer id) {
return null;
}
@Override
public List<Student> list() {
return null;
}
@Override
public boolean save(Student student) {
return false;
}
@Override
public boolean delete(Integer id) {
return false;
}
@Override
public String ribbon() {
return null;
}
@Override
public Map<String, Object> hystrix() { Map<String,Object> map=new HashMap<String,Object>();
map.put("code", 500);
map.put("info", "系統繁忙,稍後重試");
return map;
}
};
}
}
StudentClientService
package com.liwangwang.microservicecommon.service;
import com.liwangwang.microservicecommon.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;
import java.util.Map;
/**
* Student Feign接口客戶端
* @author Administrator
*
*/
@FeignClient(value="MICROSERVICE-STUDENT",fallbackFactory=StudentClientFallbackFactory.class)
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();
/**
* 測試Hystrix服務降級
* @return
*/
@GetMapping(value="/student/hystrix")
public Map<String,Object> hystrix();
}
其他保持不變。
消費者(microservice-student-consumer-feign-80)
pom.xml
<?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>
<!--保持使用版本的一致1.0-SNAPSHOT-->
<parent>
<groupId>com.liwangwang</groupId>
<artifactId>springcloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-consumer-feign-80</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--相當於全局的一個依賴關係,這個導入能確保整個項目使用的包版本一致
比如全局中的: spring-cloud-dependencies
spring-boot-dependencies
druid-spring-boot-starter
-->
<dependency>
<groupId>com.liwangwang</groupId>
<artifactId>microservice-common</artifactId>
</dependency>
<!--處理web請求-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--test測試的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--使用的數據庫關係映射框架是jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--使用的是mysql數據庫-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--使用tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</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.liwangwang</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--Eureka的包,我們在這個客戶端重點使用的是客戶端的包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!--使用了ribbon的用法-->
<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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
yml文件,
此次更改了一個ribbon默認的超時時間
和開啓了Hystrix
server:
port: 80
context-path: /
eureka:
client:
service-url:
#設置與Eureka註冊中心交互的地址,查詢服務和註冊服務用到
defaultZone: http://eureka2001.javawwl.com:2001/eureka/,http://eureka2002.javawwl.com:2002/eureka/,http://eureka2003.javawwl.com:2003/eureka/
register-with-eureka: false #false 由於該應用爲客戶端,所以設置爲false,代表不向註冊中心註冊自己。
fetch-registry: true #true 由於消費者(客戶端)就是尋找服務實例,它需要去檢索服務,所以設置爲true
#ribbon: # 設置一個前端的失敗時間,如果超時,則代表失敗
# ReadTimeout: 100
# ConnectTimeout: 100
ribbon: # 設置一個前端的失敗時間,如果超時,則代表失敗
ReadTimeout: 9000
ConnectTimeout: 9000
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 2000
main類方法
Controller文件
package com.liwangwang.microservicestudentconsumerfeign80.controller;
import com.liwangwang.microservicecommon.entity.Student;
import com.liwangwang.microservicecommon.service.StudentClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/student")
public class StudentConsumerController {
@Autowired
private StudentClientService studentClientService;
@Autowired
private RestTemplate restTemplate;
@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();
}
/**
* 測試Hystrix服務降級
* @return
*/
@GetMapping("/hystrix")
public Map<String,Object> hystrix(){
return studentClientService.hystrix();
}
}
監控服務集羣的平臺turbine
創建一個項目:microservice-student-consumer-hystrix-turbine-91
pom.xml所需依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-turbine</artifactId>
</dependency>
yml文件的配置
多了turbine和spring.application.name
server:
port: 91
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001.javaxl.com:2001/eureka/,http://eureka2002.javaxl.com:2002/eureka/,http://eureka2003.javaxl.com:2003/eureka/
turbine:
app-config: microservice-student # 指定要監控的應用名稱
clusterNameExpression: "'default'" #表示集羣的名字爲default
spring:
application:
name: turbine
main主類上加上:
測試
http://localhost:91/turbine.stream
輸入http://localhost:90/hystrix進入儀表盤,輸入地址
點擊後進入
後記
直接放整理
一、Hystrix服務集羣(三合一)
操作項目:microservice-student-provider-hystrix(服務者)
與之前的服務集羣的搭建相差不大
1、 pom依賴不變
2、 yml文件大致不變,加上profiles:name的唯一標識
3、 層次結構方面:
因爲上次我們已經把Hystrix的使用方法講的差不多了,
所以此次的一個要點在於要用Hystrix結合與服務端的Feign來學習
在結構上:我們需要整理一下方法放到service層
在hystrix()方法本體上:去掉@HystrixCommand註解(因爲我們會配合Feign來進行降級),把業務邏輯代碼放到實現層(impl層)
二、Feign與Hystrix配合使用
1、操作項目爲:microservice-common(公共模塊層)
因爲所有項目的實體類,service層都放到了這裏,當然我們也可以把回調的方法放到這裏進行一個配置。
① 創建一個新類StudentClientFallbackFactory(一個回調工廠)
繼承於我們寫在客戶端要調用的service層(StudentClientService)
② StudentClientService類加上註解內容
@FeignClient(value=“MICROSERVICESTUDENT”,
fallbackFactory=StudentClientFallbackFactory.class)
OK了,
2、操作項目爲: microservice-student-consumer-feign-80(消費者)
① yml文件
加上開啓與Hystrix一起使用的配置,和更改一下默認超時時間
ribbon:
ReadTimeout: 9000
ConnectTimeout: 9000
feign:
hystrix:
enabled: true
② main主文件
加上去尋找公共項目的的註解,如果沒有的話是沒辦法調用的。
@ComponentScan(basePackages = “com.liwangwang.microservicecommon”)
額,還有一個給這個項目增加一個請求,要記得
三、監控集羣用
沒什麼特殊的技術點,所以不講了,看文檔安裝就行