eureka(注冊中心)組件
#先添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
#配置application.yml
eureka:
client:
# 表示是否將自己注冊到Eureka Server,默認為true,
register-with-eureka: false
# 表示是否從Eureka Server獲取注冊資訊,默認為true,
fetch-registry: false
# 設定與Eureka Server互動的地址,查詢服務和注冊服務都需要依賴這個地址,默認是http://localhost:8000/eureka ;多個地址可使用,分隔
service-url:
defaultZone: http://localhost:8000/eureka/
server:
eviction-interval-timer-in-ms: 1000 # 續期時間,即掃描失效服務的間隔時間(單位毫秒,默認是60*1000)測驗時關閉自我保護機制,保證不可用服務及時踢出
enableSelfPreservation: false # 設為false,關閉自我保護
#啟動類上加注解
@EableEurekaServer
ribbon(負載均衡)組件
#ribbon依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>
#配置ribbon的application.yml檔案
ribbon:
MaxAutoRetries: 2 #最大重試次數,當Eureka中可以找到服務,但是服務連不上時將會重試
MaxAutoRetriesNextServer: 3 #切換實體的重試次數
OkToRetryOnAllOperations: false #對所有操作請求都進行重試,如果是get則可以,如果是post,put等操作沒有實作冪等的情況下是很危險的,所以設定為false
ConnectTimeout: 5000 #請求連接的超時時間
ReadTimeout: 6000 #請求處理的超時時間
feign(負載均衡,遠程呼叫)組件
#feign組件的依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
#定義FeignClient介面
在client2中創建client包,定義查詢client1的客戶端該用介面,
@FeignClient(value = "TEST-PRODUCER1")//呼叫的唯一標識
public interface ClientInterface {
//遠程呼叫client服務中的test01介面
@GetMapping("/test/getString")//標識遠程呼叫的http的方法型別是什么
public String test01();
}
#啟動類上加@EnableFeignClients注解
Feign作業原理如下:
1、 啟動類添加@EnableFeignClients注解,Spring會掃描標記了@FeignClient注解的介面,并生成此介面的代理物件
2、@FeignClient(value = "TEST-CLIENT1")即指定了cms的服務名稱,Feign會從注冊中心獲取cms服務串列,并通過負載均衡演算法進行服務呼叫,
3、在介面方法 中使用注解 @GetMapping("/test/getString"),指定呼叫的url,Feign將根據url進行遠程呼叫,
Feign注意點
SpringCloud對Feign進行了增強兼容了SpringMVC的注解 ,我們在使用SpringMVC的注解時需要注意:
1、feignClient介面 有引數在引數必須加@PathVariable("XXX")和@RequestParam("XXX")
2、feignClient回傳值為復雜物件時其型別必須有無參建構式,
zuul(服務網關)組件
#zuul組件和eureka-client使用的方式
#添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-client</artifactId>
</dependency>
#配置application.yml檔案
#注冊到eureka 服務端
eureka:
client:
service-url:
defaultZone: http://localhost:8000/eureka
zuul:
#轉發是帶頭部資訊,攜帶cookie資訊
sensitive-headers:
#啟動類上加@EnableZuulProxy注解,支持網關路由
zuul過濾器
創建一個類繼承ZuulFilter抽象類
@Component //交給Ioc處理
public class TestZuulFilter extends ZuulFilter {
}
指定當前過濾器的型別(繼承ZuulFilter父類的方法)
@Override
/*PRE:在請求被路由之前呼叫,可以使用這種過濾器實作身份驗證、在集群中選擇請求的微服務、記錄除錯Log等,
*ROUTE:將請求路由到對應的微服務,用于構建發送給微服務的請求,
*POST:在請求被路由到對應的微服務以后執行,可用來為Response添加HTTP Header、將微服務的Response發送給客戶端*等,
*ERROR:在其他階段發生錯誤時執行該過濾器,
*/
public String filterType() {
return FilterConstants.PRE_TYPE;
}
指定過濾器的執行順序
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
}
配置是否啟用
@Override
public boolean shouldFilter() {
// 開啟當前過濾器
return true;
}
指定過濾器中的具體業務
@Override
public Object run() throws ZuulException {
@Override
public Object run() throws ZuulException {
//1. 獲取Request物件
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
//2. 獲取token引數
String token = request.getParameter("token");
//3. 對比token
if(token == null || !"123".equalsIgnoreCase(token)) {
//4. token校驗失敗,直接回應資料
baseResp.setMessage("驗證失敗");
currentContext.getResponse().setContentType("text/html;charset=UTF-8");
currentContext.setResponseBody(baseResp.toString());
//停止繼續執行,
currentContext.setSendZuulResponse(false)
}
return null;
}
zuul的降級
創建一個類實作FallbackProvider
@Component //交給Ioc處理
public class ZuulFallBack implements FallbackProvider {}
重寫兩個方法
@Override
public String getRoute() {
return "*"; // 代表指定全部出現問題的服務,都走這個降級方法
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
System.out.println("降級的服務:" + route);
cause.printStackTrace();
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
// 指定具體的HttpStatus
return HttpStatus.INTERNAL_SERVER_ERROR;
}
@Override
public int getRawStatusCode() throws IOException {
// 回傳的狀態碼
return HttpStatus.INTERNAL_SERVER_ERROR.value();
}
@Override
public String getStatusText() throws IOException {
// 指定錯誤資訊
return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
// 給用戶回應的資訊
String msg = "當前服務:" + route + "出現問題!!!";
return new ByteArrayInputStream(msg.getBytes());
}
@Override
public HttpHeaders getHeaders() {
// 指定回應頭資訊
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
config組件
本地配置
#添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
#配置appication.yml檔案
spring:
application:
name: spring-cloud-config-server
profiles:
active: native # 配置使用本地儲存
cloud:
config:
server:
native:
search-locations: classpath:properties/ # 搜索src/main/resource 下的properties檔案夾下的檔案
#在resource下創建檔案prpoperties檔案下創建
neo-config-dev.properties //開發環境
neo-config-pro.properties //產品環境
neo-config-test.properties //測驗環境
#啟動類上加@EenableConfigServer,激活對配置中心的支持
#測驗http://localhost:8006/neo-config/dev
客戶端配置
#客戶端上加的依賴包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
#將application.yml改為bootstrap.yml檔案
##config-客戶端的組態檔`
spring:
application:
name: zuul-eureka
cloud:
config:
discovery:
enabled: true
service-id: config-server
name: shop-config
profile: dev
spring.application.name:對應{application}部分
spring.cloud.config.profile:對應{profile}部分
spring.cloud.config.label:對應git的分支,如果配置中心使用的是本地存盤,則該引數無用
spring.cloud.config.uri:配置中心的具體地址
spring.cloud.config.discovery.service-id:指定配置中心的service-id,便于擴展為高可用配置集群,
特別注意:上面這些與spring-cloud相關的屬性必須配置在bootstrap.properties中,config部分內容才能被正確加載,因為config的相關配置會先于application.properties,而bootstrap.properties的加載也是先于application.properties,
git環境配置
#在config-server端添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
#服務端的組態檔
server:
port: 8006
spring:
application:
name: spring-cloud-config-server
cloud:
config:
server:
git:
uri: https://github.com/miaohangbo/config-repo.git/ # 配置git倉庫的地址
search-paths: config-repo # git倉庫地址下的相對地址,可以配置多個,用,分割,
#可以不用寫
username: miaohangbo # git倉庫的賬號
password: aini59852369 # git倉庫的密碼
refresh重繪
#在客戶端添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
#開啟更新機制
需要給加載變數的類上面加載`@RefreshScope`,在客戶端執行`/refresh`的時候就會更新此類下面的變數值,
#在客戶端組態檔加入
management.endpoints.web.exposure.include=refresh
#`http://localhost:8003/actuator/refresh`
Hystyix服務熔斷、降級
使用Hystyix
<!-- Hystrix 依賴 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
#在啟動類上加@EnableCircuitBreaker注解
修改Colltroller
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/getString")
//- Hystrix的執行緒池(默認),接收用戶請求采用tomcat的執行緒池,執行業務代碼,呼叫其他服務時,采用Hystrix的執行緒池,
- 信號量,使用的還是Tomcat的執行緒池,幫助我們去管理Tomcat的執行緒池
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.strategy",value = "THREAD"),
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")},
fallbackMethod = "getMsgFallback")
@ResponseBody
public String test01(){
int i =1/0;
return "你好,呼叫成功";
}
public String getMsgFallback() {
return "祝您 2021 牛年大吉";
}
}
Feigin結合Hystrix
#在呼叫方匯入jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
#消費啟動類開啟@EnableHytrix
#消費者組態檔
#feign結合hystrix使用
feign:
hystrix:
enabled: true
hystrix:
command:
default: #default全域有效,service id指定應用有效
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 20000
通過配置@FeignClient注解的fallback屬性來位MessageServiceClient指定一個自定義的fallback處理類(MessageServiceFallback),
@FeignClient(value = "TEST-CLIENT1",fallback = MessageServiceFallback.class)
public interface ClientInterface {
//遠程呼叫client服務中的test01介面
@GetMapping("/test/getString")//標識遠程呼叫的http的方法型別是什么
public String test01();
}
創建Fallback處理類
MessageServiceFallback需要實作ClientInterface介面,并且在Spring容器中必須存在一個該型別的有效Bean,在這里,我們使用@Component注解將其注入到Spring容器中
@Component
public class MessageServiceFallback implements ClientInterface {
@Override
public String test01() {
System.out.println("呼叫訊息介面失敗,對其進行降級處理!");
return "訊息介面繁忙,請稍后重試!";
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/266657.html
標籤:java
上一篇:Spring整合單元測驗
