SpringCloud入門(一)

1. 系統架構演變概述

集中式架構
垂直拆分
分布式服務
SOA面向服務架構
微服務架構

2. 微服務架構說明

SOA使用了ESB組件的面向服務架構:ESB自身實現復雜;應用服務粒度較大,所有服務之間的通信都經過ESB會降低通信速度;部署、測試ESB比較麻煩。

微服務架構:是一套使用小服務或者單一業務來開發單個應用的方式或途徑。

微服務架構特點:

  • 單一職責
  • 服務粒度小
  • 面向服務(對外暴露REST api)
  • 服務之間相互獨立

與使用ESB的SOA架構的區別:微服務架構沒有使用ESB,有服務治理注冊中心;業務粒度小。

3. 服務調用方式說明

  • RPC:基于socket,速度快,效率高;webservice、dubbo
  • HTTP:基于TCP,封裝比較臃腫;對服務和調用方沒有任何技術、語言的限定,自由靈活;RESTful,Spring Cloud

4. Spring RestTemplate示例工程導入

一般情況下有如下三種http客戶端工具類包都可以方便的進行http服務調用:

  • httpClient
  • okHttp
  • JDK原生URLConnection

spring 提供了RestTemplate的工具類對上述的3種http客戶端工具類進行了封裝,可在spring項目中使用RestTemplate進行服務調用。

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateTest {@Autowiredprivate RestTemplate restTemplate;@Testpublic void test(){String url = "http://localhost/user/8";//restTemplate可以對json格式字符串進行反序列化User user = restTemplate.getForObject(url, User.class);System.out.println(user);}
}

5. Spring Cloud概述

  • 整合的組件可以有很多組件;常見的組件有:eureka注冊中心,Gateway網關,Ribbon負載均衡,Feign服務調用,Hystrix熔斷器。在有需要的時候項目添加對于的啟動器依賴即可。
  • 版本特征:以英文單詞命名(倫敦地鐵站名)

6. 創建微服務工程

需求:查詢數據庫中的用戶數據并輸出到瀏覽器

  • 父工程heima-springcloud:添加spring boot父坐標和管理其它組件的依賴
  • 用戶服務工程user-service:整合mybatis查詢數據庫中用戶數據;提供查詢用戶服務
  • 服務消費工程consumer-demo:利用查詢用戶服務獲取用戶數據并輸出到瀏覽器

小結

            <!-- springCloud --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency>

通過 scope 的import可以繼承 spring-cloud-dependencies 工程中的依賴

7. 搭建配置user-service工程

需求:可以訪問http://localhost:9091/user/8輸出用戶數據

實現步驟:

  1. 添加啟動器依賴(web、通用Mapper);
  2. 創建啟動引導類和配置文件;
  3. 修改配置文件中的參數;
  4. 編寫測試代碼(UserMapper,UserService,UserController);
  5. 測試
  • 添加啟動器依賴
    <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 通用Mapper啟動器 --><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId></dependency><!-- mysql驅動 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies>
  • 編寫配置文件
server:port: 9091
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/springcloudusername: rootpassword: rootmybatis:type-aliases-package: com.itheima.user.pojo

8. 搭建配置consumer-demo工程

目標:編寫測試類使用restTemplate訪問user-service的路徑根據id查詢用戶

分析

需求:訪問http://localhost:8080/consumer/8 使用RestTemplate獲取http://localhost:9091/user/8的數據

實現步驟:

  1. 添加啟動器依賴;
  2. 創建啟動引導類(注冊RestTemplate)和配置文件;
  3. 編寫測試代碼(ConsumerController中使用restTemplate訪問服務獲取數據)
  4. 測試
    <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>
@SpringBootApplication
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}@Beanpublic RestTemplate get(){return new RestTemplate();}
}
@RestController
@RequestMapping("/consumer")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/{id}")public User get(@PathVariable long id){return restTemplate.getForObject("http://localhost:9091/user/"+id, User.class);}}
  • 服務管理
    如何自動注冊和發現
    如何實現狀態監管
    如何實現動態路由
  • 服務如何實現負載均衡
  • 服務如何解決容災問題
  • 服務如何實現統一配置

上述的問題都可以通過Spring Cloud的各種組件解決。

9. Eureka注冊中心說明

Eureka的主要功能是進行服務管理,定期檢查服務狀態,返回服務地址列表。

10. 搭建eureka-server工程

Eureka是服務注冊中心,只做服務注冊;自身并不提供服務也不消費服務。可以搭建web工程使用Eureka,可以使用Spring Boot方式搭建。

