Alibaba?SpringCloud集成Nacos、openFeign實(shí)現(xiàn)負(fù)載均衡的解決方案
Spring cloud alibaba
Spring Cloud Alibaba 致力于提供微服務(wù)開(kāi)發(fā)的一站式解決方案。此項(xiàng)目包含開(kāi)發(fā)分布式應(yīng)用微服務(wù)的必需組件,方便開(kāi)發(fā)者通過(guò) Spring Cloud 編程模型輕松使用這些組件來(lái)開(kāi)發(fā)分布式應(yīng)用服務(wù)。
主要功能
- 服務(wù)限流降級(jí):默認(rèn)支持 WebServlet、WebFlux、OpenFeign、RestTemplate、Spring Cloud Gateway、Dubbo 和 RocketMQ 限流降級(jí)功能的接入,可以在運(yùn)行時(shí)通過(guò)控制臺(tái)實(shí)時(shí)修改限流降級(jí)規(guī)則,還支持查看限流降級(jí) Metrics 監(jiān)控。
- 服務(wù)注冊(cè)與發(fā)現(xiàn):適配 Spring Cloud 服務(wù)注冊(cè)與發(fā)現(xiàn)標(biāo)準(zhǔn),默認(rèn)集成對(duì)應(yīng) Spring Cloud 版本所支持的負(fù)載均衡組件的適配。
- 分布式配置管理:支持分布式系統(tǒng)中的外部化配置,配置更改時(shí)自動(dòng)刷新。
- 消息驅(qū)動(dòng)能力:基于 Spring Cloud Stream 為微服務(wù)應(yīng)用構(gòu)建消息驅(qū)動(dòng)能力。
- 分布式事務(wù):使用 @GlobalTransactional 注解, 高效并且對(duì)業(yè)務(wù)零侵入地解決分布式事務(wù)問(wèn)題。
- 阿里云對(duì)象存儲(chǔ):阿里云提供的海量、安全、低成本、高可靠的云存儲(chǔ)服務(wù)。支持在任何應(yīng)用、任何時(shí)間、任何地點(diǎn)存儲(chǔ)和訪問(wèn)任意類型的數(shù)據(jù)。
- 分布式任務(wù)調(diào)度:提供秒級(jí)、精準(zhǔn)、高可靠、高可用的定時(shí)(基于 Cron 表達(dá)式)任務(wù)調(diào)度服務(wù)。同時(shí)提供分布式的任務(wù)執(zhí)行模型,如網(wǎng)格任務(wù)。網(wǎng)格任務(wù)支持海量子任務(wù)均勻分配到所有 Worker(schedulerx-client)上執(zhí)行。
- 阿里云短信服務(wù):覆蓋全球的短信服務(wù),友好、高效、智能的互聯(lián)化通訊能力,幫助企業(yè)迅速搭建客戶觸達(dá)通道。
功能組件
- Sentinel:把流量作為切入點(diǎn),從流量控制、熔斷降級(jí)、系統(tǒng)負(fù)載保護(hù)等多個(gè)維度保護(hù)服務(wù)的穩(wěn)定性。
- Nacos:一個(gè)更易于構(gòu)建云原生應(yīng)用的動(dòng)態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺(tái)。
- RocketMQ:一款開(kāi)源的分布式消息系統(tǒng),基于高可用分布式集群技術(shù),提供低延時(shí)的、高可靠的消息發(fā)布與訂閱服務(wù)。
- Seata:阿里巴巴開(kāi)源產(chǎn)品,一個(gè)易于使用的高性能微服務(wù)分布式事務(wù)解決方案。
- Alibaba Cloud OSS: 阿里云對(duì)象存儲(chǔ)服務(wù)(Object Storage Service,簡(jiǎn)稱 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存儲(chǔ)服務(wù)。您可以在任何應(yīng)用、任何時(shí)間、任何地點(diǎn)存儲(chǔ)和訪問(wèn)任意類型的數(shù)據(jù)。
- Alibaba Cloud SchedulerX: 阿里中間件團(tuán)隊(duì)開(kāi)發(fā)的一款分布式任務(wù)調(diào)度產(chǎn)品,提供秒級(jí)、精準(zhǔn)、高可靠、高可用的定時(shí)(基于 Cron 表達(dá)式)任務(wù)調(diào)度服務(wù)。
- Alibaba Cloud SMS: 覆蓋全球的短信服務(wù),友好、高效、智能的互聯(lián)化通訊能力,幫助企業(yè)迅速搭建客戶觸達(dá)通道。
springboot集成
<dependencyManagement> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2023.0.0.1-RC2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
OpenFeign
OpenFeign(簡(jiǎn)稱Feign)是一個(gè)聲明式的Web服務(wù)客戶端,用于簡(jiǎn)化服務(wù)之間的HTTP通信。它是Spring Cloud組件中的一個(gè)輕量級(jí)RESTful的HTTP服務(wù)客戶端,內(nèi)置了Ribbon來(lái)做客戶端負(fù)載均衡,以調(diào)用服務(wù)注冊(cè)中心的服務(wù)。
主要特性
- 聲明式API定義:使用注解方式定義和配置HTTP請(qǐng)求,使得代碼更加簡(jiǎn)潔、易讀和易于維護(hù)。
- 與Spring Cloud集成:OpenFeign與Spring Cloud無(wú)縫集成,可以通過(guò)@EnableFeignClients注解開(kāi)啟Feign的功能,并利用Eureka等服務(wù)注冊(cè)發(fā)現(xiàn)機(jī)制進(jìn)行服務(wù)間的調(diào)用。
- 負(fù)載均衡和容錯(cuò)支持:OpenFeign內(nèi)置了Ribbon負(fù)載均衡器的支持,可以根據(jù)配置的策略自動(dòng)選擇可用的服務(wù)實(shí)例。此外,結(jié)合Hystrix等熔斷器框架,還能提供容錯(cuò)保護(hù)和自動(dòng)降級(jí)的能力。
- 支持多種編解碼器:OpenFeign提供了多種默認(rèn)的編碼器和解碼器,使得開(kāi)發(fā)者無(wú)需過(guò)多關(guān)注底層實(shí)現(xiàn)細(xì)節(jié),更加專注于業(yè)務(wù)邏輯的開(kāi)發(fā)。
- 可擴(kuò)展性和定制化:OpenFeign支持自定義的編碼器、解碼器和攔截器,可以根據(jù)實(shí)際需求進(jìn)行擴(kuò)展和定制。
OpenFeign的工作方式是聲明式接口編程,開(kāi)發(fā)者可以定義一個(gè)接口,并對(duì)其進(jìn)行注解,以標(biāo)識(shí)需要調(diào)用的遠(yuǎn)程服務(wù)的HTTP端點(diǎn)。借助Spring MVC的注解,如@RequestMapping和@PathVariable等,這個(gè)接口直觀地映射了遠(yuǎn)程服務(wù)的API。OpenFeign自動(dòng)處理請(qǐng)求的發(fā)送和響應(yīng)的接收,封裝了編碼請(qǐng)求和解碼響應(yīng)的過(guò)程,極大地減少了樣板代碼。
總之,OpenFeign是一個(gè)功能強(qiáng)大的Web服務(wù)客戶端,可以方便地實(shí)現(xiàn)服務(wù)間的HTTP通信,并且與Spring Cloud無(wú)縫集成,為微服務(wù)架構(gòu)提供了良好的支持。
Nacos安裝
因?yàn)楹竺鏁?huì)經(jīng)常用到nacos,所以最好先安裝好了。
安裝
- 下載:https://github.com/alibaba/nacos/releases
- 修改JDK版本,因?yàn)橄螺d的是V2.3.2版本,需要JDK17支持。 在在startup.sh中約66行配置
export JAVA_HOME = /Users/liudong/Library/Java/JavaVirtualMachines/openjdk-21.0.1/Contents/Home
開(kāi)啟授權(quán)
防止出現(xiàn)登陸失敗,修改nacos配置,如下:
nacos.core.auth.system.type=nacos nacos.core.auth.enabled=true ###設(shè)置服務(wù)端驗(yàn)證 key nacos.core.auth.server.identity.key=test nacos.core.auth.server.identity.value=test ### The default token (Base64 String): nacos.core.auth.plugin.nacos.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789
啟動(dòng)
sh startup.sh -m standalone ,然后可以通過(guò) http://127.0.0.1:8848/nacos 地址訪問(wèn)。
授權(quán)驗(yàn)證
### 獲取 accessToken:使用用戶名和密碼登陸 nacos server: curl -X POST '127.0.0.1:8848/nacos/v1/auth/login' -d 'username=nacos&password=nacos' ### 使用 accessToken 請(qǐng)求 nacos api 接口: curl -X GET '127.0.0.1:8848/nacos/v1/cs/configs?accessToken=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyMzkyM30.O-s2yWfDSUZ7Svd3Vs7jy9tsfDNHs1SuebJB4KlNY8Q&dataId=nacos.example.1&group=nacos_group'
配置mysql數(shù)據(jù)庫(kù)
這是可選的,默認(rèn)采用了內(nèi)置的Derby數(shù)據(jù)庫(kù),配置了mysql更有利于數(shù)據(jù)共享和操作。
- 創(chuàng)建一個(gè)名為nacos的數(shù)據(jù)庫(kù);
- 初始化名為
mysql-schema.sql
的腳本文件; - 修改nacos配置,如下:
spring.datasource.platform=mysql db.num=1 db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC db.user.0=root db.password.0=123456
alibaba-nacos-server provider模塊
pom.xml
依賴版本可參考 springbootSeries 模塊中pom.xml文件中的版本定義
<dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies>
application.properties配置
spring.profiles.active = dev spring.application.name=AlibabaSpringbootNacosServer server.port=19501 management.endpoints.web.exposure.include=* spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 spring.cloud.nacos.discovery.fail-fast=true spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos
application-server2.properties配置
spring.application.name=AlibabaSpringbootNacosServer server.port=19502 management.endpoints.web.exposure.include=* spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 spring.cloud.nacos.discovery.fail-fast=true spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos #springboot Server spring.aop.auto=true spring.aop.proxy-target-class=true # log4j logging.config=classpath:log4j2.xml logging.level.root=INFO logging.level.org.springframework.web=ERROR #restful Server server.compression.enabled=true server.compression.mime-types=application/json,application/octet-stream #swagger springdoc.api-docs.enabled=true springdoc.api-docs.path=/api-schema swagger-config.group = default-group swagger-config.description= The following is a restful-api list of {} application, and you can browse or test them to determine if they are working as you expect. swagger-config.version=V1.0 swagger-config.urlPattern=/** swagger-config.base-package=com.korgs swagger-config.authorization-key-name=token swagger-config.wiki = https://korgs.blog.csdn.net/
SpringbootApplication啟動(dòng)類
@Slf4j @SpringBootApplication(scanBasePackages = {"com.korgs", "cn.hutool.extra.spring"}) @Configuration @EnableConfigurationProperties @ServletComponentScan @RestController @EnableDiscoveryClient public class AlibabaSpringbootNacosServerApplication { @Value("${server.port}") private String serverPort; public static void main(String[] args) { SpringApplication.run(AlibabaSpringbootNacosServerApplication.class, args); } @GetMapping("/helloworld/{uuid}") public BaseResponse<String> helloWorld(@PathVariable String uuid){ String str = LogGenerator.trackLog() + " uuid=" + uuid + " I am busy to handle this request." + " serverPort=" + serverPort; log.info( str ); return BaseResponse.success(str); } }
springboot-openFeign-client consumer模塊
pom.xml
依賴版本可參考 springbootSeries 模塊中pom.xml文件中的版本定義
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
application.properties配置
spring.profiles.active = dev spring.application.name=SpringbootOpenFeignClient server.port=19506 management.endpoints.web.exposure.include=* spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 spring.cloud.nacos.discovery.fail-fast=true spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos logging.level.com.korgs.biz.service = debug
OpenFeign Bean 實(shí)現(xiàn)
@Configuration public class OpenFeignConfig { @Bean Logger.Level level() { return Logger.Level.FULL; } }
Service服務(wù)類實(shí)現(xiàn)
這個(gè)類用于調(diào)用Provider的Restful接口,相比ribbon省云了定義RestTemplate這一步。但從結(jié)構(gòu)上更合理了,注意添加@FeignClient
注解,值為provide的注冊(cè)名稱。
@FeignClient(value = "AlibabaSpringbootNacosServer") public interface LoadService { @GetMapping("/helloworld/{uuid}") BaseResponse<String> loadHelloContent(@PathVariable String uuid); }
Controller測(cè)試類實(shí)現(xiàn)
@RestController @RequestMapping("/api/load") @RestController @RequestMapping("/api/load") public class LoadBalanceController { @Autowired private LoadService loadService; @GetMapping("/v1/hello-content") public BaseResponse<String> loadHelloContent(String uuid){ return loadService.loadHelloContent(uuid); } }
SpringbootApplication啟動(dòng)類
@Slf4j @SpringBootApplication(scanBasePackages = {"com.korgs", "cn.hutool.extra.spring"}) @Configuration @EnableConfigurationProperties @ServletComponentScan @RestController @EnableDiscoveryClient @EnableFeignClients public class SpringbootOpenFeignClientApplication { public static void main(String[] args) { SpringApplication.run(SpringbootOpenFeignClientApplication.class, args); } @GetMapping("/helloworld") public BaseResponse helloWorld(){ log.info( LogGenerator.trackLog() + "msg=" + "I am busy to handle this request."); return BaseResponse.success("hello world"); } }
源碼下載
涉及模塊:
- alibaba-nacos-server:19501,19502 provide服務(wù)端
- springboot-openFeign-client : 19506, consumer客戶端
源碼下載:
基礎(chǔ)框架源碼下載:
百度網(wǎng)盤下載:
鏈接: https://pan.baidu.com/s/1XUQyKdR6yDM__aJqCF-b5g?pwd=58pd
提取碼: 58pd
Alibaba SpringCloud集成Nacos、openFeign實(shí)現(xiàn)負(fù)載均衡
百度網(wǎng)盤下載:
鏈接: https://pan.baidu.com/s/1T-YRtfuuJq0xA4jqlWxvkQ?pwd=1gcj
提取碼: 1gcj
參考資料:
源碼運(yùn)行方法:
模塊詳細(xì)功能說(shuō)明和運(yùn)行測(cè)試方法
依次啟動(dòng)nacos、server(兩個(gè))、client,在瀏覽器中輸入:http://localhost:19503/swagger-ui/index.html#/open-feign-controller/loadHelloContent,觀察返回字符串中端口的變化。
到此這篇關(guān)于Alibaba SpringCloud集成Nacos、openFeign實(shí)現(xiàn)負(fù)載均衡的文章就介紹到這了,更多相關(guān)SpringCloud負(fù)載均衡內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA2023創(chuàng)建MavenWeb項(xiàng)目并搭建Servlet工程的全過(guò)程
Maven提供了大量不同類型的Archetype模板,通過(guò)它們可以幫助用戶快速的創(chuàng)建Java項(xiàng)目,這篇文章主要給大家介紹了關(guān)于IDEA2023創(chuàng)建MavenWeb項(xiàng)目并搭建Servlet工程的相關(guān)資料,需要的朋友可以參考下2023-10-10JavaSE中compare、compareTo的區(qū)別
本文主要介紹了JavaSE中compare、compareTo的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05Java 基礎(chǔ)語(yǔ)法之解析 Java 的包和繼承
包是組織類的一種方式,繼承顧名思義,比如誰(shuí)繼承了長(zhǎng)輩的產(chǎn)業(yè),其實(shí)這里的繼承和我們生活中的繼承很類似,下面文字將為大家詳細(xì)介紹Java的包和繼承2021-09-09在Java中FreeMarker?模板來(lái)定義字符串模板
這篇文章主要介紹了在Java中FreeMarker?模板來(lái)定義字符串模板,文章基于Java的相關(guān)資料展開(kāi)詳細(xì)內(nèi)容,需要的小伙伴可以參考一下2022-04-04Java8 自定義CompletableFuture的原理解析
這篇文章主要介紹了Java8 自定義CompletableFuture的原理解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11SpringBoot中@Scheduled實(shí)現(xiàn)服務(wù)啟動(dòng)時(shí)執(zhí)行一次
本文主要介紹了SpringBoot中@Scheduled實(shí)現(xiàn)服務(wù)啟動(dòng)時(shí)執(zhí)行一次,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08Spring AOP定義Before增加實(shí)戰(zhàn)案例詳解
這篇文章主要介紹了Spring AOP定義Before增加,結(jié)合實(shí)例形式詳細(xì)分析了Spring面向切面AOP定義Before增加相關(guān)定義與使用技巧,需要的朋友可以參考下2020-01-01如何通過(guò)java將doc文件轉(zhuǎn)換為docx文件詳解
在數(shù)字化時(shí)代文檔處理成為了我們?nèi)粘9ぷ骱蛯W(xué)習(xí)中不可或缺的一部分,其中doc和docx作為兩種常見(jiàn)的文檔格式,各自具有不同的特點(diǎn)和優(yōu)勢(shì),這篇文章主要給大家介紹了關(guān)于如何通過(guò)java將doc文件轉(zhuǎn)換為docx文件的相關(guān)資料,需要的朋友可以參考下2024-07-07