本文简单说名了Eurake、Gateway和Redis的配置及使用,聚合项目内相关包未做精简规划,Pom配置仅供参考
Redis默认只允许本机IP访问,如果测试时Redis安装地址与项目地址不一致,需要修改Redis配置文件,详细说明参考另一篇Redis安装教程即可
1.先建一个父级工程:
最终pom.xml配置如下:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.6.RELEASE
com.demo
zhx-parent
0.0.1-SNAPSHOT
zhx-parent
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
2.新建一个Eurake子工程
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.6.RELEASE
com.demo
zhx-eurake
0.0.1-SNAPSHOT
zhx-eurake
Demo project for Spring Boot
UTF-8
UTF-8
1.8
Hoxton.SR1
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.boot
spring-boot-autoconfigure
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
false
配置文件:
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文件如下:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.6.RELEASE
com.demo
zhx-gateway
0.0.1-SNAPSHOT
zhx-gateway
Demo project for Spring Boot
UTF-8
UTF-8
Hoxton.SR1
1.8
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.boot
spring-boot-starter-webflux
org.springframework.boot
spring-boot-starter-data-redis
com.alibaba
fastjson
1.2.41
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-tomcat
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
配置文件如下:
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 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文件:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.6.RELEASE
com.license
zhx-license
0.0.1-SNAPSHOT
zhx-license
Demo project for Spring Boot
UTF-8
UTF-8
Hoxton.SR1
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-autoconfigure
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
配置文件如下:
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/