溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringCloud之Eureka

發(fā)布時(shí)間:2020-06-04 00:33:09 來(lái)源:網(wǎng)絡(luò) 閱讀:259 作者:wx5d4ece0dab0a6 欄目:軟件技術(shù)

前面的話】SpringCloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)的一些工具,包括配置管理、服務(wù)發(fā)現(xiàn)、斷路器、路由、微代理、事件總線、全局鎖、決策競(jìng)選、分布式會(huì)話等等。它配置簡(jiǎn)單,上手快,而且生態(tài)成熟,便于應(yīng)用。但是它對(duì)SpringBoot有很強(qiáng)的依賴,需要有一定基礎(chǔ),但是SpringBoot倆小時(shí)就可以入門(mén)。另外對(duì)于“微服務(wù)架構(gòu)” 不了解的話,可以通過(guò)搜索引擎搜索“微服務(wù)架構(gòu)”了解下。另外這是SpringCloud的版本為Greenwich.SR2,JDK版本為1.8,SpringBoot的版本為2.1.7.RELEASE


壹、新建父工程

  • 新建一個(gè)Maven父工程lovincloud,便于版本管理,然后刪除src文件夾
  • 添加pom依賴和SpringCloud和SpringBoot的版本

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <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>

    貳、添加一個(gè)注冊(cè)中心

    在這里,我們需要用的的組件上Spring Cloud Netflix的Eureka ,eureka是一個(gè)服務(wù)注冊(cè)和發(fā)現(xiàn)模塊。

  • 新建一個(gè)子工程lovin-eureka-server作為服務(wù)的注冊(cè)中心

    <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服務(wù)端</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>
  • 然后在啟動(dòng)類(lèi)上添加@EnableEurekaServer注解:
    
    package com.eelve.lovin;

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

/**

  • @ClassName LovinEurekaServerApplication
  • @Description TDO
  • @Author zhao.zhilue
  • @Date 2019/8/15 16:20
  • @Version 1.0**/
    @EnableEurekaServer
    br/>**/
    @EnableEurekaServer
    public class LovinEurekaServerApplication {
    public static void main(String[] args) {
    SpringApplication.run(LovinEurekaServerApplication.class,args);
    }
    }
    - eureka是一個(gè)高可用的組件,它沒(méi)有后端緩存,每一個(gè)實(shí)例注冊(cè)之后需要向注冊(cè)中心發(fā)送心跳(因此可以在內(nèi)存中完成),在默認(rèn)情況下erureka server也是一個(gè)eureka client ,必須要指定一個(gè) server。eureka server的配置文件appication.yml:
    ~~~yaml
    spring:
    application:
    naem: lovineurkaserver  # 服務(wù)模塊名稱(chēng)
    server:
    port: 8881  # 設(shè)置的eureka端口號(hào)
    eureka:
    instance:
    hostname: localhost   # 設(shè)置eureka的主機(jī)地址
    client:
    registerWithEureka: false  #表示是否將自己注冊(cè)到Eureka Server,默認(rèn)為true。由于當(dāng)前應(yīng)用就是Eureka Server,故而設(shè)置為false
    fetchRegistry: false  #表示是否從Eureka Server獲取注冊(cè)信息,默認(rèn)為true。因?yàn)檫@是一個(gè)單點(diǎn)的Eureka Server,不需要同步其他的Eureka Server節(jié)點(diǎn)的數(shù)據(jù),故而設(shè)置為false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/   #Eureka server地址,查詢服務(wù)和注冊(cè)服務(wù)都需要依賴這個(gè)地址,多個(gè)地址可用逗號(hào)(英文的)分割

叁、添加一個(gè)服務(wù)消費(fèi)端

  • 新建一個(gè)子工程lovin-eureka-server作為服務(wù)的注冊(cè)中心

    <parent>
        <artifactId>lovincloud</artifactId>
        <groupId>com.eelve.lovincloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    
    <artifactId>lovin-eureka-client</artifactId>
    <packaging>jar</packaging>
    <name>eurekaclient</name>
    <version>0.0.1</version>
    <description>eureka的一個(gè)消費(fèi)端</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>
  • 然后在啟動(dòng)類(lèi)上添加@EnableEurekaClient注解:
    
    package com.eelve.lovin;

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

/**

  • @ClassName LovinEurekaClientApplication
  • @Description TDO
  • @Author zhao.zhilue
  • @Date 2019/8/15 16:37
  • @Version 1.0**/
    @SpringBootApplication
    br/>**/
    @SpringBootApplication
    public class LovinEurekaClientApplication {
    public static void main(String[] args) {
    SpringApplication.run(LovinEurekaClientApplication.class,args);
    }
    }
    - 然后我們需要連接到服務(wù)端,具體配置如下
    ~~~yaml
    server:
    port: 8801   # 服務(wù)端口號(hào)
    spring:
    application:
    name: lovineurkaclient     # 服務(wù)名稱(chēng)
    eureka:
    client:
    serviceUrl:
      defaultZone: http://localhost:8881/eureka/   # 注冊(cè)到的eureka服務(wù)地址
    • 新建一個(gè)Controller寫(xiě)一個(gè)測(cè)試接口
      
      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;

