spring cloud(二)

1. Feign應用

Feign的作用;使用Feign實現consumer-demo代碼中調用服務

  1. 導入啟動器依賴;
  2. 開啟Feign功能;
  3. 編寫Feign客戶端;
  4. 編寫一個處理器ConsumerFeignController,注入Feign客戶端并使用;
  5. 測試
        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>

@SpringCloudApplication
@EnableFeignClients
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate get(){return new RestTemplate();}
}
@FeignClient("user-service")
public interface UserClient {@GetMapping("/user/{id}")User get(@PathVariable long id);
}
@RestController
@RequestMapping("/cf")
public class ConsumerFeignController {@Autowiredprivate UserClient userClient;@GetMapping("/{id}")public User get(@PathVariable long id){return userClient.get(id);}
}

Feign主要作用:自動根據參數拼接http請求地址。

2. Feign負載均衡及熔斷

目標:可以配置Feign內置ribbon配置項和Hystrix熔斷的Fallback配置

分析

  • 負載均衡
  • 服務熔斷
  • 請求壓縮
  • 日志級別
ribbon:ConnectTimeout: 1000 # 連接超時時長ReadTimeout: 2000 # 數據通信超時時長MaxAutoRetries: 0 # 當前服務器的重試次數MaxAutoRetriesNextServer: 0 # 重試多少次服務OkToRetryOnAllOperations: false # 是否對所有的請求方式都重試
feign:hystrix:enabled: true # 開啟Feign的熔斷功能compression:request:enabled: true # 開啟請求壓縮mime-types: text/html,application/xml,application/json # 設置壓縮的數據類型min-request-size: 2048 # 設置觸發壓縮的大小下限response:enabled: true
logging:level:com.gogo: debug
@Component
public class UserClientFallback implements UserClient{@Overridepublic User get(long id) {User user = new User();user.setId(id);user.setName("異常用戶");return user;}
}
@Configuration
public class FeignConfig {@BeanLogger.Level logLevel(){return Logger.Level.FULL;}}
@FeignClient(value = "user-service",fallback = UserClientFallback.class,configuration = FeignConfig.class)
public interface UserClient {@GetMapping("/user/{id}")User get(@PathVariable long id);
}

Spring Cloud Gateway的核心就是一系列的過濾器,可以將客戶端的請求轉發到不同的微服務。主要作用:過濾和路由。

4. Spring Cloud Gateway入門

需求:通過網關系統heima-gateway將包含有 /user 的請求 路由到 http://127.0.0.1:9091/user/用戶id

實現步驟:

  1. 創建工程;
  2. 添加啟動器依賴;
  3. 編寫啟動引導類和配置文件;
  4. 修改配置文件,設置路由信息;
  5. 啟動測試
    <dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency></dependencies>
server:port: 10010
spring:application:name: api-gatewaycloud:gateway:routes:- id: user-service-routeuri: http://127.0.0.1:9091predicates:- Path=/user/**eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:prefer-ip-address: true

5. 面向服務的路由

使用在eureka注冊的服務作為路由地址

如果將路由服務地址寫死明顯是不合理的;在Spring Cloud Gateway中可以通過配置動態路由解決。

面向服務的路由;只需要在配置文件中指定路由路徑類似: lb://user-service

lb 之后編寫的服務名必須要在eureka中注冊才能使用

server:port: 10010
spring:application:name: api-gatewaycloud:gateway:routes:- id: user-service-routeuri: lb://user-servicepredicates:- Path=/**filters:# 添加請求路徑的前綴- PrefixPath=/usereureka:client:service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:prefer-ip-address: true

6. 路由前綴處理

可以對請求到網關服務的地址添加或去除前綴

提供服務的地址:http://127.0.0.1:9091/user/8

  • 添加前綴:對請求地址添加前綴路徑之后再作為代理的服務地址;

http://127.0.0.1:10010/8 --> http://127.0.0.1:9091/user/8 添加前綴路徑/user

  • 去除前綴:將請求地址中路徑去除一些前綴路徑之后再作為代理的服務地址;

http://127.0.0.1:10010/api/user/8 --> http://127.0.0.1:9091/user/8 去除前綴路徑/api

server:port: 10010
spring:application:name: api-gatewaycloud:gateway:routes:- id: user-service-routeuri: lb://user-servicepredicates:- Path=/**filters:# 添加請求路徑的前綴- PrefixPath=/usereureka:client:service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:prefer-ip-address: true
          filters:# 添加請求路徑的前綴- StripPrefix=1

客戶端的請求地址與微服務的服務地址如果不一致的時候,可以通過配置路徑過濾器實現路徑前綴的添加和去除。

