Spring Cloud Eureka 學習記錄

丶Pz發表於2019-03-01

SpringCloud版本

           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-dependencies</artifactId>
           <version>Finchley.RELEASE</version>

1.1 Eureka Server

引入SpringCloud

 <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-parent</artifactId>
                <version>2.1.3.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--引入SpringCloud依賴-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

新建 Module:fly-services-discovery

新增Dependency

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

編寫入口類,加上@EnableEurekaServer

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {
    public static void main(String[] args) {
        SpringApplication.run(DiscoveryApplication.class,args);
    }
}

resources中新增application.yml

server:
  port: 8761
security:

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:8761/eureka

啟動專案,訪問:http://localhost:8761/

注意事項

  • SpringCloud 版本問題,要注意和SpringBoot相應的版本相容。
  • SpringBoot版本:2.1.3.RELEASE.
  • SpringCloud版本:Finchley.RELEASE

1.2 Eureka Client

新建 Module:fly-user-service


新增Dependency

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

編寫入口類,這裡不需要加上@EnableEurekaClient。新版的會預設將此服務作為Eureka Client.

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

resources中新增application.yml

server:
  port: 8081
spring:
  application:
    name: fly-user-service
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka
  instance:
    prefer-ip-address: true
    instanceId: ${spring.application.name}:${spring.application.instance_id:${server.port}}

啟動專案.再次訪問http://localhost:8761. FLY-USER-SERVICE已經註冊上。

img

1.3 Eureka Client Matadata

Eureka Client中新建RestController,注入o.s.cloud.client.discovery.DiscoveryClient,通過呼叫getInstances(serviceId) 返回matadata資訊

@RestController
@RequestMapping("/api")
public class UserServiceController {

    @Value("${spring.application.name}")
    private String serviceId;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 獲取使用者服務的詳細資訊
     * */
    @GetMapping("/user-service")
    public List<ServiceInstance> userServiceInfo(){
       return this.discoveryClient.getInstances(serviceId);
    }
}

修改application.yml,增加matadata

instance:
    prefer-ip-address: true
    metadata-map:
      # 這裡自定義,些什麼都可以 key/value
      description: 使用者微服務:包含使用者基礎資訊介面,賬戶介面等

執行程式,訪問:http://localhost:8081/api/user-service

[{
    "host": "192.168.157.1",
    "port": 8081,
    "metadata": {
        "description": "使用者微服務:包含使用者基礎資訊介面,賬戶介面等",
        "management.port": "8081",
        "jmx.port": "52681"
    },
    "secure": false,
    "uri": "http://192.168.157.1:8081",
    "instanceInfo": {
        "instanceId": "fly-user-service:8081",
        "app": "FLY-USER-SERVICE",
        "appGroupName": null,
        "ipAddr": "192.168.157.1",
        "sid": "na",
        "homePageUrl": "http://192.168.157.1:8081/",
        "statusPageUrl": "http://192.168.157.1:8081/actuator/info",
        "healthCheckUrl": "http://192.168.157.1:8081/actuator/health",
        "secureHealthCheckUrl": null,
        "vipAddress": "fly-user-service",
        "secureVipAddress": "fly-user-service",
        "countryId": 1,
        "dataCenterInfo": {
            "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
            "name": "MyOwn"
        },
        "hostName": "192.168.157.1",
        "status": "UP",
        "overriddenStatus": "UNKNOWN",
        "leaseInfo": {
            "renewalIntervalInSecs": 30,
            "durationInSecs": 90,
            "registrationTimestamp": 1551449194524,
            "lastRenewalTimestamp": 1551449194524,
            "evictionTimestamp": 0,
            "serviceUpTimestamp": 1551448771780
        },
        "isCoordinatingDiscoveryServer": false,
        "metadata": {
            "description": "使用者微服務:包含使用者基礎資訊介面,賬戶介面等",
            "management.port": "8081",
            "jmx.port": "52681"
        },
        "lastUpdatedTimestamp": 1551449194524,
        "lastDirtyTimestamp": 1551449194336,
        "actionType": "ADDED",
        "asgName": null
    },
    "serviceId": "FLY-USER-SERVICE",
    "scheme": null
}]

1.4 Eureka Authentication

fly-services-discovery專案中新增引用

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

修改配置檔案application.yml,增加以下配置:

spring:
  security:
    user:
      name: panzi
      password: 123456

defaultZone改為http://user:password@host:port/eureka格式

  defaultZone: http://panzi:123456@localhost:${server.port}/eureka

這裡需要注意的是,在高版本中,Eureka Client並不能成功註冊,會出現401錯誤.所以還需要在服務端增加配置類:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //關閉csrf
        http.csrf().ignoringAntMatchers("/eureka/**");
        //開啟認證
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

修改Eureka Client:fly-user-service的配置檔案,將defaultZone改為上文中的地址:

defaultZone: http://panzi:123456@localhost:${server.port}/eureka

啟動服務端和客戶端:訪問http://localhost:8761/

img

1.5 Eureka High Availability

搭建Eureka Server高可用,本機模擬先將hosts修改,windows下:C:\Windows\System32\drivers\etc

127.0.0.1 eureka1 eureka2

增加 application-eureka1.yml

spring:
  application:
    name: eureka-server
  profiles: eureka1
server:
  port: 8761
eureka:
  instance:
    hostname: eureka1
  client:
    service-url:
    # server1 註冊到server2上
      defaultZone: http://panzi:123456@eureka2:8762/eureka/
    register-with-eureka: true

增加 application-eureka2.yml

spring:
  application:
    name: eureka-server
  profiles: eureka2
server:
  port: 8762
eureka:
  instance:
    hostname: eureka2
  client:
    service-url:
    # server2 註冊到server1 上
      defaultZone: http://panzi:123456@eureka1:8761/eureka/
    register-with-eureka: true

分別執行兩個命令啟動服務

java -jar fly-services-discovery-1.0-SNAPSHOT.jar --spring.profiles.active=eureka1
java -jar fly-services-discovery-1.0-SNAPSHOT.jar --spring.profiles.active=eureka2

啟動成功之後,輸入使用者名稱和密碼

img

修改Eureka Client的配置檔案

defaultZone:http://panzi:123456@eureka1:8761/eureka/,http://panzi:123456@eureka2:8762/eureka/

執行Eureka Client,訪問:http://eureka1:8761/,http://eureka2:8761/

img


原文地址:https://github.com/fanpan26/Fly.SpringCloud/wiki
專案地址:https://github.com/fanpan26/Fly.SpringCloud

相關文章