搭建步驟:

  1. 創建工程;
  2. 添加啟動器依賴;
  3. 編寫啟動引導類(添加Eureka的服務注解)和配置文件;
  4. 修改配置文件(端口,應用名稱…);
  5. 啟動測試

小結

  • 啟動器依賴
        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency>
  • 配置文件
server:port: 10086
spring:application:name: eureka-server
eureka:client:service-url:# eureka 服務地址,如果是集群的話;需要指定其它集群eureka地址defaultZone: http://127.0.0.1:10086/eureka# 不注冊自己register-with-eureka: false# 不拉取服務fetch-registry: false

11. 服務注冊與發現

  • 服務注冊:在服務提供工程user-service上添加Eureka客戶端依賴;自動將服務注冊到EurekaServer服務地址列表。
    • 添加依賴;
    • 改造啟動引導類;添加開啟Eureka客戶端發現的注解;
    • 修改配置文件;設置Eureka 服務地址
  • 服務發現:在服務消費工程consumer-demo上添加Eureka客戶端依賴;可以使用工具類根據服務名稱獲取對應的服務地址列表。
    • 添加依賴;
    • 改造啟動引導類;添加開啟Eureka客戶端發現的注解;
    • 修改配置文件;設置Eureka 服務地址;
    • 改造處理器類ConsumerController,可以使用工具類DiscoveryClient根據服務名稱獲取對應服務地址列表。

添加依賴

      <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>

修改配置文件

eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eureka

服務注冊

@SpringBootApplication
@MapperScan("com.gogo.mapper")
@EnableDiscoveryClient
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class,args);}
}

服務發現

@RestController
@RequestMapping("/consumer")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate DiscoveryClient discoveryClient;@GetMapping("/{id}")public User get(@PathVariable long id){List<ServiceInstance> instances = discoveryClient.getInstances("user-service");ServiceInstance serviceInstance = instances.get(0);return restTemplate.getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id, User.class);}}

12. Eureka Server高可用配置

分析

Eureka Server是一個web應用,可以啟動多個實例(配置不同端口)保證Eureka Server的高可用。

高可用配置:將Eureka Server作為一個服務注冊到其它Eureka Server,這樣多個Eureka Server之間就能夠互相發現對方,同步服務,實現Eureka Server集群。

13. Eureka客戶端與服務端配置

配置eureka客戶端user-service的注冊、續約等配置項,配置eureka客戶端consumer-demo的獲取服務間隔時間;了解失效剔除和自我保護

  • Eureka客戶端工程
    • user-service 服務提供
      • 服務地址使用ip方式
      • 續約
    • consumer-demo 服務消費
      • 獲取服務地址的頻率
  • Eureka服務端工程 eureka-server
    • 失效剔除
    • 自我保護
  • user-service
eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eurekainstance:# 更傾向使用ip地址,而不是host名prefer-ip-address: true# ip地址ip-address: 127.0.0.1# 續約間隔,默認30秒lease-renewal-interval-in-seconds: 5# 服務失效時間,默認90秒lease-expiration-duration-in-seconds: 5
  • consumer-demo
eureka:client:service-url:defaultZone: http://127.0.0.1:10086/eureka# 獲取服務地址列表間隔時間,默認30秒registry-fetch-interval-seconds: 10
  • eureka-server
eureka:server:# 服務失效剔除時間間隔,默認60秒eviction-interval-timer-in-ms: 60000# 關閉自我保護模式(默認是打開的)enable-self-preservation: false

15. Ribbon負載均衡應用

分析

需求:可以使用RestTemplate訪問http://user-service/user/8獲取服務數據。

可以使用Ribbon負載均衡:在執行RestTemplate發送服務地址請求的時候,使用負載均衡攔截器攔截,根據服務名獲取服務地址列表,使用Ribbon負載均衡算法從服務地址列表中選擇一個服務地址,訪問該地址獲取服務數據。

實現步驟:

  1. 啟動多個user-service實例(9091,9092);
  2. 修改RestTemplate實例化方法,添加負載均衡注解;
  3. 修改ConsumerController;
  4. 測試
@SpringBootApplication
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate get(){return new RestTemplate();}
}
@RestController
@RequestMapping("/consumer")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate DiscoveryClient discoveryClient;@GetMapping("/{id}")public User get(@PathVariable long id){List<ServiceInstance> instances = discoveryClient.getInstances("user-service");ServiceInstance serviceInstance = instances.get(0);return restTemplate.getForObject("http://"+"user-service"+"/user/"+id, User.class);}}

小結

