一文掌握Spring Cloud Erueka(附帶工程源碼)

一文掌握Spring Cloud Eureka

經過此程序你能夠學到java

  1. 搭建高可用的eureka servernode

  2. 服務提供者把服務發佈到erueka server上web

  3. 消費者應用接入erueka Server進行服務調用spring

  4. 消費方經過ribbon達到負載均衡的調用provider服務瀏覽器

1、項目結構

eurekserver ,兩個server,構建高可用
  • eurekaServer 端口:8800tomcat

  • eurekaServer2 端口:8801springboot

eureka 服務提供者,兩個Provider,服務
  • eurekaProvider 端口:8802app

  • eurekaProvider2 端口:8803負載均衡

eureka服務消費者,consumer,測試鏈接
  • eurekaConsumer 端口:8804ide

2、項目搭建

  • 版本選擇: Spring Cloud目前最新的Release版本是:Hoxton.SR6,經過官網查的,官方建議與之匹配的Spring Boot版本是:2.3.1.RELEASE


  • 圖片

  • springcloud版本:Hoxton.SR6

  • springboot版本:2.3.1.RELEASE

3、搭建單機版eruekaServer

  • 在idea中經過Spring Initializr來建立springCloud項目eruekaServer(傻瓜式操做,不描述)

  • pom.xml 引入spring-cloud-starter-netflix-eureka-server

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
    </parent>
   
    <groupId>com.fqh</groupId>
    <artifactId>server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eruekaServer</name>
   
    <properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Hoxton.SR6</spring-cloud.version>
    </properties>
   
    <dependencies>
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter</artifactId>
    </dependency>

    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    </dependencies>
  • EruekaServerApplication 加入@EnableEurekaServer註解

@EnableEurekaServer
@SpringBootApplication
public class EruekaServerApplication {

public static void main(String[] args) {
SpringApplication.run(EruekaServerApplication.class, args);
}
}
  • yml配置文件中 加入eureka相關配置

server:
 port: 8800
eureka:
 instance:
   hostname: 127.0.0.1
   prefer-ip-address: true
   leaseExpirationDurationInSeconds: 15
 client:
   register-with-eureka: false
   fetch-registry: false
   service-url:
     defaultZone: http://${eureka.instance.hostname}:8800/eureka/

這裏須要注意:單機版的erueka server的client配置裏,須要把register-with-eureka與fetch-registry參數都設置成false 表示此此erueka啓動後不向本身進行註冊,也不從本身讀取註冊信息。啓動EruekaServerApplication,查看日誌,發現eruekaServer已經啓動

Setting the eureka configuration..
2020-08-03 17:12:11.598  INFO 30533 --- [     Thread-383] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka data center value eureka.datacenter is not set, defaulting to default
2020-08-03 17:12:11.599  INFO 30533 --- [     Thread-383] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka environment value eureka.environment is not set, defaulting to test
2020-08-03 17:12:11.623  INFO 30533 --- [     Thread-383] o.s.c.n.e.server.EurekaServerBootstrap   : isAws returned false
2020-08-03 17:12:11.623  INFO 30533 --- [     Thread-383] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2020-08-03 17:12:11.624  INFO 30533 --- [     Thread-383] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2020-08-03 17:12:11.624  INFO 30533 --- [     Thread-383] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2020-08-03 17:12:11.624  INFO 30533 --- [     Thread-383] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2020-08-03 17:12:11.635  INFO 30533 --- [     Thread-383] e.s.EurekaServerInitializerConfiguration : Started Eureka Server

打開瀏覽器輸入localhost:8800,發現eureka已經啓動,而且Instances currently registered with Eureka中註冊的服務列表爲空 

4、服務提供者把服務發佈到erueka server中

  • 在idea中經過Spring Initializr來建立springCloud項目eruekaProvider,這裏咱們搭建2臺provider實例(eruekaProvider與eruekaProvider2)

  • pom.xml 引入spring-cloud-starter-netflix-eureka-client

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.fqh</groupId>
<artifactId>provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eruekaProvider</name>

<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • EruekaProviderApplication 加入@EnableDiscoveryClient註解,而且提供getUser方法對外提供Rest服務(注意這裏返回信息的from顯示provider-one)

@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class EruekaProviderApplication {

public static void main(String[] args) {
SpringApplication.run(EruekaProviderApplication.class, args);
}
/**
* 假如這個客戶端要提供一個getUser的方法
* @return
*/
@GetMapping(value = "/getUser")
@ResponseBody
public Map<String,Object> getUser(@RequestParam Integer id){
Map<String,Object> data = new HashMap<>();
data.put("id",id);
data.put("userName","張三");
data.put("from","provider-one");
return data;
}

}
  • application yml配置文件中增長eureka.client.serviceUrl.defaultZone配置

eureka:
 client:
   serviceUrl: #註冊中心的註冊地址
     defaultZone: http://127.0.0.1:8800/eureka/
server:
 port: 8802  #服務端口號
spring:
 application:
   name: user-provider #服務名稱--調用的時候根據名稱來調用該服務的方法
重複上面操做,搭建另外的一個provider實例

其中注意兩點

  • provide2 的EruekaProvider2Application的getUser方法裏的from的值爲:provider-two

  • provider2 的application yml配置文件的server.port 端口爲8803

分別啓動 兩個provider程序,查看啓動日誌 發現 Registering application USER-PROVIDER with eureka with status UP,說明已經把user-provider服務發佈到了erueka服務上了。