7. 過濾器簡介

  • 用法:在配置文件中指定要使用的過濾器名稱;
  • 類型:局部、全局;
  • 使用場景:請求鑒權、異常處理、記錄調用時長等。

8. 自定義局部過濾器

按照默認過濾器編寫并配置一個自定義局部過濾器,該過濾器可以通過配置文件中的參數名稱獲取請求的參數值

需求:在過濾器(MyParamGatewayFilterFactory)中將http://localhost:10010/api/user/8?name=itcast中的參數name的值獲取到并輸出到控制臺;并且參數名是可變的,也就是不一定每次都是name;需要可以通過配置過濾器的時候做到配置參數名。

實現步驟:

  1. 配置過濾器;
  2. 編寫過濾器;
  3. 測試
spring:application:name: api-gatewaycloud:gateway:routes:- id: user-service-routeuri: lb://user-servicepredicates:- Path=/api/user/**filters:# 添加請求路徑的前綴- StripPrefix=1- My=namedefault-filters:- AddResponseHeader=X-Response-Default-MyName, gogo
@Component
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory<MyGatewayFilterFactory.config> {public static final String PARAM_NAME = "param";@Overridepublic GatewayFilter apply(config config) {return ((exchange, chain) -> {ServerHttpRequest request = exchange.getRequest();if(request.getQueryParams().containsKey(config.param))request.getQueryParams().get(config.param).forEach(var-> System.out.println(config.param+var));return chain.filter(exchange);});}public MyGatewayFilterFactory() {super(config.class);}@Overridepublic List<String> shortcutFieldOrder() {return Arrays.asList(PARAM_NAME);}@Datapublic static class config{String param;}
}

9. 自定義全局過濾器

定義一個全局過濾器檢查請求中是否攜帶有token參數

需求:編寫全局過濾器,在過濾器中檢查請求地址是否攜帶token參數。如果token參數的值存在則放行;如果token的參數值為空或者不存在則設置返回的狀態碼為:未授權也不再執行下去。

實現步驟:

  1. 編寫全局過濾器;
  2. 測試
@Componentpublic class MyGlobalFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {System.out.println("全局------------------");String token = exchange.getRequest().getQueryParams().getFirst("token");if(StringUtils.isBlank(token)){exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);return exchange.getResponse().setComplete();}return chain.filter(exchange);}@Overridepublic int getOrder() {return 1;}
}

10. Gateway其它配置說明

Gateway網關的負載均衡和熔斷參數配置

server:port: 10010
spring:application:name: api-gatewaycloud:gateway:routes:- id: user-service-routeuri: lb://user-servicepredicates:- Path=/api/user/**filters:# 添加請求路徑的前綴- StripPrefix=1- My=namedefault-filters:- AddResponseHeader=X-Response-Default-MyName, gogoglobalcors:corsConfigurations:'[/**]':#allowedOrigins: * # 這種寫法或者下面的都可以,*表示全部allowedOrigins:- "http://docs.spring.io"allowedMethods:- GETeureka:client:service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:prefer-ip-address: truehystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 6000
ribbon:ConnectTimeout: 1000ReadTimeout: 2000MaxAutoRetries: 0MaxAutoRetriesNextServer: 0

Gateway網關一般直接給終端請求使用;Feign一般用在微服務之間調用。

11. Spring Cloud Config分布式配置中心簡介

目標:分布式配置中心的作用

小結

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Mg8yPP56-1614310505789)(assets/1560919656472.png)]

spring cloud config作用:可以通過修改在git倉庫中的配置文件實現其它所有微服務的配置文件的修改。

12. 搭建配置中心微服務

創建碼云的遠程公開git倉庫,搭建配置中心微服務config-server

  • 創建git倉庫:在碼云上創建倉庫

  • 搭建配置中心config-server:使用spring boot方式搭建和配置

  • 配置中心依賴

    <dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-config-server</artifactId></dependency></dependencies>
  • 配置中心的配置文件
eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:prefer-ip-address: trueserver:port: 12000
spring:application:name: config-servercloud:config:server:git:uri: https://gitee.com/Gogo-gitee/config.git

在gitee中修改了配置文件會在配置中心服務及時更新。

13. 獲取配置中心配置

需求:將服務提供工程user-service的application.yml配置文件刪除,修改為從配置中心config-server中獲取。

實現步驟:

  1. 添加啟動器依賴;
  2. 修改配置文件;
  3. 啟動測試

將原來的application.yml刪除;然后添加bootstrap.yml配置文件,該文件也是spring boot的默認配置文件,其內容經常配置一些項目中固定的配置項。如果是項目經常變動的應該配置到application.yml中,現在使用了配置中心則應該配置到git倉庫中對于的配置文件。

  • 依賴
        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId><version>2.1.1.RELEASE</version></dependency>
  • 配置文件bootstrap.yml
