springcloud項(xiàng)目快速開(kāi)始起始模板的實(shí)現(xiàn)
1.創(chuàng)建實(shí)體類模塊
引入依賴(這里使用tkmybatis的依賴)
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
效果如下

2.創(chuàng)建配置中心,搭建注冊(cè)中心集群
選擇依賴(修改spring cloud版本號(hào))

修改application.yml搭建server集群 此處要注意域名解析peer1,peer2,peer3
server:
port: 9004
spring:
application:
name: euraka-server
eureka:
client:
service-url:
#如果是集群,,后面用逗號(hào)隔開(kāi)
defaultZone: http://127.0.0.1:9004/eureka
#自己本身就是服務(wù)注冊(cè)中心,聲明不注冊(cè)自己
register-with-eureka: false
#聲明自己不拉取自己的服務(wù)注冊(cè)列表
fetch-registry: false
instance:
# ?跳間隔時(shí)間
lease-renewal-interval-in-seconds: 30
# 沒(méi)收到?跳多?時(shí)間剔除
lease-expiration-duration-in-seconds: 90
server:
enable-self-preservation: false # 關(guān)閉?我保護(hù)模式(缺省為打開(kāi))
eviction-interval-timer-in-ms: 1000 # 掃描失效服務(wù)的間隔時(shí)間(缺省為60*1000ms)
logging:
level:
com.netflix: warn
---
spring:
config:
activate:
on-profile: peer1
server:
port: 9003
eureka:
instance:
hostname: peer1
client:
service-url:
defaultZone: http://peer2:9004/eureka,http://peer3:9005/eureka
---
spring:
config:
activate:
on-profile: peer2
server:
port: 9004
eureka:
instance:
hostname: peer2
client:
service-url:
defaultZone: http://peer1:9003/eureka,http://peer3:9005/eureka
---
spring:
config:
activate:
on-profile: peer3
server:
port: 9005
eureka:
instance:
hostname: peer3
client:
service-url:
defaultZone: http://peer1:9003/eureka,http://peer2:9004/eureka
啟動(dòng)器加@EnableEurekaServer注解
3.創(chuàng)建網(wǎng)關(guān)(修改版本號(hào))

?網(wǎng)關(guān)yml配置文件
server:
port: 9006
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: service
uri: http://127.0.0.1:9001
predicates:
- Path=/pay/{segment}
filters:
- name: CircuitBreaker
args:
name: backendA
fallbackUri: forward:/fallbackA
#全部允許跨域訪問(wèn)
globalcors:
cors-configurations:
'[/**]':
allowed-origin-patterns: "*" # spring boot2.4配置
# allowed-origins: "*"
allowed-headers: "*"
allow-credentials: true
allowed-methods:
- GET
- POST
- DELETE
- PUT
- OPTION
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:9004/eureka
#網(wǎng)關(guān)熔斷,快速降級(jí)
resilience4j:
circuitbreaker:
configs:
default:
failureRateThreshold: 30 #失敗請(qǐng)求百分比,超過(guò)這個(gè)比例,CircuitBreaker變?yōu)镺PEN狀態(tài)
slidingWindowSize: 10 #滑動(dòng)窗口的大小,配置COUNT_BASED,表示10個(gè)請(qǐng)求,配置TIME_BASED表示10秒
minimumNumberOfCalls: 5 #最小請(qǐng)求個(gè)數(shù),只有在滑動(dòng)窗口內(nèi),請(qǐng)求個(gè)數(shù)達(dá)到這個(gè)個(gè)數(shù),才會(huì)觸發(fā)CircuitBreader對(duì)于斷路器的判斷
slidingWindowType: TIME_BASED #滑動(dòng)窗口的類型
permittedNumberOfCallsInHalfOpenState: 3 #當(dāng)CircuitBreaker處于HALF_OPEN狀態(tài)的時(shí)候,允許通過(guò)的請(qǐng)求個(gè)數(shù)
automaticTransitionFromOpenToHalfOpenEnabled: true #設(shè)置true,表示自動(dòng)從OPEN變成HALF_OPEN,即使沒(méi)有請(qǐng)求過(guò)來(lái)
waitDurationInOpenState: 2s #從OPEN到HALF_OPEN狀態(tài)需要等待的時(shí)間
recordExceptions: #異常名單
- java.lang.Exception
instances:
backendA:
baseConfig: default
backendB:
failureRateThreshold: 50
slowCallDurationThreshold: 2s #慢調(diào)用時(shí)間閾值,高于這個(gè)閾值的呼叫視為慢調(diào)用,并增加慢調(diào)用比例。
slowCallRateThreshold: 30 #慢調(diào)用百分比閾值,斷路器把調(diào)用時(shí)間大于slowCallDurationThreshold,視為慢調(diào)用,當(dāng)慢調(diào)用比例大于閾值,斷路器打開(kāi),并進(jìn)行服務(wù)降級(jí)
slidingWindowSize: 10
slidingWindowType: TIME_BASED
minimumNumberOfCalls: 2
permittedNumberOfCallsInHalfOpenState: 2
waitDurationInOpenState: 120s #從OPEN到HALF_OPEN狀態(tài)需要等待的時(shí)間
創(chuàng)建網(wǎng)關(guān)熔斷對(duì)應(yīng)降級(jí)方法
@RestController
@Slf4j
public class FallbackController {
@GetMapping("/fallbackA")
public ResponseEntity fallbackA() {
return ResponseEntity.ok("服務(wù)不可用,降級(jí)");
}
}
啟動(dòng)器加@EnableDiscoveryClient 或@EnableEurekaClient注解
還可以在網(wǎng)關(guān)中設(shè)置全局或局部過(guò)濾器
4.搭建配置中心
添加依賴()另加下面依賴實(shí)現(xiàn)git倉(cāng)庫(kù)自動(dòng)刷新,需要配合rabbitmq使用,需要內(nèi)網(wǎng)穿透

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
?yml配置文件(可以更改本地作為配置中心)
server:
port: 9007
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
application:
name: cloud-config
cloud:
config:
server:
git:
uri: https://gitee.com/zhaoy999/springcloud_config.git
search-paths: config
default-label: master
#配置中心設(shè)在本地使用
# profiles:
# active: native
# cloud:
# config:
# server:
# native:
# search-locations: classpath:/config
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:9004/eureka
#git倉(cāng)庫(kù)配置中心自動(dòng)刷新
management:
endpoints:
web:
exposure:
include: bus-refresh
endpoint:
bus-refresh:
enabled: true
在已經(jīng)指定好的倉(cāng)庫(kù)config目錄下創(chuàng)建配置文件
5.構(gòu)思需要的微服務(wù)(每個(gè)微服務(wù)既可以是提供者也可以是消費(fèi)者)
引入依賴(需要另外引入下面代碼塊的依賴)
!!!修改,先不要加sleuth依賴,會(huì)報(bào)錯(cuò)

