SpringCloud之Eureka
阿新 • • 發佈:2019-08-25
【前面的話】SpringCloud為開發人員提供了快速構建分散式系統的一些工具,包括配置管理、服務發現、斷路器、路由、微代理、事件匯流排、全域性鎖、決策競選、分散式會話等等。它配置簡單,上手快,而且生態成熟,便於應用。但是它對SpringBoot有很強的依賴,需要有一定基礎,但是SpringBoot倆小時就可以入門。另外對於“微服務架構” 不瞭解的話,可以通過搜尋引擎搜尋“微服務架構”瞭解下。另外這是SpringCloud的版本為Greenwich.SR2,JDK版本為1.8,SpringBoot的版本為2.1.7.RELEASE。
壹、新建父工程
- 新建一個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>
貳、新增一個註冊中心
在這裡,我們需要用的的元件上Spring Cloud Netflix的Eureka ,eureka是一個服務註冊和發現模組。
- 新建一個子工程lovin-eureka-server作為服務的註冊中心
<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註解:
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
@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:
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作為服務的註冊中心
<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的一個消費端</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註解:
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
@EnableEurekaClient
public class LovinEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(LovinEurekaClientApplication.class,args);
}
}
- 然後我們需要連線到服務端,具體配置如下
server:
port: 8801 # 服務埠號
spring:
application:
name: lovineurkaclient # 服務名稱
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8881/eureka/ # 註冊到的eureka服務地址
- 新建一個Controller寫一個測試介面
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應用預設訪問介面
* @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檢視結果
到這裡我們可以已經看到已經成功將客戶端註冊到服務端了,然後我們訪問測試介面
可以看到已經訪問成功,至此Eureka的搭建已經完成。
伍、加入安全配置
在網際網路中我們一般都會考慮安全性,尤其是管理服務的註冊中心,所以我們可以用spring-boot-starter-security來做安全限制
- 給lovin-eureka-server新增spring-boot-starter-security的pom依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 修改配置檔案
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配置
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依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 修改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配置
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
- 然後為了區分是哪個節點的請求我們可以新增獲取埠
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<WebServerInitializedEvent> {
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/
可以看到,這裡已經讓我們輸入使用者名稱和密碼了,說明spring-boot-starter-security已經配置成功,這時我們輸入配置的使用者名稱:lovin和密碼:lovin
這裡我們可以看到已經成功了,那麼到這裡Eureka的配置已經全部成功了。 - 最後的最後是本部落格的原始碼,歡迎關注這一套SpringCloud的實踐