spring:cloud:config:# 要與倉庫中的配置文件的application保持一致name: user# 要與倉庫中的配置文件的profile保持一致profile: dev# 要與倉庫中的配置文件所屬的版本(分支)一樣label: masterdiscovery:# 使用配置中心enabled: true# 配置中心服務名service-id: config-servereureka:client:service-url:defaultZone: http://127.0.0.1:10086/eureka

14. Spring Cloud Bus簡介

目標:了解Spring Cloud Bus作用

小結

Spring Cloud Bus作用:將git倉庫的配置文件更新,在不重啟系統的情況下實現及時同步到各個微服務。

15. Spring Cloud Bus應用

需求:在碼云的git倉庫中修改user-dev.yml配置文件,實現不重啟user-service的情況下可以及時更新配置文件。

實現步驟:

  1. 啟動RabbitMQ;
  2. 修改配置中心config-server;
  3. 修改服務提供工程user-service;
  4. 測試
  • config-server的依賴添加內容
        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-bus</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-stream-binder-rabbit</artifactId></dependency>
  • config-server的配置文件添加內容
server:port: 12000
spring:application:name: config-servercloud:config:server:git:uri: https://gitee.com/goheima/heima-config.git# 配置rabbitmq信息;如果是都與默認值一致則不需要配置rabbitmq:host: localhostport: 5672username: guestpassword: guest
eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eureka
management:endpoints:web:exposure:# 暴露觸發消息總線的地址include: bus-refresh
  • user-service的依賴添加內容
        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-bus</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-stream-binder-rabbit</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
  • user-service的配置文件添加內容
  # 配置rabbitmq信息;如果是都與默認值一致則不需要配置rabbitmq:host: localhostport: 5672username: guestpassword: guest
  • UserController的修改
