天天看點

服務發現之:EurekaClient

在springboot的官方文檔中有介紹怎麼搭建EurekaClient,這裡我們結合Idea來搭建EurekaClient

在文檔中有一段是這樣描述的:

To include the Eureka Client in your project, use the starter with a group ID of org.springframework.cloud and an artifact ID of spring-cloud-starter-netflix-eureka-client

如果要建立一個Eureka client在你的項目中,需要使用group ID是“org.springframework.cloud”和artifact ID是“spring-cloud-starter-netflix-eureka-client”的starter,因為我們項目一般是一個web項目,是以在我們搭建的時候也包含一個web的starter。

服務發現之:EurekaClient
服務發現之:EurekaClient

官網上有這樣一段描述:

@SpringBootApplication
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}
           

Note that the preceding example shows a normal Spring Boot application. By having spring-cloud-starter-netflix-eureka-client on the classpath, your application automatically registers with the Eureka Server. Configuration is required to locate the Eureka server, as shown in the following example:

注意以上示例展示的是一個正常的springboot應用程式。随着having spring-cloud-starter-netflix-eureka-client 加入包類路徑下,你的應用會自動的注冊到Eureka Server上。

然後需要把配置檔案application.properties檔案改成application.yml添加如下配置

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
           

這段配置是官網給的配置。

如果在我們測試當中僅僅加入一個這樣的配置也是可以讓EurekaServer發現它或者是EurekaClient也可以注冊到Eureka Server上,但是我們通路注冊中心管理頁面看一下情況

服務發現之:EurekaClient

雖然是發現了他但是感覺并不是很友好,我們把服務名稱和端口加上再看看

application.yml

spring:
  application:
    name: product-service
server:
    port: 8771
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
           
服務發現之:EurekaClient

Having spring-cloud-starter-netflix-eureka-client on the classpath makes the app into both a Eureka “instance” (that is, it registers itself) and a “client” (it can query the registry to locate other services). The instance behaviour is driven by eureka.instance.* configuration keys, but the defaults are fine if you ensure that your application has a value for spring.application.name (this is the default for the Eureka service ID or VIP).

如果有了spring-cloud-starter-netflix-eureka-client在你的類路徑下,那麼你就有了倆個功能,一個是把自己注冊到Eureka Server上,一個是作為一個用戶端可以查找到注冊到EurekaServer上的其他服務。注冊到EurekaServer 上的執行個體表現都是來自于eureka.instance.*的配置的keys,但這些預設值的也是可以,如果你確定你的應用有了一個spring.application.name配置的應用名稱(這個就是預設Eureka服務的id)。

To disable the Eureka Discovery Client, you can set eureka.client.enabled to false. Eureka Discovery Client will also be disabled when spring.cloud.discovery.enabled is set to false.

使Eureka discovery client不能使用的倆個配置,一個是你可以設定eureka.client.enabled為false,一個是設定spring.cloud.discovery.enabled 為false

親測有效

繼續閱讀