下午有時間,繼續接着,上次的看。web
上次已經完成了Eureka的搭建,和集羣,今天開始研究服務的註冊和發佈spring
建立一個工程,爲註冊服務,向Eureka服務中心,進行註冊app
選擇好之後,建立成功註冊服務工程ide
開始進行配置測試
application.properties配置文件 裏面,增長服務配置idea
spring.application.name=spring-cloud-consumer server.port=9000 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
spring.application.name 服務名稱,用戶服務之間,進行調用3d
port端口 eureka.client.serviceUrl.defaultZone設置與Eureka Server交互的地址,查詢服務和註冊服務都須要依賴這個地址。多個地址可以使用 , 分隔。server
Springboot的啓動文件增長配置註解,讓Eureka發現此服務,進行註冊blog
@EnableDiscoveryClient//啓用服務註冊與發現
啓動項目,訪問Eureka8000端口,發現,新增了一個服務,服務名,與配置文件相同接口
建立controller
package com.example.democloudserver.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { /** * 測試服務註冊 * @param name * @return */ @GetMapping("/hello") public String index(@RequestParam String name){ return "hello-2:"+ name; } }
好了,這一步,已經說明,服務註冊成功,下面,建立調用服務,用過Eureka調用,剛纔註冊的服務
建立調用服務和以前基本相同,idea建立工程,就能夠,惟一不一樣的是,調用服務,須要Feign,全部,在這裏,還要進行勾選這個
建立成功項目,開始配置
spring.application.name=spring-cloud-consumer server.port=9001 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
啓動項配置
@EnableDiscoveryClient//啓用服務註冊與發現 @EnableFeignClients//啓用feign進行遠程調用
開啓feign的做用,是進行遠程調用,開啓EnableDiscoveryClient,是爲了讓Eureka發現
建立一個接口,經過註解,遠程調用剛纔的註冊服務
package com.example.servicefeign.interfaceServer; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name= "spring-cloud-producer") //name:遠程服務名,及spring.application.name配置的名稱 public interface HelloRemote { @RequestMapping(value = "/hello") public String hello(@RequestParam(value = "name") String name); }
定義好了之後,能夠注入controller,進行調用
package com.example.servicefeign.controller; import com.example.servicefeign.interfaceServer.HelloRemote; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired HelloRemote hello;//註冊接口層 @RequestMapping("/hello/{name}") public String index(@PathVariable("name") String name) { return hello.hello(name); } }
啓動服務調用層,訪問controller進行訪問,調動註冊的服務,成功
這裏,我也順便測試了,服務中心提供的服務均衡負載
註冊服務,設置不一樣的端口,相同的服務名,進行啓動,修改輸出controller輸出爲
"hello-2:"+ name
"hello-1:"+ name
頁面屢次請求,發現兩種結果交替出現。