介紹spring
spring-cloud-eureka,更加具體的內容,這裏將會介紹遠程服務調用和及其負載均衡。須要JAVA Spring Cloud大型企業分佈式微服務雲構建的B2B2C電子商務平臺源碼 一零三八七七四六二六瀏覽器
咱們將咱們的服務註冊在咱們的服務中內心,那麼如何去調用這些服務呢?咱們能夠用使用遠程服務調用來解決,順帶還有方便的負載均衡功能。app
如何使用負載均衡
建立服務中心分佈式
註冊幾個被調用服務微服務
註冊一個consumer測試
測試consumer與負載均衡url
上一篇文章,咱們已經學會了使用單機或者集羣的方式來建立服務中心,這裏咱們使用簡單的單機方式來建立!rest
在 spring-cloud-eureka-server 裏啓動採用這個profile文件:code
server: port: 8761 spring: application: name: eureka-server eureka: instance: lease-expiration-duration-in-seconds: 6 lease-renewal-interval-in-seconds: 2 client: service-url: defaultZone: http://localhost:8761/eureka/
這個是單機版的。並將本身註冊到了服務裏。
咱們啓動了這三個profile文件。
配置文件中,server.port 分別是 8083,8084,8085,其餘參數徹底一致!同時,咱們在controller中設置了這樣一個rest服務。
@Value("${server.port}") String port; @RequestMapping("/hi") public String hi() { return port+" 端口爲您服務!"; }
這樣方便知道咱們具體調用了哪一個服務。
須要額外的依賴,使用了feign來進行遠程調用。
pom.xml :
<!--遠程調用--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
建立一個接口:
@Component @FeignClient(name = "eureka-client-1") public interface HelloRemoteInterface { @RequestMapping(value = "/hi") public String hi(); }
這裏的name就是你的那個服務的application.name。根據名字來調用,才能實現負載均衡嘛。
使用接口,建立一個測試的controller:
@RestController public class ConsumerController { @Autowired HelloRemoteInterface helloRemoteInterface; @RequestMapping("/hello") public String hello() { return helloRemoteInterface.hi(); } }
同時,將咱們的這個服務也註冊到服務中心。
配置文件:
server: port: 8086 spring: application: name: eureka-consumer eureka: client: service-url: defaultZone: http://localhost:8761/eureka/
啓動方法:
@SpringBootApplication @EnableEurekaClient @EnableFeignClients public class SpringCloudEurekaConsumerApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudEurekaConsumerApplication.class, args); } }
到這裏,咱們已經啓動了好多個服務,如上圖所示,在IDEA中,採用不一樣的profile來啓動的方式,有一個單機的server,三個普通的服務(端口號不同),還有咱們的消費服務,下一節,你能夠從截圖中看的更明白。
到上一步爲止,咱們已經能夠看到在Eureka的dashboard中已經有了好多個服務,以下圖,主要包括:
一個服務註冊server
一個消費者,用來進行遠程調用
三個普通的client(其端口不同,來模擬分佈式)
這時候,咱們調用咱們的consumer服務,瀏覽器裏輸入 http://localhost:8086/hello
獲得的結果是不同的,一共有三個:
8083 端口爲您服務!
8084 端口爲您服務!
8085 端口爲您服務!
正好就是咱們想要的結果。
不斷的進行測試下去會發現3種結果交替出現,說明服務中心自動提供了服務均衡負載的功能。若是咱們將服務提供者的數量在提升爲N個,測試結果同樣,請求會自動輪詢到每一個服務端來處理。