這里使用的tkmybatis操作持久層
<!--使用rabbitmq鏈路追蹤,接收rabbitmq隊(duì)列消息,實(shí)現(xiàn)配置的自動(dòng)刷新-->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
</dependency>
<!--微服務(wù)限流-->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-ratelimiter</artifactId>
<version>1.7.0</version>
</dependency>
<!-- 信號(hào)量隔離-->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-bulkhead</artifactId>
<version>1.7.0</version>
</dependency>
<!-- 配置自動(dòng)刷新,需要配合@RefreshScope注解-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<!-- 可不用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--數(shù)據(jù)庫(kù)連接-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--tkmybatis-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
<!--PageHelper分頁(yè)插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.11</version>
</dependency>
<!--前后端分離使用的thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--tkmybatis使用,增強(qiáng)mybatis不能用-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
yml基本配置:
- 連接eureka注冊(cè)中心:啟動(dòng)器加@EnableDiscoveryClient 或@EnableEurekaClient注解
- 端口號(hào),服務(wù)名,連接配置中心:本地application.yml
- 鏈路追蹤配置:git倉(cāng)庫(kù)config目錄下application.yml
- rabbitmq消息接收配置:git倉(cāng)庫(kù)config目錄下application.yml
- 選擇性配置feign:git倉(cāng)庫(kù)config目錄下application.yml
- 熔斷,隔離,限流:git倉(cāng)庫(kù)config目錄下application.yml
- 數(shù)據(jù)庫(kù)連接::git倉(cāng)庫(kù)config目錄下application.yml
本地application.yml
server:
port: ${port:9001}
spring:
application:
name: pay-service
cloud:
config:
uri: http://localhost:9007
profile: default
label: master
config:
import: optional:configserver:http://localhost:9007
git倉(cāng)庫(kù)config目錄下application.yml
spring:
zipkin:
base-url: http://localhost:9411
sender:
type: web
sleuth:
sampler:
probability: 1
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://peer1:9003/eureka,http://peer2:9004/eureka,http://peer3:9005/eureka
feign:
client:
config:
default:
connectTimeout: 5000 #防止由于服務(wù)器處理時(shí)間長(zhǎng)而阻塞調(diào)用者
readTimeout: 5000 #從連接建立時(shí)開(kāi)始應(yīng)用,在返回響應(yīng)時(shí)間過(guò)長(zhǎng)時(shí)觸發(fā)
circuitbreaker:
enabled: true
compression:
request:
enabled: true # 請(qǐng)求壓縮
mime-types: text/xml,application/xml,application/json # 壓縮的類型
min-request-size: 2048 # 請(qǐng)求最小壓縮的閾值
response:
enabled: true #響應(yīng)壓縮
useGzipDecoder: true #使用gzip解碼器解碼響應(yīng)數(shù)據(jù)
logging:
level:
com.zhao: debug
#設(shè)置自己作為斷路器
resilience4j:
circuitbreaker:
configs:
default:
failureRateThreshold: 30 #失敗請(qǐng)求百分比,超過(guò)這個(gè)比例,CircuitBreaker變?yōu)镺PEN狀態(tài)
slidingWindowSize: 10 #滑動(dòng)窗口的大小,配置COUNT_BASED,表示10個(gè)請(qǐng)求,配置TIME_BASED表示10秒
minimumNumberOfCalls: 5 #最小請(qǐng)求個(gè)數(shù),只有在滑動(dòng)窗口內(nèi),請(qǐng)求個(gè)數(shù)達(dá)到這個(gè)個(gè)數(shù),才會(huì)觸發(fā)CircuitBreader對(duì)于斷路器的判斷
slidingWindowType: TIME_BASED #滑動(dòng)窗口的類型
permittedNumberOfCallsInHalfOpenState: 3 #當(dāng)CircuitBreaker處于HALF_OPEN狀態(tài)的時(shí)候,允許通過(guò)的請(qǐng)求個(gè)數(shù)
automaticTransitionFromOpenToHalfOpenEnabled: true #設(shè)置true,表示自動(dòng)從OPEN變成HALF_OPEN,即使沒(méi)有請(qǐng)求過(guò)來(lái)
waitDurationInOpenState: 2s #從OPEN到HALF_OPEN狀態(tài)需要等待的時(shí)間
recordExceptions: #異常名單
- java.lang.Exception
instances:
backendA:
baseConfig: default #熔斷器backendA,繼承默認(rèn)配置default
backendB:
failureRateThreshold: 50
slowCallDurationThreshold: 2s #慢調(diào)用時(shí)間閾值,高于這個(gè)閾值的呼叫視為慢調(diào)用,并增加慢調(diào)用比例。
slowCallRateThreshold: 30 #慢調(diào)用百分比閾值,斷路器把調(diào)用時(shí)間大于slowCallDurationThreshold,視為慢調(diào)用,當(dāng)慢調(diào)用比例大于閾值,斷路器打開(kāi),并進(jìn)行服務(wù)降級(jí)
slidingWindowSize: 10
slidingWindowType: TIME_BASED
minimumNumberOfCalls: 2
permittedNumberOfCallsInHalfOpenState: 2
waitDurationInOpenState: 2s #從OPEN到HALF_OPEN狀態(tài)需要等待的時(shí)間
bulkhead:
configs:
default:
maxConcurrentCalls: 5 # 隔離允許并發(fā)線程執(zhí)行的最大數(shù)量
maxWaitDuration: 20ms # 當(dāng)達(dá)到并發(fā)調(diào)用數(shù)量時(shí),新的線程的阻塞等待的最長(zhǎng)時(shí)間
instances:
backendA:
baseConfig: default
backendB:
maxWaitDuration: 10ms
maxConcurrentCalls: 20
#線程池隔離()
thread-pool-bulkhead:
configs:
default:
maxThreadPoolSize: 4 # 最大線程池大小
coreThreadPoolSize: 2 # 核心線程池大小
queueCapacity: 2 # 隊(duì)列容量
instances:
backendA:
baseConfig: default
backendB:
maxThreadPoolSize: 1
coreThreadPoolSize: 1
queueCapacity: 1
#微服務(wù)限流
ratelimiter:
configs:
default:
timeoutDuration: 5 # 線程等待權(quán)限的默認(rèn)等待時(shí)間
limitRefreshPeriod: 1s # 限流器每隔1s刷新一次,將允許處理的最大請(qǐng)求重置為2
limitForPeriod: 2 #在一個(gè)刷新周期內(nèi),允許執(zhí)行的最大請(qǐng)求數(shù)
instances:
backendA:
baseConfig: default
backendB:
timeoutDuration: 5
limitRefreshPeriod: 1s
limitForPeriod: 5
實(shí)現(xiàn)微服務(wù)的負(fù)載均衡(有使用resttemplate和使用openfeign兩種方式),這里直接使用restTemplate,在消費(fèi)者啟動(dòng)器類里引入restTemplate Bean類,加上@loadbalanced注解就可以用了
@EnableDiscoveryClient
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
使用方法示例:
@Autowired
private RestTemplate restTemplate;
@Autowired
DiscoveryClient discoveryClient;
@GetMapping("/pay/{id}")
@RateLimiter(name = "backendA", fallbackMethod = "fallback")
public ResponseEntity<Payment> getPaymentById(@PathVariable("id") Integer id) throws InterruptedException, ExecutionException {
log.info("now i enter the method!!!");
// Thread.sleep(10000L); //阻塞10秒,已測(cè)試慢調(diào)用比例熔斷
String url = "http://pay-service/pay/" + id;
Payment payment = restTemplate.getForObject(url, Payment.class);
log.info("now i exist the method!!!");
return ResponseEntity.ok(payment);
}
6.依賴引入完畢,以上全部微服務(wù)創(chuàng)建出來(lái)后修改位置
啟動(dòng)器加啟動(dòng)器加@EnableDiscoveryClient 或@EnableEurekaServer
逐個(gè)修改yml文件,修改端口號(hào)和服務(wù)名
打開(kāi)services,方便同時(shí)打開(kāi)多個(gè)服務(wù)
配置中心加@EnableConfigServer
修改倉(cāng)庫(kù)配置文件
添加本項(xiàng)目實(shí)體類依賴
打開(kāi)rabbitmq,打開(kāi)方法參考我的另一篇博客rabbitmq安裝全過(guò)程[含安裝包,可直接用
打開(kāi)鏈路追蹤控制臺(tái)
開(kāi)始寫邏輯代碼;

到此這篇關(guān)于springcloud項(xiàng)目快速開(kāi)始起始模板的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)springcloud 起始模板 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
理解Java注解及Spring的@Autowired是如何實(shí)現(xiàn)的
今天通過(guò)本文帶領(lǐng)大家學(xué)習(xí)注解的基礎(chǔ)知識(shí),學(xué)習(xí)Spring的@Autowired是怎么實(shí)現(xiàn)的,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-07-07
解決mybatis執(zhí)行SQL語(yǔ)句部分參數(shù)返回NULL問(wèn)題
這篇文章主要介紹了mybatis執(zhí)行SQL語(yǔ)句部分參數(shù)返回NULL問(wèn)題,需要的的朋友參考下吧2017-06-06
Flink實(shí)戰(zhàn)之實(shí)現(xiàn)流式數(shù)據(jù)去重
流式數(shù)據(jù)是一種源源不斷產(chǎn)生的數(shù)據(jù),本文探索了一種流式大數(shù)據(jù)的實(shí)時(shí)去重方法,不一定適用于所有場(chǎng)景,不過(guò)或許可以給面對(duì)相似問(wèn)題的你一點(diǎn)點(diǎn)啟發(fā),2025-03-03
淺談Java虛擬機(jī)對(duì)內(nèi)部鎖的四種優(yōu)化方式
這篇文章主要介紹了淺談Java虛擬機(jī)對(duì)內(nèi)部鎖的四種優(yōu)化方式,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10
關(guān)于SpringBoot自定義條件注解與自動(dòng)配置
這篇文章主要介紹了關(guān)于SpringBoot自定義條件注解與自動(dòng)配置,Spring Boot的核心功能就是為整合第三方框架提供自動(dòng)配置,而本文則帶著大家實(shí)現(xiàn)了自己的自動(dòng)配置和Starter,需要的朋友可以參考下2023-07-07
springboot訪問(wèn)靜態(tài)資源遇到的坑及解決
這篇文章主要介紹了springboot訪問(wèn)靜態(tài)資源遇到的坑及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot使用@EnableAutoConfiguration實(shí)現(xiàn)自動(dòng)配置詳解
你有想過(guò)SpringBoot為什么能夠自動(dòng)的幫我們創(chuàng)建一個(gè)Bean對(duì)象么?或許在我們使用的時(shí)候只需要在自己自定義的配置文件中加入@Bean對(duì)象就可以,但SpringBoot是如何來(lái)創(chuàng)建的呢2022-08-08
Java將字符串String轉(zhuǎn)換為整型Int的兩種方式
這篇文章主要介紹了Java如何將字符串String轉(zhuǎn)換為整型Int,在 Java 中要將 String 類型轉(zhuǎn)化為 int 類型時(shí),需要使用 Integer 類中的 parseInt() 方法或者 valueOf() 方法進(jìn)行轉(zhuǎn)換,本文通過(guò)實(shí)例代碼給大家詳細(xì)講解,需要的朋友可以參考下2023-04-04