Discovery Client initialized at timestamp 1596450682466 with initial instances count: 1
2020-08-03 18:31:22.470  INFO 32144 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application USER-PROVIDER with eureka with status UP
2020-08-03 18:31:22.470  INFO 32144 --- [           main] com.netflix.discovery.DiscoveryClient    : Saw local status change event StatusChangeEvent [timestamp=1596450682470, current=UP, previous=STARTING]
2020-08-03 18:31:22.472  INFO 32144 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_USER-PROVIDER/192.168.0.19:user-provider:8802: registering service...
2020-08-03 18:31:22.517  INFO 32144 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_USER-PROVIDER/192.168.0.19:user-provider:8802 - registration status: 204
  • 查看eruekaServer,發現已經接入了USER-PROVIDER服務,該服務有以下兩個服務提供者

UP (2) - 192.168.0.19:user-provider:8802 , 192.168.0.19:user-provider:8803


5、消費者接入erueka server進行服務調用,並使用ribbon讓consumer負載均衡的去調用erueka中的服務provider

  • 在idea中經過Spring Initializr來建立springCloud項目eruekaConsumer

  • eruekaConsumer pom.xml文件

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.fqh</groupId>
<artifactId>consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eruekaConsumer</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • eruekaConsumer EurekaConsumerApplication文件 這裏須要注意

  • 咱們實例化了restTemplateBean類,並用ribbon的@LoadBalanced註解進行修飾

  • getUserInfo方法經過restTemplate進行user—service服務的getUser方法(http://user-provider/getUser?id=xx)調用

@RestController
@EnableEurekaClient
@SpringBootApplication
public class EruekaConsumerApplication {

@Autowired
RestTemplate restTemplate;

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

/**
* 實例化RestTemplate
*/
@LoadBalanced
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}

@GetMapping(value = "/getUserInfo")
public Map<String,Object> getUserInfo(@RequestParam Integer id){
Map<String,Object> data = restTemplate.getForObject("http://user-provider/getUser?id="+id,Map.class);
   return data;
}
}
  • applicate yml文件配置

eureka:
 client:
   serviceUrl: #註冊中心的註冊地址
     defaultZone: http://127.0.0.1:8800/eureka/
server:
 port: 8804 #服務端口號
spring:
 application:
   name: service-consumer #服務名稱--調用的時候根據名稱來調用該服務的方法

啓動EruekaConsumerApplication,發現已經連上eruekaServer

Registering application SERVICE-CONSUMER with eureka with status UP
2020-08-03 18:57:29.437  INFO 32764 --- [           main] com.netflix.discovery.DiscoveryClient    : Saw local status change event StatusChangeEvent [timestamp=1596452249437, current=UP, previous=STARTING]
2020-08-03 18:57:29.439  INFO 32764 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_SERVICE-CONSUMER/192.168.0.19:service-consumer:8804: registering service...
2020-08-03 18:57:29.490  INFO 32764 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_SERVICE-CONSUMER/192.168.0.19:service-consumer:8804 - registration status: 204
2020-08-03 18:57:29.508  INFO 32764 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8804 (http) with context path ''
2020-08-03 18:57:29.510  INFO 32764 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8804
  • 咱們發起get請求: http://localhost:8884/getUserInfo?id=xxx,發現調用服務成功,from裏Provider-one與Provider-two交替顯示,實現了負載均衡調用


6、搭建集羣高可用版本erueKaServer

現實中,咱們的erueka server端不可能單點運行,須要至少部署2個節點的erueka server來實現服務高可用,其實搭建erueka server集羣也很簡單 須要設置register-with-eureka 與fetch-registry都爲true(默認),並相互配置service-url的defaultZone爲對方的eruek Server訂閱地址 - 搭建eruekaServer2 (端口8801) 搭建項目項目過程與第三步一致,主要不一樣點在於application.yml配置處

  • 配置application.yml, 單點的eruekaServer咱們配置了register-with-eureka 與fetch-registry 都爲false,這裏咱們去掉這兩項,採用他們的默認配置true ,這裏配置的defaultZoneurl爲:http://${eureka.instance.hostname}:8800/eureka/

server:
 port: 8801
eureka:
 instance:
   hostname: 127.0.0.1
   prefer-ip-address: true
   leaseExpirationDurationInSeconds: 15
 client:
   service-url:
     defaultZone: http://${eureka.instance.hostname}:8800/eureka/

- 改造eruekaServer的application.yml(端口8800)以下:

server:
 port: 8800
eureka:
 instance:
   hostname: 127.0.0.1
   prefer-ip-address: true
   leaseExpirationDurationInSeconds: 15
 client:
   service-url:
     defaultZone: http://${eureka.instance.hostname}:8801/eureka/

啓動兩個eruekaserver,訪問8800與8801兩個臺eruekaServer發現兩個server已經相互註冊。實現了高可用。

Instances currently registered with Eureka
Application AMIs Availability Zones   Status
UNKNOWN       n/a (2)     (2)               UP (2)  - 192.168.0.19:8800 , 192.168.0.19:8801

- 改造eruekaProvider 與eruekaProvider的application.yml的erueka DefaultZone配置,多個鏈接用逗號分隔

defaultZone: http://127.0.0.1:8800/eureka/,http://127.0.0.1:8801/eureka/

最終的eruekaserver中的服務列表 

圖片

相關文章
相關標籤/搜索