SpringCloud之Eureka

前面的話】SpringCloud爲開發人員提供了快速構建分佈式系統的一些工具,包括配置管理、服務發現、斷路器、路由、微代理、事件總線、全局鎖、決策競選、分佈式會話等等。它配置簡單,上手快,並且生態成熟,便於應用。可是它對SpringBoot有很強的依賴,須要有必定基礎,可是SpringBoot倆小時就能夠入門。另外對於「微服務架構」 不瞭解的話,能夠經過搜索引擎搜索「微服務架構」瞭解下。另外這是SpringCloud的版本爲Greenwich.SR2,JDK版本爲1.8,SpringBoot的版本爲2.1.7.RELEASEcss

壹、新建父工程

  • 新建一個Maven父工程lovincloud,便於版本管理,而後刪除src文件夾
  • 添加pom依賴和SpringCloud和SpringBoot的版本
    ~~~pom

    org.springframework.boot
    spring-boot-starter-parent
    2.1.7.RELEASE

<groupId>com.eelve.lovincloud</groupId>
    <artifactId>lovincloud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>複製代碼
<name>lovincloud</name>
    <url>http://maven.apache.org</url>複製代碼
<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
        <java.version>1.8</java.version>
    </properties>複製代碼
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>複製代碼
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>複製代碼
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
~~~
# 貳、添加一個註冊中心
在這裏,咱們須要用的的組件上Spring Cloud Netflix的Eureka ,eureka是一個服務註冊和發現模塊。
- 新建一個子工程**lovin-eureka-server**做爲服務的註冊中心
~~~pom
<parent>
        <artifactId>lovincloud</artifactId>
        <groupId>com.eelve.lovincloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>複製代碼
<artifactId>lovin-eureka-server</artifactId>
    <packaging>jar</packaging>
    <name>eurekaserver</name>
    <version>0.0.1</version>
    <description>eureka服務端</description>複製代碼
<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>複製代碼
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>複製代碼
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
~~~
- 而後在啓動類上添加@EnableEurekaServer註解:
~~~java
package com.eelve.lovin;複製代碼

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;java

/**git

  • @ClassName LovinEurekaServerApplication
  • @Description TDO
  • @Author zhao.zhilue
  • @Date 2019/8/15 16:20
  • @Version 1.0
    **/
    @EnableEurekaServer
    @SpringBootApplication
    public class LovinEurekaServerApplication {
    public static void main(String[] args) {
    SpringApplication.run(LovinEurekaServerApplication.class,args);
    }
    }
    ~~~
    • eureka是一個高可用的組件,它沒有後端緩存,每個實例註冊以後須要向註冊中心發送心跳(所以能夠在內存中完成),在默認狀況下erureka server也是一個eureka client ,必需要指定一個 server。eureka server的配置文件appication.yml:
      ~~~yaml
      spring:
      application:
      naem: lovineurkaserver # 服務模塊名稱
      server:
      port: 8881 # 設置的eureka端口號
      eureka:
      instance:
      hostname: localhost # 設置eureka的主機地址
      client:
      registerWithEureka: false #表示是否將本身註冊到Eureka Server,默認爲true。因爲當前應用就是Eureka Server,故而設置爲false
      fetchRegistry: false #表示是否從Eureka Server獲取註冊信息,默認爲true。由於這是一個單點的Eureka Server,不須要同步其餘的Eureka Server節點的數據,故而設置爲false
      serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #Eureka server地址,查詢服務和註冊服務都須要依賴這個地址,多個地址可用逗號(英文的)分割
      ~~~

叄、添加一個服務消費端

  • 新建一個子工程lovin-eureka-server做爲服務的註冊中心
    ~~~pom

    lovincloud
    com.eelve.lovincloud
    1.0-SNAPSHOT

    4.0.0
<artifactId>lovin-eureka-client</artifactId>
    <packaging>jar</packaging>
    <name>eurekaclient</name>
    <version>0.0.1</version>
    <description>eureka的一個消費端</description>複製代碼
<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>複製代碼
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
~~~
- 而後在啓動類上添加@EnableEurekaClient註解:
~~~java
package com.eelve.lovin;複製代碼

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;github

/**web

  • @ClassName LovinEurekaClientApplication
  • @Description TDO
  • @Author zhao.zhilue
  • @Date 2019/8/15 16:37
  • @Version 1.0
    **/
    @SpringBootApplication
    @EnableEurekaClient
    public class LovinEurekaClientApplication {
    public static void main(String[] args) {
    SpringApplication.run(LovinEurekaClientApplication.class,args);
    }
    }
    ~~~
    • 而後咱們須要鏈接到服務端,具體配置以下
      ~~~yaml
      server:
      port: 8801 # 服務端口號
      spring:
      application:
      name: lovineurkaclient # 服務名稱
      eureka:
      client:
      serviceUrl:
      defaultZone: http://localhost:8881/eureka/ # 註冊到的eureka服務地址
      ~~~
    • 新建一個Controller寫一個測試接口
      ~~~java
      package com.eelve.lovin.controller;

import com.eelve.lovin.config.ServerConfig;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;spring

