1. 程式人生 > 實用技巧 >Spring Cloud 框架 -- Eureka 服務的註冊與消費

Spring Cloud 框架 -- Eureka 服務的註冊與消費

服務註冊

服務註冊就是把一個微服務註冊到 Eureka Server 上,這樣,當其他服務需要呼叫該服務時,只需要從 Eureka Server 上查詢該服務的資訊即可。

這裡建立一個 provider ,作為服務提供者,建立專案時,選擇 Eureka Client 依賴,這樣,當服務建立完成後,簡單配置一下,就可以被註冊到 Eureka Server 上了:

專案建立好了後,在 application.properties 中配置一下:

# 設定當前服務的名稱
spring.application.name=provider   
# 設定當前服務的埠號
server.port=1113
# 設定當前服務的註冊地址
eureka.client.service-url.defaultZone = http://localhost:1111/eureka

然後,先啟動 Eureka Server (Eureka 的搭建參考文章https://www.cnblogs.com/youcoding/p/13238058.html),待服務註冊中心啟動成功後,再啟動 provider 。

隨後,再在瀏覽器中輸入 http://localhost:1111,就可以檢視 provider 的註冊資訊,如下圖:

服務消費

首先在 provider 中提供一個介面,然後建立一個新的 consumer 專案,消費這個介面;

在 provider 中,提供一個 hello 介面,如下:

@RestController
public class HelloController {
    @Value("${server.port}")
    Integer port;
    @GetMapping("/hello")
    public String hello(){
        return "hello you!" + port;
    }
}

建立一個 consumer 專案,新增 web 和 eureka client 依賴:

建立完成後,我們首先在 application.properties 中配置一下注冊資訊:

spring.application.name=consumer
# 應用服務 WEB 訪問埠
server.port=1116
eureka.client.service-url.defaultZone = http://localhost:1111/eureka

消費者 consumer 的主函式如下:

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient

public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    // 建立一個 RestTemplate 例項
    // 並開啟客戶端負載均衡
    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

再新建 HelloController 類,定義一個 hello 介面:

@RestController
public class HelloController {
    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/hello")
    public String hello(){
        return restTemplate.getForObject("http://PROVIDER/hello", String.class);
        //return "hello haha";
    }
}

啟動 consumer,開啟 eureka 後臺,檢視註冊情況:

忽略掉 Hystrix ,可以看到,provider 和 consumer 成功註冊到 eureka 之中。

再訪問 http://localhost:1116/hello, 如下圖:

如上,就是 eureka 的服務註冊與消費。

每天學習一點點,每天進步一點點。