@RestController
@RefreshScope
public class HelloController {@Autowiredprivate DataSource dataSource;@AutowiredUserService userService;@Value("${test}")private String test;@GetMapping("/user/{id}")public User query(@PathVariable long id){return userService.queryId(id);}@GetMapping("/hello")public String hello(){return "hello "+test;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391705.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391705.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391705.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c/c++編譯器的安裝

MinGW(Minimalist GNU For Windows)是個精簡的Windows平臺C/C、ADA及Fortran編譯器&#xff0c;相比Cygwin而言&#xff0c;體積要小很多&#xff0c;使用較為方便。 MinGW最大的特點就是編譯出來的可執行文件能夠獨立在Windows上運行。 MinGW的組成&#xff1a; 編譯器(支持C、…

滲透工具

滲透工具 https://blog.csdn.net/Fly_hps/article/details/89306104 查詢工具 https://blog.csdn.net/Fly_hps/article/details/89070552 轉載于:https://www.cnblogs.com/liuYGoo/p/11347693.html

numpy 線性代數_數據科學家的線性代數—用NumPy解釋

numpy 線性代數Machine learning and deep learning models are data-hungry. The performance of them is highly dependent on the amount of data. Thus, we tend to collect as much data as possible in order to build a robust and accurate model. Data is collected i…

spring 注解方式配置Bean

概要&#xff1a; 再classpath中掃描組件 組件掃描&#xff08;component scanning&#xff09;&#xff1a;Spring可以從classpath下自己主動掃描。偵測和實例化具有特定注解的組件特定組件包含&#xff1a; Component&#xff1a;基本注解。標示了一個受Spring管理的組件&…

主成分分析 獨立成分分析_主成分分析概述

主成分分析 獨立成分分析by Moshe Binieli由Moshe Binieli 主成分分析概述 (An overview of Principal Component Analysis) This article will explain you what Principal Component Analysis (PCA) is, why we need it and how we use it. I will try to make it as simple…

擴展方法略好于幫助方法

如果針對一個類型實例的代碼片段經常被用到&#xff0c;我們可能會想到把之封裝成幫助方法。如下是一段針對DateTime類型實例的一段代碼&#xff1a;class Program{static void Main(string[] args){DateTime d new DateTime(2001,5,18);switch (d.DayOfWeek){case DayOfWeek.…

零元學Expression Blend 4 - Chapter 25 以Text相關功能就能簡單做出具有設計感的登入畫面...

原文:零元學Expression Blend 4 - Chapter 25 以Text相關功能就能簡單做出具有設計感的登入畫面本章將交大家如何運用Blend 4 內的Text相關功能做出有設計感的登入畫面 讓你五分鐘就能快速做出一個登入畫面 ? 本章將教大家如何運用Blend 4 內的Text相關功能做出有設計感的登入…

leetcode 395. 至少有 K 個重復字符的最長子串(滑動窗口)

給你一個字符串 s 和一個整數 k &#xff0c;請你找出 s 中的最長子串&#xff0c; 要求該子串中的每一字符出現次數都不少于 k 。返回這一子串的長度。 示例 1&#xff1a; 輸入&#xff1a;s “aaabb”, k 3 輸出&#xff1a;3 解釋&#xff1a;最長子串為 “aaa” &…

冠狀病毒時代的負責任數據可視化

First, a little bit about me: I’m a data science grad student. I have been writing for Medium for a little while now. I’m a scorpio. I like long walks on beaches. And writing for Medium made me realize the importance of taking personal responsibility ove…

集合_java集合框架

轉載自http://blog.csdn.net/zsw101259/article/details/7570033 Java集合框架圖 簡化圖&#xff1a; Java平臺提供了一個全新的集合框架。“集合框架”主要由一組用來操作對象的接口組成。不同接口描述一組不同數據類型。 1、Java 2集合框架圖 ①集合接口&#xff1a;6個…

顯示隨機鍵盤

顯示隨機鍵盤 1 <!DOCTYPE html>2 <html lang"zh-cn">3 <head>4 <meta charset"utf-8">5 <title>7-77 課堂演示</title>6 <link rel"stylesheet" type"text/css" href"style…

數據特征分析-統計分析

一、統計分析 統計分析是對定量數據進行統計描述&#xff0c;常從集中趨勢和離中趨勢兩個方面分析。 集中趨勢&#xff1a;指一組數據向某一中心靠攏的傾向&#xff0c;核心在于尋找數據的代表值或中心值-統計平均數&#xff08;算數平均數和位置平均數&#xff09; 算術平均數…

心學 禪宗_禪宗宣言,用于有效的代碼審查

心學 禪宗by Jean-Charles Fabre通過讓查爾斯法布爾(Jean-Charles Fabre) 禪宗宣言&#xff0c;用于有效的代碼審查 (A zen manifesto for effective code reviews) When you are coding, interruptions really suck.當您編碼時&#xff0c;中斷確實很糟糕。 You are in the …

leetcode 896. 單調數列

如果數組是單調遞增或單調遞減的&#xff0c;那么它是單調的。 如果對于所有 i < j&#xff0c;A[i] < A[j]&#xff0c;那么數組 A 是單調遞增的。 如果對于所有 i < j&#xff0c;A[i]> A[j]&#xff0c;那么數組 A 是單調遞減的。 當給定的數組 A 是單調數組…

數據eda_銀行數據EDA:逐步

數據edaThis banking data was retrieved from Kaggle and there will be a breakdown on how the dataset will be handled from EDA (Exploratory Data Analysis) to Machine Learning algorithms.該銀行數據是從Kaggle檢索的&#xff0c;將詳細介紹如何將數據集從EDA(探索性…

結構型模式之組合

重新看組合/合成&#xff08;Composite&#xff09;模式&#xff0c;發現它并不像自己想象的那么簡單&#xff0c;單純從整體和部分關系的角度去理解還是不夠的&#xff0c;并且還有一些通俗的模式講解類的書&#xff0c;由于其舉的例子太過“通俗”&#xff0c;以致讓人理解產…

計算機網絡原理筆記-三次握手

三次握手協議指的是在發送數據的準備階段&#xff0c;服務器端和客戶端之間需要進行三次交互&#xff1a; 第一次握手&#xff1a;客戶端發送syn包(synj)到服務器&#xff0c;并進入SYN_SEND狀態&#xff0c;等待服務器確認&#xff1b; 第二次握手&#xff1a;服務器收到syn包…

VB2010 的隱式續行(Implicit Line Continuation)

VB2010 的隱式續行&#xff08;Implicit Line Continuation&#xff09;許多情況下,您可以讓 VB 后一行繼續前一行的語句&#xff0c;而不必使用下劃線&#xff08;_&#xff09;。下面列舉出隱式續行語法的使用情形。1、逗號“&#xff0c;”之后PublicFunctionGetUsername(By…

flutter bloc_如何在Flutter中使用Streams,BLoC和SQLite

flutter blocRecently, I’ve been working with streams and BLoCs in Flutter to retrieve and display data from an SQLite database. Admittedly, it took me a very long time to make sense of them. With that said, I’d like to go over all this in hopes you’ll w…

leetcode 303. 區域和檢索 - 數組不可變

給定一個整數數組 nums&#xff0c;求出數組從索引 i 到 j&#xff08;i ≤ j&#xff09;范圍內元素的總和&#xff0c;包含 i、j 兩點。 實現 NumArray 類&#xff1a; NumArray(int[] nums) 使用數組 nums 初始化對象 int sumRange(int i, int j) 返回數組 nums 從索引 i …