SpringBoot聚合項目配置Eurake和Gateway
本文簡單說名了Eurake、Gateway和Redis的配置及使用,聚合項目內相關包未做精簡規劃,Pom配置僅供參考
Redis默認只允許本機IP訪問,如果測試時Redis安裝地址與項目地址不一致,需要修改Redis配置文件,詳細說明參考另一篇Redis安裝教程即可
一、版本信息:
-
SpringBoot <version>2.2.6.RELEASE</version>
-
SpringCloud <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
-
項目目錄如圖:
二、開始配置一個聚合項目
1.先建一個父級工程:
最終pom.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>zhx-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>zhx-parent</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.新建一個Eurake子工程
如圖,右鍵父項目New-Module
Pom文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>zhx-eurake</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>zhx-eurake</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
</properties>
<dependencies>
<!-- 引入的Eureka-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
配置文件:
server:
port: 8082 #服務註冊中心端口號
spring:
application:
name: zhx-eurake
eureka:
instance:
hostname: 127.0.0.1 #服務註冊中心IP地址
client:
registerWithEureka: true #是否向服務註冊中心註冊自己
fetchRegistry: false #是否檢索服務
serviceUrl: #服務註冊中心的配置內容,指定服務註冊中心的位置
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
server:
renewal-percent-threshold: 0.5 #留存的服務示例低於多少比例進入保護模式
enable-self-preservation: true #是否開啓保護模式
啓動類要加上Eureka註解
package com.demo.eurake;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* 啓動一個服務註冊中心
*/
@EnableEurekaServer
@SpringBootApplication
public class ZhxEurakeApplication {
public static void main(String[] args) {
SpringApplication.run(ZhxEurakeApplication.class, args);
}
}
3.再建一個Gateway子工程
Pom文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>zhx-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>zhx-gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<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>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</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>
</project>
配置文件如下:
server:
port: 8081 #端口
spring:
application:
name: zhx-gateway
redis:
# Redis數據庫索引(默認爲0)
database: 10
# Redis服務器地址
host: 192.168.31.62
# Redis服務器連接端口
port: 6379
# Redis服務器連接密碼(默認爲空)
password:
timeout: 100
pool:
# 連接池最大連接數(使用負值表示沒有限制)
max-active: 8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-wait: -1
# 連接池中的最大空閒連接
max-idle: 8
# 連接池中的最小空閒連接
min-idle: 0
# 連接超時時間(毫秒)
timeout: 100
cloud:
gateway:
discovery:
locator:
enable: true
#配置路由規則
routes:
- id: eurake
uri: lb://ZHX-EURAKE #eureka註冊中心存在的服務名稱
predicates:
- Path=/eurake/** #路徑配置
filters:
- StripPrefix=1
- id: license
uri: lb://ZHX-LICENSE
predicates:
- Path=/license/**
filters:
- StripPrefix=1
- id: 163 #網關路由到網易官網
uri: http://www.163.com/
predicates:
- Path=/163/**
filters:
- StripPrefix=1 #忽略Path配置的個數,此處爲1代表訪問/api/customer/**時,會將api忽略,真實的訪問地址爲lb://customer-center/customer/**,如果爲2,則爲lb://customer-center/**
#- Authorize=true #啓用過濾器 Authorize爲過濾類的前綴
feign:
hystrix:
enabled: false
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8082/eureka/ #註冊中心地址
攔截器類:
package com.demo.gateway.filter;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
/**
* @author
* @ClassName AuthorizeFilter
* @Description 全局token校驗器
* @Date 2019-06-05 14:09
* @Version 1.0
*/
@Component
public class GatewayFilter implements GlobalFilter, Ordered {
private static final String AUTHORIZE_TOKEN="Authorization";
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String url_1 = "/Login";
String url = exchange.getRequest().getURI() + "";
if(url.contains(url_1)){
return chain.filter(exchange);
}
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
String token = headers.getFirst(AUTHORIZE_TOKEN);
if (!stringRedisTemplate.hasKey(token)){
ServerHttpResponse response = exchange.getResponse();
JSONObject message = new JSONObject();
message.put("status", -1);
message.put("data", "鑑權失敗");
byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bits);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
//指定編碼,否則在瀏覽器中會中文亂碼
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
啓動類:
package com.demo.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class ZhxGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ZhxGatewayApplication.class, args);
}
}
4.增加一個登陸模塊![在這裏插入圖片描述](https://img-blog.csdnimg.cn/2020050622054755.png?x-oss-
Pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.license</groupId>
<artifactId>zhx-license</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>zhx-license</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency><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-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</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>
</project>
配置文件如下:
server:
port: 8083
spring:
application:
name: zhx-license
redis:
# Redis數據庫索引(默認爲0)
database: 10
# Redis服務器地址
host: 192.168.31.62
# Redis服務器連接端口
port: 6379
# Redis服務器連接密碼(默認爲空)
password:
timeout: 100
pool:
# 連接池最大連接數(使用負值表示沒有限制)
max-active: 8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-wait: -1
# 連接池中的最大空閒連接
max-idle: 8
# 連接池中的最小空閒連接
min-idle: 0
# 連接超時時間(毫秒)
timeout: 100
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8082/eureka/ #註冊中心地址
登錄和退出類:
package com.license.java.controller.login;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/user")
public class LoginController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/Login")
public String Login(String userName,String password){
stringRedisTemplate.opsForValue().set(userName,password);
return "登陸成功";
}
@GetMapping("/Logout")
public String Logout(HttpServletRequest request){
String token = request.getHeader("Authorization");
stringRedisTemplate.delete(token);
return "退出成功";
}
}
啓動類:
package com.license.java;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class ZhxLicenseApplication {
public static void main(String[] args) {
SpringApplication.run(ZhxLicenseApplication.class, args);
}
}
三、測試
1.打開瀏覽器並訪問:http://127.0.0.1:8082/
2.用Gateway轉發的路徑訪問:http://localhost:8081/eurake/
3.用Postman進行登錄、退出測試
將zhx存入Authorization
用其他賬號退出,鑑權失敗:
用zhx賬號退出,成功並從Redis刪除zhx記錄:
重複退出,由於登錄信息已刪除,則返回鑑權失敗: