包括服務註冊中心,服務提供方(註冊服務),服務使用方(調用服務)
註冊中心:
1. 使用spring-cloud-starter-eureka-server,主類中使用@EnableEurekaServer,開啓服務註冊功能,增加服務註冊中心
2. 配置yml
server.port=10001
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
3. 啓動註冊中心工程後,訪問:http://localhost:10001/ 可通過spring自帶的管理器查看註冊中心的服務註冊信息。
服務註冊:
1. 各個服務提供方使用spring-cloud-starter-eureka,主類中使用@EnableEurekaClient,註冊到中心。
2. 配置yml
spring.application.name=provider-service
server.port=18443
eureka.client.serviceUrl.defaultZone=http://localhost:10001/eureka/
說明:
spring.application.name屬性,我們可以指定微服務的名稱後續在調用的時候只需要使用該名稱就可以進行服務的訪問。
eureka.client.serviceUrl.defaultZone屬性對應服務註冊中心的配置內容,指定服務註冊中心的位置。
3. 啓動該工程後,再次訪問:http://localhost:10001/ 可看到compute-service已註冊到中心。
服務調用:
1)Ribbon
使用spring-cloud-starter-ribbon,啓動類中使用@EnableEurekaClient,開啓服務發現功能,
創建RestTemplate實例到容器中,並通過@LoadBalanced註解到該實例,開啓均衡負載能力。
配置yml
spring.application.name=ribbon-service
server.port=30001
eureka.client.serviceUrl.defaultZone=http://localhost:10001/eureka/
優點:簡單、直接。
2)Feign
使用spring-cloud-starter-feign,啓動類中使用@EnableFeignClients,開啓Feign功能,
創建interface,並通過@FeignClient(value=服務名)綁定服務提供方服務到interface(相當於被調用接口的聲明),調用方直接注入該interface,通過調用本地接口就可實現RPC。Feign已包含Ribbon的負載均衡能力。
配置yml
spring.application.name=feign-service
server.port=40001
eureka.client.serviceUrl.defaultZone=http://localhost:10001/eureka/
優點:就像調用本地方法一樣調用遠程接口
實例源碼: register-server service-provider feign-call ribbon-call