在實例化RestTemplate的時候使用@LoadBalanced,服務地址直接可以使用服務名。

16. 熔斷器Hystrix簡介

目標:了解熔斷器Hystrix的作用

小結

Hystrix是一個延遲和容錯庫,用于隔離訪問遠程服務,防止出現級聯失敗。

17. 線程隔離&服務降級

Hystrix解決雪崩效應:

  • 線程隔離:用戶請求不直接訪問服務,而是使用線程池中空閑的線程訪問服務,加速失敗判斷時間。

  • 服務降級:及時返回服務調用失敗的結果,讓線程不因為等待服務而阻塞。

  • consumer-demo中添加依賴

        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency>
  • 開啟熔斷
@SpringCloudApplication
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate get(){return new RestTemplate();}
}
  • 降級邏輯
@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFall")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/{id}")
/*    @HystrixCommand(fallbackMethod = "fall")*/@HystrixCommandpublic String get(@PathVariable long id){return restTemplate.getForObject("http://"+"user-service"+"/user/"+id, String.class);}public String fall(long id){log.error("查詢{}失敗",id);return "網絡太差了";}public String defaultFall(){return "默認網絡太差了";}}
  • 修改超時配置
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 2000

18. 服務熔斷演示

@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFall")
public class ConsumerController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/{id}")
/*    @HystrixCommand(fallbackMethod = "fall")*/@HystrixCommandpublic String get(@PathVariable long id){
if(id==1) throw new RuntimeException("不行的");return restTemplate.getForObject("http://"+"user-service"+"/user/"+id, String.class);}public String fall(long id){log.error("查詢{}失敗",id);return "網絡太差了";}public String defaultFall(){return "默認網絡太差了";}}
hystrix:command:default:execution:isolation:thread:timeoutInMilliseconds: 2000circuitBreaker:errorThresholdPercentage: 50 # 觸發熔斷錯誤比例閾值,默認值50%sleepWindowInMilliseconds: 10000 # 熔斷后休眠時長,默認值5秒requestVolumeThreshold: 10 # 熔斷觸發最小請求次數,默認值是20

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

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

相關文章

PullToRefreshListView中嵌套ViewPager滑動沖突的解決

PullToRefreshListView中嵌套ViewPager滑動沖突的解決 最近恰好遇到PullToRefreshListView中需要嵌套ViewPager的情況,ViewPager 作為頭部添加到ListView中&#xff0c;發先ViewPager在滑動過程中流暢性太差幾乎很難左右滑動。在網上也看了很多大神的介紹&#xff0c;看了ViewP…

神經網絡 卷積神經網絡_如何愚弄神經網絡?

神經網絡 卷積神經網絡Imagine you’re in the year 2050 and you’re on your way to work in a self-driving car (probably). Suddenly, you realize your car is cruising at 100KMPH on a busy road after passing through a cross lane and you don’t know why.想象一下…

數據特征分析-分布分析

分布分析用于研究數據的分布特征&#xff0c;常用分析方法&#xff1a; 1、極差 2、頻率分布 3、分組組距及組數 df pd.DataFrame({編碼:[001,002,003,004,005,006,007,008,009,010,011,012,013,014,015],\小區:[A村,B村,C村,D村,E村,A村,B村,C村,D村,E村,A村,B村,C村,D村,E村…

開發工具總結(2)之全面總結Android Studio2.X的填坑指南

前言&#xff1a;好多 Android 開發者都在說Android Studio太坑了&#xff0c;老是出錯&#xff0c;導致開發進度變慢&#xff0c;出錯了又不知道怎么辦&#xff0c;網上去查各種解決方案五花八門&#xff0c;有些可以解決問題&#xff0c;有些就是轉來轉去的寫的很粗糙&#x…

無聊的一天_一人互聯網公司背后的無聊技術

無聊的一天Listen Notes is a podcast search engine and database. The technology behind Listen Notes is actually very very boring. No AI, no deep learning, no blockchain. “Any man who must say I am using AI is not using True AI” :)Listen Notes是一個播客搜索…

如何在Pandas中使用Excel文件

From what I have seen so far, CSV seems to be the most popular format to store data among data scientists. And that’s understandable, it gets the job done and it’s a quite simple format; in Python, even without any library, one can build a simple CSV par…

Js實現div隨鼠標移動的方法

HTML: <div id"odiv" style" COLOR: #666; padding: 2px 8px; FONT-SIZE: 12px; MARGIN-RIGHT: 5px; position: absolute; background: #fff; display: block; border: 1px solid #666; top: 50px; left: 10px;"> Move_Me</div>第一種&…