/**

  • @ClassName HelloController
  • @Description TDO應(yīng)用默認(rèn)訪問(wèn)接口
  • @Author zhao.zhilue
  • @Date 2019/8/15 16:45
  • @Version 1.0**/
    @RestController
    br/>**/
    @RestController

    @Autowired
    ServerConfig serverConfig;

    @RequestMapping("hello")
    public String hello(){
    return serverConfig.getUrl()+"###"+ HelloController.class.getName();
    }
    }

    # 肆、分別啟動(dòng)注冊(cè)中心的服務(wù)端和客戶端
    訪問(wèn)localhost:8881查看結(jié)果
    ![注冊(cè)中心](https://cache.yisu.com/upload/information/20200312/76/254765.jpg)
    到這里我們可以已經(jīng)看到已經(jīng)成功將客戶端注冊(cè)到服務(wù)端了,然后我們?cè)L問(wèn)測(cè)試接口
    ![192202](https://cache.yisu.com/upload/information/20200312/76/254766.jpg)
    可以看到已經(jīng)訪問(wèn)成功,至此Eureka的搭建已經(jīng)完成。
    # 伍、加入安全配置
    在互聯(lián)網(wǎng)中我們一般都會(huì)考慮安全性,尤其是管理服務(wù)的注冊(cè)中心,所以我們可以用**spring-boot-starter-security**來(lái)做安全限制
    - 給**lovin-eureka-server**添加**spring-boot-starter-security**的pom依賴
    ~~~pom
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    • 修改配置文件
      spring:
      application:
      naem: lovineurkaserver  # 服務(wù)模塊名稱(chēng)
      security:
      basic:
      enabled: true
      user:
      name: lovin
      password: ${REGISTRY_SERVER_PASSWORD:lovin}
      server:
      port: 8881  # 設(shè)置的eureka端口號(hào)
      eureka:
      instance:
      hostname: localhost   # 設(shè)置eureka的主機(jī)地址
      metadata-map:
      user.name: ${security.user.name}
      user.password: ${security.user.password}
      client:
      registerWithEureka: false  #表示是否將自己注冊(cè)到Eureka Server,默認(rèn)為true。由于當(dāng)前應(yīng)用就是Eureka Server,故而設(shè)置為false
      fetchRegistry: false  #表示是否從Eureka Server獲取注冊(cè)信息,默認(rèn)為true。因?yàn)檫@是一個(gè)單點(diǎn)的Eureka Server,不需要同步其他的Eureka Server節(jié)點(diǎn)的數(shù)據(jù),故而設(shè)置為false
      serviceUrl:
      defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/   #Eureka server地址,查詢服務(wù)和注冊(cè)服務(wù)都需要依賴這個(gè)地址,多個(gè)地址可用逗號(hào)(英文的)分割
    • 添加security配置
      
      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
    br/>**/
    @EnableWebSecurity

    @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配置文件
      server:
      port: 8801   # 服務(wù)端口號(hào)
      spring:
      application:
      name: lovineurkaclient     # 服務(wù)名稱(chēng)
      security:
      basic:
      enabled: true
      user:
      name: lovin
      password: ${REGISTRY_SERVER_PASSWORD:lovin}
      eureka:
      client:
      serviceUrl:
      defaultZone: http://lovin:lovin@localhost:8881/eureka/   # 注冊(cè)到的eureka服務(wù)地址
      instance:
      leaseRenewalIntervalInSeconds: 10
      health-check-url-path: /actuator/health
      metadata-map:
      user.name: lovin
      user.password: lovin
    • 添加security配置
      
      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
    br/>**/
    @Configuration

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().permitAll()
    .and().csrf().disable();
    }
    }

    
    - 另外為了測(cè)試多客服端注冊(cè),我們可以修改再給客戶端新建一個(gè)配置文件,然后開(kāi)啟IDEA的多節(jié)點(diǎn)運(yùn)行,如下圖所示勾選**Allow parallel run**
    ![192203](https://cache.yisu.com/upload/information/20200312/76/254767.jpg)
    - 然后為了區(qū)分是哪個(gè)節(jié)點(diǎn)的請(qǐng)求我們可以添加獲取端口
    ~~~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
    br/>**/
    @Component
    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();
    }

}


- 然后我們一次重啟服務(wù)端和兩個(gè)客戶端,這個(gè)時(shí)候我們?cè)L問(wèn)http://localhost:8881/
![192205](https://cache.yisu.com/upload/information/20200312/76/254769.jpg)
可以看到,這里已經(jīng)讓我們輸入用戶名和密碼了,說(shuō)明**spring-boot-starter-security**已經(jīng)配置成功,這時(shí)我們輸入配置的用戶名:lovin和密碼:lovin
![192204](https://cache.yisu.com/upload/information/20200312/76/254772.jpg)
這里我們可以看到已經(jīng)成功了,那么到這里Eureka的配置已經(jīng)全部成功了。
* [最后的最后是本博客的源碼,歡迎關(guān)注這一套SpringCloud的實(shí)踐](https://github.com/lovinstudio/lovincloud)
向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI