目錄?
一、整合注冊中心nacos
二、整合openFeign
(一)準(zhǔn)備工作
(二)導(dǎo)入依賴?
(三)接口的遠(yuǎn)程調(diào)用
(四)配置超時(shí)控制和日志打印
三、整合Sentinel
四、整合gateway服務(wù)網(wǎng)關(guān)
一、整合注冊中心nacos
使用nacos1.4.1,下載地址:Releases · alibaba/nacos · GitHub
詳細(xì)可以看這篇文章:SpringCloud AlibabaNacos服務(wù)注冊和配置中心?
進(jìn)入nacos目錄下的bin目錄,通過cmd窗口輸入startup.cmd -m standalone啟動(dòng)nacos
通過8848端口訪問nacos,賬號(hào)密碼都為nacos
http://localhost:8848/nacos/
在service-base模塊中配置Nacos客戶端依賴
<!--服務(wù)發(fā)現(xiàn)-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
給每一個(gè)微服務(wù)配置nacos發(fā)現(xiàn)的配置
#spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848 # nacos服務(wù)地址
?可以看到三個(gè)服務(wù)都注冊進(jìn)來了
二、整合openFeign
在用戶注冊時(shí),原本我們的流程是用戶填寫信息,獲取驗(yàn)證碼,點(diǎn)擊登錄后再判斷是否注冊過,這樣子即浪費(fèi)用戶時(shí)間又浪費(fèi)短信次數(shù),應(yīng)該在點(diǎn)擊獲取驗(yàn)證碼的時(shí)候就對手機(jī)號(hào)進(jìn)行判斷,即在service-ssm獲取驗(yàn)證碼的方法中調(diào)用service-core的userInfo對象查詢數(shù)據(jù)庫是否該手機(jī)已經(jīng)有注冊用戶。像這樣一個(gè)微服務(wù)調(diào)用另外一個(gè)微服務(wù)的情況,我們就可以整合openFeign進(jìn)行服務(wù)接口的調(diào)用
(一)準(zhǔn)備工作
首先在userInfoController中添加校驗(yàn)手機(jī)號(hào)是否注冊的方法
@ApiOperation("校驗(yàn)手機(jī)號(hào)是否注冊")
@GetMapping("/checkMobile/{mobile}")
public boolean checkMobile(@PathVariable String mobile){
return userInfoService.checkMobile(mobile);
}
userService
boolean checkMobile(String mobile);
?userServiceImpl
@Override
public boolean checkMobile(String mobile) {
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("mobile", mobile);
Integer count = baseMapper.selectCount(queryWrapper);
return count > 0;
}
(二)導(dǎo)入依賴?
引入openFeign,在service-base的pom.xml中導(dǎo)入依賴
<!--服務(wù)調(diào)用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
?在service-sms啟動(dòng)類上添加注解@EnableFeignClients
(三)接口的遠(yuǎn)程調(diào)用
service-sms中添加遠(yuǎn)程調(diào)用的client接口,調(diào)用生產(chǎn)者的方法
@FeignClient(value = "service-core")
public interface CoreUserInfoClient {
// 注意這里的路徑要寫全
@GetMapping("/api/core/userInfo/checkMobile/{mobile}")
boolean checkMobile(@PathVariable String mobile);
}
在ApiSmsController引入client
@Resource
private CoreUserInfoClient coreUserInfoClient;
在獲取驗(yàn)證碼方法中調(diào)用遠(yuǎn)程方法校驗(yàn)手機(jī)號(hào)是否存在
//手機(jī)號(hào)是否注冊
boolean result = coreUserInfoClient.checkMobile(mobile);
System.out.println("result = " + result);
Assert.isTrue(result == false, ResponseEnum.MOBILE_EXIST_ERROR);
//生成驗(yàn)證碼
.....
(四)配置超時(shí)控制和日志打印
openfeign默認(rèn)的連接超時(shí)時(shí)間為1秒,測試時(shí)很可能會(huì)出現(xiàn)遠(yuǎn)程調(diào)用超時(shí)錯(cuò)誤。
可以在配置文件中添加如下配置:
feign:
client:
config:
default:
connectTimeout: 10000 #連接超時(shí)配置
readTimeout: 600000 #執(zhí)行超時(shí)配置
OpenFeign提供了日志打印功能,我們可以通過配置來調(diào)整日志級(jí)別,從而了解OpenFeign中Http請求的細(xì)節(jié)。即對OpenFeign遠(yuǎn)程接口調(diào)用的情況進(jìn)行監(jiān)控和日志輸出。
日志級(jí)別
- NONE:默認(rèn)級(jí)別,不顯示日志
- BASIC:僅記錄請求方法、URL、響應(yīng)狀態(tài)及執(zhí)行時(shí)間
- HEADERS:除了BASIC中定義的信息之外,還有請求和響應(yīng)頭信息
- FULL:除了HEADERS中定義的信息之外,還有請求和響應(yīng)正文及元數(shù)據(jù)信息
配置日志bean
在service-base中創(chuàng)建配置文件
@Configuration
public class OpenFeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
開啟日志
?sms的application.yml中指定監(jiān)控的接口,以及日志級(jí)別
logging:
level:
com.atguigu.srb.sms.client.CoreUserInfoClient: DEBUG #以什么級(jí)別監(jiān)控哪個(gè)接口
修改logback日志級(jí)別
?修改日志的level為DEBUG
<!-- 開發(fā)環(huán)境和測試環(huán)境 -->
<springProfile name="dev,test">
<logger name="com.atguigu" level="DEBUG">
<appender-ref ref="CONSOLE" />
</logger>
</springProfile>
查看日志輸出
HTTP 是一種無狀態(tài)協(xié)議,客戶端向服務(wù)器發(fā)送一個(gè) TCP 請求,服務(wù)端響應(yīng)完畢后斷開連接。
如果客戶端向服務(wù)器發(fā)送多個(gè)請求,每個(gè)請求都要建立各自獨(dú)立的連接以傳輸數(shù)據(jù)。
HTTP 有一個(gè) KeepAlive 模式,它告訴 webserver 在處理完一個(gè)請求后保持這個(gè) TCP 連接的打開狀態(tài)。
若接收到來自客戶端的其它請求,服務(wù)端會(huì)利用這個(gè)未被關(guān)閉的連接,而不需要再建立一個(gè)連接。
KeepAlive 在一段時(shí)間內(nèi)保持打開狀態(tài),它們會(huì)在這段時(shí)間內(nèi)占用資源。占用過多就會(huì)影響性能。
timeout 來指定 KeepAlive 的超時(shí)時(shí)間(timeout)。指定每個(gè) TCP 連接最多可以保持多長時(shí)間。
三、整合Sentinel
當(dāng)sms服務(wù)調(diào)用core服務(wù),如果core服務(wù)出現(xiàn)問題無法響應(yīng),此時(shí)會(huì)造成sms的忙等,如果有別的服務(wù)也在這條鏈路上,那么整條鏈路都會(huì)崩壞。所以我們需要對調(diào)用做兜底
service-base引入sentinel的依賴
<!--服務(wù)容錯(cuò)-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
在service-sms的yml配置文件中開啟Feign對Sentinel的支持
#開啟Feign對Sentinel的支持
#feign:
sentinel:
enabled: true
創(chuàng)建容錯(cuò)類,即兜底方案,fallback:當(dāng)無法校驗(yàn)手機(jī)號(hào)是否已注冊時(shí),直接發(fā)送短信
@Service
@Slf4j
public class CoreUserInfoClientRollback implements CoreUserInfoClient {
/*
* 當(dāng)接口中的原本的服務(wù)出現(xiàn)問題沒法響應(yīng)時(shí),調(diào)用當(dāng)前方法,即為服務(wù)降級(jí)
* 也相當(dāng)于一種兜底方案,需要在接口上FeignClient的fallback注冊
*/
@Override
public boolean checkMobile(String mobile) {
return false;
}
}
為OpenFeign遠(yuǎn)程調(diào)用接口添加fallback屬性值沒指定容錯(cuò)類
@FeignClient(value = "service-core", fallback = CoreUserInfoClientFallback.class)
public interface CoreUserInfoClient {
此時(shí)重新啟動(dòng)service-sms服務(wù)并停止service-core服務(wù),發(fā)送驗(yàn)證碼可以發(fā)現(xiàn)短信發(fā)送成功,而且redis中也有驗(yàn)證碼,說明走了兜底方案
四、整合gateway服務(wù)網(wǎng)關(guān)
我們使用gateway代替nginx文章來源:http://www.zghlxwxcb.cn/news/detail-424869.html
(一)添加依賴
<dependencies>
<!-- 網(wǎng)關(guān) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--服務(wù)注冊-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
(二)配置application
server:
port: 80 # 服務(wù)端口
spring:
profiles:
active: dev # 環(huán)境設(shè)置
application:
name: service-gateway # 服務(wù)名
cloud:
nacos:
discovery:
server-addr: localhost:8848 # nacos服務(wù)地址
gateway:
discovery:
locator:
enabled: true # gateway可以發(fā)現(xiàn)nacos中的微服務(wù),并自動(dòng)生成轉(zhuǎn)發(fā)路由
(三)logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<contextName>atguiguSrb</contextName>
<!-- 日志的輸出目錄 -->
<property name="log.path" value="D:/idealworkspace/shangrb/srb_log/gateway" />
<!--控制臺(tái)日志格式:彩色日志-->
<!-- magenta:洋紅 -->
<!-- boldMagenta:粗紅-->
<!-- cyan:青色 -->
<!-- white:白色 -->
<!-- magenta:洋紅 -->
<property name="CONSOLE_LOG_PATTERN"
value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>
<!--文件日志格式-->
<property name="FILE_LOG_PATTERN"
value="%date{yyyy-MM-dd HH:mm:ss} [%-5level] %thread %file:%line %logger %msg%n" />
<!--編碼-->
<property name="ENCODING"
value="UTF-8" />
<!-- 控制臺(tái)日志 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>${ENCODING}</charset>
</encoder>
</appender>
<!-- 文件日志 -->
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${log.path}/log.log</file>
<append>true</append>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>${ENCODING}</charset>
</encoder>
</appender>
<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 要區(qū)別于其他的appender中的文件名字 -->
<file>${log.path}/log-rolling.log</file>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>${ENCODING}</charset>
</encoder>
<!-- 設(shè)置滾動(dòng)日志記錄的滾動(dòng)策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志歸檔路徑以及格式 -->
<fileNamePattern>${log.path}/info/log-rolling-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!--歸檔日志文件保留的最大數(shù)量-->
<maxHistory>15</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>1KB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<!-- <logger name="com.atguigu" level="INFO">-->
<!-- <appender-ref ref="CONSOLE" />-->
<!-- <appender-ref ref="FILE" />-->
<!-- </logger>-->
<!-- 開發(fā)環(huán)境和測試環(huán)境 -->
<springProfile name="dev,test">
<logger name="com.atguigu" level="INFO">
<appender-ref ref="CONSOLE" />
</logger>
</springProfile>
<!-- 生產(chǎn)環(huán)境 -->
<springProfile name="prod">
<logger name="com.atguigu" level="ERROR">
<appender-ref ref="CONSOLE" />
<appender-ref ref="ROLLING_FILE" />
</logger>
</springProfile>
</configuration>
(四)啟動(dòng)類
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceGatewayApplication.class, args);
}
}
(五)配置路由
#spring:
# cloud:
# gateway:
routes:
- id: service-core
uri: lb://service-core
predicates:
- Path=/*/core/**
- id: service-sms
uri: lb://service-sms
predicates:
- Path=/*/sms/**
- id: service-oss
uri: lb://service-oss
predicates:
- Path=/*/oss/**
(六)跨域配置
使用nginx的時(shí)候,對于跨域問題我們的方案是在類上加上@CrossOrigin注解,使用gateway后原本的方案就不行了,需要使用以下配置類解決文章來源地址http://www.zghlxwxcb.cn/news/detail-424869.html
package com.atguigu.srb.gateway.config;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); //是否允許攜帶cookie
config.addAllowedOrigin("*"); //可接受的域,是一個(gè)具體域名或者*(代表任意域名)
config.addAllowedHeader("*"); //允許攜帶的頭
config.addAllowedMethod("*"); //允許訪問的方式
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
到了這里,關(guān)于尚融寶21-整合springcloud的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!