/**apache

  • @ClassName HelloController
  • @Description TDO應用默認訪問接口
  • @Author zhao.zhilue
  • @Date 2019/8/15 16:45
  • @Version 1.0
    **/
    @RestController
    public class HelloController {
@Autowired
    ServerConfig serverConfig;複製代碼
@RequestMapping("hello")
    public String hello(){
        return serverConfig.getUrl()+"###"+ HelloController.class.getName();
    }
}
~~~
# 肆、分別啓動註冊中心的服務端和客戶端
訪問localhost:8881查看結果
![註冊中心](https://user-gold-cdn.xitu.io/2019/8/25/16cc8d3d94bbaced?w=1348&h=654&f=png&s=72636)
到這裏咱們能夠已經看到已經成功將客戶端註冊到服務端了,而後咱們訪問測試接口
![192202](https://user-gold-cdn.xitu.io/2019/8/25/16cc8d3dbbd9da16?w=824&h=394&f=png&s=12778)
能夠看到已經訪問成功,至此Eureka的搭建已經完成。
# 伍、加入安全配置
在互聯網中咱們通常都會考慮安全性,尤爲是管理服務的註冊中心,因此咱們能夠用**spring-boot-starter-security**來作安全限制
- 給**lovin-eureka-server**添加**spring-boot-starter-security**的pom依賴
~~~pom
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
~~~
- 修改配置文件
~~~yaml
spring:
  application:
    naem: lovineurkaserver  # 服務模塊名稱
  security:
    basic:
      enabled: true
    user:
      name: lovin
      password: ${REGISTRY_SERVER_PASSWORD:lovin}
server:
  port: 8881  # 設置的eureka端口號
eureka:
  instance:
    hostname: localhost   # 設置eureka的主機地址
    metadata-map:
      user.name: ${security.user.name}
      user.password: ${security.user.password}
  client:
    registerWithEureka: false  #表示是否將本身註冊到Eureka Server,默認爲true。因爲當前應用就是Eureka Server,故而設置爲false
    fetchRegistry: false  #表示是否從Eureka Server獲取註冊信息,默認爲true。由於這是一個單點的Eureka Server,不須要同步其餘的Eureka Server節點的數據,故而設置爲false
    serviceUrl:
      defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/   #Eureka server地址,查詢服務和註冊服務都須要依賴這個地址,多個地址可用逗號(英文的)分割
~~~
- 添加security配置
~~~java
package com.eelve.lovin.config;複製代碼

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;後端

/**緩存

  • @ClassName SecurityConfig
  • @Description TDO
  • @Author zhao.zhilue
  • @Date 2019/8/16 14:13
  • @Version 1.0
    **/
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/css/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
        super.configure(http);
    }
}
~~~
- 給**lovin-eureka-client**添加**spring-boot-starter-security**的pom依賴
~~~pom
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
~~~
- 修改yaml配置文件
~~~yaml
server:
  port: 8801   # 服務端口號
spring:
  application:
    name: lovineurkaclient     # 服務名稱
  security:
    basic:
      enabled: true
    user:
      name: lovin
      password: ${REGISTRY_SERVER_PASSWORD:lovin}
eureka:
  client:
    serviceUrl:
      defaultZone: http://lovin:lovin@localhost:8881/eureka/   # 註冊到的eureka服務地址
  instance:
    leaseRenewalIntervalInSeconds: 10
    health-check-url-path: /actuator/health
    metadata-map:
      user.name: lovin
      user.password: lovin
~~~
- 添加security配置
~~~java
package com.eelve.lovin.config;複製代碼

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

/**

  • @ClassName SecurityConfig
  • @Description TDO
  • @Author zhao.zhilue
  • @Date 2019/8/16 14:13
  • @Version 1.0
    **/
    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll()
                .and().csrf().disable();
    }
}
~~~
- 另外爲了測試多客服端註冊,咱們能夠修改再給客戶端新建一個配置文件,而後開啓IDEA的多節點運行,以下圖所示勾選**Allow parallel run**
![192203](https://user-gold-cdn.xitu.io/2019/8/25/16cc8d3ddf81eb53?w=1092&h=685&f=png&s=57674)
- 而後爲了區分是哪一個節點的請求咱們能夠添加獲取端口
~~~java
package com.eelve.lovin.config;複製代碼

import org.springframework.boot.web.context.WebServerInitializedEvent;import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;

import java.net.InetAddress;import java.net.UnknownHostException;

/**

  • @ClassName ServerConfig
  • @Description TDO
  • @Author zhao.zhilue
  • @Date 2019/8/18 12:03
  • @Version 1.0
    **/
    @Component
    public class ServerConfig implements ApplicationListener {
    private int serverPort;
public String getUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+address.getHostAddress() +":"+this.serverPort;
    }複製代碼
@Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }複製代碼

}~~~

  • 而後咱們一次重啓服務端和兩個客戶端,這個時候咱們訪問http://localhost:8881/
    192205
    能夠看到,這裏已經讓咱們輸入用戶名和密碼了,說明spring-boot-starter-security已經配置成功,這時咱們輸入配置的用戶名:lovin和密碼:lovin
    192204
    這裏咱們能夠看到已經成功了,那麼到這裏Eureka的配置已經所有成功了。
  • 最後的最後是本博客的源碼,歡迎關注這一套SpringCloud的實踐
相關文章
相關標籤/搜索