leetcode 867. 轉置矩陣

給你一個二維整數數組 matrix&#xff0c; 返回 matrix 的 轉置矩陣 。 矩陣的 轉置 是指將矩陣的主對角線翻轉&#xff0c;交換矩陣的行索引與列索引。 示例 1&#xff1a; 輸入&#xff1a;matrix [[1,2,3],[4,5,6],[7,8,9]] 輸出&#xff1a;[[1,4,7],[2,5,8],[3,6,9]] …

數據特征分析-對比分析

對比分析是對兩個互相聯系的指標進行比較。 絕對數比較(相減)&#xff1a;指標在量級上不能差別過大&#xff0c;常用折線圖、柱狀圖 相對數比較(相除)&#xff1a;結構分析、比例分析、空間比較分析、動態對比分析 df pd.DataFrame(np.random.rand(30,2)*1000,columns[A_sale…

Linux基線合規檢查中各文件的作用及配置腳本

1./etc/motd 操作&#xff1a;echo " Authorized users only. All activity may be monitored and reported " > /etc/motd 效果&#xff1a;telnet和ssh登錄后的輸出信息 2. /etc/issue和/etc/issue.net 操作&#xff1a;echo " Authorized users only. All…

tableau使用_使用Tableau升級Kaplan-Meier曲線

tableau使用In a previous article, I showed how we can create the Kaplan-Meier curves using Python. As much as I love Python and writing code, there might be some alternative approaches with their unique set of benefits. Enter Tableau!在上一篇文章中 &#x…

踩坑 net core

webclient 可以替換為 HttpClient 下載獲取url的內容&#xff1a; 證書&#xff1a; https://stackoverflow.com/questions/40014047/add-client-certificate-to-net-core-httpclient 轉載于:https://www.cnblogs.com/zxs-onestar/p/7340386.html

我從參加#PerfMatters會議中學到的東西

by Stacey Tay通過史黛西泰 我從參加#PerfMatters會議中學到的東西 (What I learned from attending the #PerfMatters conference) 從前端的網絡運行情況發布會上的注意事項 (Notes from a front-end web performance conference) This week I had the privilege of attendin…

修改innodb_flush_log_at_trx_commit參數提升insert性能

最近&#xff0c;在一個系統的慢查詢日志里發現有個insert操作很慢&#xff0c;達到秒級&#xff0c;并且是比較簡單的SQL語句&#xff0c;把語句拿出來到mysql中直接執行&#xff0c;速度卻很快。 這種問題一般不是SQL語句本身的問題&#xff0c;而是在具體的應用環境中&#…

leetcode 1178. 猜字謎(位運算)

外國友人仿照中國字謎設計了一個英文版猜字謎小游戲&#xff0c;請你來猜猜看吧。 字謎的迷面 puzzle 按字符串形式給出&#xff0c;如果一個單詞 word 符合下面兩個條件&#xff0c;那么它就可以算作謎底&#xff1a; 單詞 word 中包含謎面 puzzle 的第一個字母。 單詞 word…

Nexus3.x.x上傳第三方jar

exus3.x.x上傳第三方jar&#xff1a; 1. create repository 選擇maven2(hosted)&#xff0c;說明&#xff1a; proxy&#xff1a;即你可以設置代理&#xff0c;設置了代理之后&#xff0c;在你的nexus中找不到的依賴就會去配置的代理的地址中找hosted&#xff1a;你可以上傳你自…

責備的近義詞_考試結果危機:我們應該責備算法嗎?

責備的近義詞I’ve been considering writing on the topic of algorithms for a little while, but with the Exam Results Fiasco dominating the headline news in the UK during the past week, I felt that now is the time to look more closely into the subject.我一直…

電腦如何設置終端設置代理_如何設置一個嚴肅的Kubernetes終端

電腦如何設置終端設置代理by Chris Cooney克里斯庫尼(Chris Cooney) 如何設置一個嚴肅的Kubernetes終端 (How to set up a serious Kubernetes terminal) 所有k8s書呆子需要的CLI工具 (All the CLI tools a growing k8s nerd needs) Kubernetes comes pre-packaged with an ou…

spring cloud(二)

1. Feign應用 Feign的作用&#xff1b;使用Feign實現consumer-demo代碼中調用服務 導入啟動器依賴&#xff1b;開啟Feign功能&#xff1b;編寫Feign客戶端&#xff1b;編寫一個處理器ConsumerFeignController&#xff0c;注入Feign客戶端并使用&#xff1b;測試 <dependen…

c/c++編譯器的安裝

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