Consul集群加入網關服務
架構示意圖
外部的應用或網站通過外部網關服務消費各種服務,內部的生產者本身也可能是消費者,內部消費行為通過內部網關服務消費。
一個內部網關和一個外部網關以及一個Consul Client部署在一台服務器上,這樣的網關服務器至少2組,外部網關前面還會有負載均衡設備,內部網關服務使用Consul Client進行查詢后使用,內部網關的負載均衡由Consul負責了。
搭建演示環境
在Consul集群Server+Client模式的基礎上,我們更新並啟動網關服務和消費者服務,演示環境中我們只啟動一個網關服務進行模擬。
刪除spring-cloud-gateway和spring-cloud-consul-consumer這兩個容器。
docker pull bluersw/spring-cloud-gateway:v3
docker run --name=spring-cloud-gateway -d -p 9000:9000 bluersw/spring-cloud-gateway:v3 /opt/consul/./consul agent -data-dir=/opt/consul/data -config-dir=/opt/consul/config -node=gw-cc -join 172.17.0.2
docker exec spring-cloud-gateway /usr/local/java/bin/java -jar /opt/spring-cloud-gateway-0.0.1-SNAPSHOT.jar
docker pull bluersw/spring-cloud-consul-consumer:v3
docker run --name=spring-cloud-consul-consumer -d -p 9003:9003 bluersw/spring-cloud-consul-consumer:v3 /opt/consul/./consul agent -data-dir=/opt/consul/data -config-dir=/opt/consul/config -node=consumer-cc -join 172.17.0.2
docker exec spring-cloud-consul-consumer /usr/local/java/bin/java -jar /opt/spring-cloud-consul-client-0.0.1-SNAPSHOT.jar
TAG:V3版本的網關和消費者鏡像修改內容
spring-cloud-gateway的項目配置文件修改如下(也是在本機Consul Client注冊),主要是為了增加prefer-ip-address否則Consul獲取不到服務的IP地址:
server:
port: 9000
spring:
cloud:
consul:
host: 127.0.0.1
port: 8500
discovery:
register: true
prefer-ip-address: true
health-check-path: /actuator/health
gateway:
routes:
- id: test_route
uri: lb://service-provider
predicates:
- Path=/service-provider/{segment}
filters:
- SetPath=/{segment}
- name: Hystrix
args:
name: service-provider-fallback
fallbackUri: forward:/service-provider-error
- name: Retry
args:
retries: 3
statuses: BAD_GATEWAY,BAD_REQUEST
default-filters:
- name: Hystrix
args:
name: fallbackcmd
fallbackUri: forward:/default-error
application:
name: PC-ApiGateWay
為了模擬內部服務調用網關消費其他服務,spring-cloud-consul-client項目(spring-cloud-consul-consumer)添加如下代碼:
創建Feign風格的代理類
//網關服務
@FeignClient(name="PC-ApiGateWay")
public interface GatewayRemote {
//網關上的請求地址和外部用瀏覽器瀏覽的路徑相同
@RequestMapping("/service-provider/hello")
public String Hello(@RequestParam String name);
}
Controller里增加如下方法:
@Autowired
GatewayRemote gatewayRemote;
@RequestMapping("/TestGW")
public String TestGW(){
String first = gatewayRemote.Hello("first-SWS");
String second = gatewayRemote.Hello("second-SWS");
return first + " | " + second;
}
模擬外部訪問
直接在瀏覽器里訪問127.0.0.1:9000/service-provider/hello?name=sws,得到服務的返回信息:
模擬內部訪問
在瀏覽器里訪問127.0.0.1:9003/TestGW,得到服務的返回信息:
源碼
Github倉庫:https://github.com/sunweisheng/spring-cloud-example