瞭解spring cloud的可以看下這篇文章
https://blog.csdn.net/forezp/article/details/70148833/
下面簡單介紹些使用
spring cloud有一個註冊中心,作爲服務端;然後多個客戶端註冊到註冊中心
簡單介紹下服務端跟客戶端 網管什麼的還沒搞清楚就不寫了
服務端
第一步 導入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
第二步配置啓動項
@EnableEurekaServer
在啓動類添加註解,表明是spring cloud的服務端
第三步 配置配置文件
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://你的鏈接地址:端口號(默認8761)/eureka/ #服務地址
# 關閉eureka自我保護機制
server:
enableSelfPreservation: false
evictionIntervalTimerInMs: 4000 # 清理間隔(單位毫秒,默認是60*1000)
# Eureka 安全認證
security:
basic:
enabled: true
user:
name: 用戶名
password: 密碼
到此 服務端配置完畢
客戶端
第一步 導入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
兩個依賴 一個表明是客戶端 ,另一個是spring cloud使用的一個依賴
配置啓動項
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
註解@EnableDiscoveryClient,@EnableEurekaClient的區別
EnableFeignClients 實現遠程調用跟負載均衡的註解
配置配置文件
eureka:
client:
serviceUrl:
defaultZone: http://你的服務端鏈接地址:端口號/eureka/
spring:
application:
name: 你的應用名 #應用名
這裏還有其他一些配置 具體的可以百度下 上面的是服務端的地址 以便註冊到服務端
配置結束,下面是具體使用
以下總結自廖師兄視頻 如有侵權 告知即刪除
廖師兄的視頻裏更詳細 大家可以去看下
spring cloud微服務實戰
客戶端B輸出一句話,客戶端A調用
看上去很想我們平時寫的接收前臺請求路徑調用的方式,但其實是spring cloud客戶端之間的調用
客戶端A調用有三種方式
方式一 直接使用eurke提供的restTemplate
這裏上面直接寫你調用的客戶端的ip加端口號就可以,但是有缺點,集羣的時候沒法用
方式二 使用loadBalance
通過autowired註解 把 loadBlanceClient引入。
通過loadBlanceClient類 選擇你調用的應用的名稱,他會自己進行負載均衡
方式三 通過bean註解
配置restTemplate
使用autowired註解引入restTemplat類
然後就可以直接使用這個類,調用拼接你另一個客戶端的方法就可以了
最後還有一種終極調用方式, 需要在調用的客戶端導入下面一個依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
上面的話即是在A的pom里加上如上依賴
在A的啓動項加下面這個註解
@EnableFeignClients
新建一個clien接口,通過註解 聲明調用的應用名 調用的應用是哪一個
然後 在A的controller 注入這個client調用方法即可
以上就是spring cloud使用的簡單案例 如果有不明白的 請留言 寫的可能有些含糊