SpringBoot集成Eurake、Gateway和Redis+Token验证拦截器实现

SpringBoot集成Eurake、Gateway和Redis+Token验证拦截器实现SpringBoot聚合项目配置Eurake和Gateway一、版本信息:SpringBoot <version>2.2.6.RELEASE</version>SpringCloud <spring-cloud.version>Hoxton.SR1</spring-cloud.version>二、开始配置一个聚合项目1.先建一个父级工程:最终pom.xml配置如下:<?xmlversion=”1.0″encodin

大家好,又见面了,我是你们的朋友全栈君。

SpringBoot聚合项目配置Eurake和Gateway

本文简单说名了Eurake、Gateway和Redis的配置及使用,聚合项目内相关包未做精简规划,Pom配置仅供参考
Redis默认只允许本机IP访问,如果测试时Redis安装地址与项目地址不一致,需要修改Redis配置文件,详细说明参考另一篇Redis安装教程即可

一、版本信息:

  1.  SpringBoot		<version>2.2.6.RELEASE</version>
    
  2.  SpringCloud	<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
    
  3.  项目目录如图:
    

    在这里插入图片描述

二、开始配置一个聚合项目

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记录:

在这里插入图片描述
重复退出,由于登录信息已删除,则返回鉴权失败:

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/139847.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • LaTeX公式自动换行

    LaTeX公式自动换行LaTeX公式自动换行文章目录LaTeX公式自动换行前言一、autobreak宏包二、breqn宏包总结前言在使用amsmath等宏包输入公式的时候,最折腾的就是比较特殊样式的公式和长公式,尤其是长公式在投稿期刊排版的时候经常遇到,有的期刊是双栏的版式,这样公式太大就要面临公式要进行折行的调整,很多时候我们使用align,multiline等环境,现在有个更加灵活的更加自动的宏包来了,可以让长公式自动换行了。一、autobreak宏包\usepackage{amsmath}\usepacka

  • docker 镜像导入导出_docker常用镜像

    docker 镜像导入导出_docker常用镜像将本机的镜像导出到压缩包,使用save和load进行导入和导出查看镜像列表dockerimages导出镜像dockersave0fdf2b4c26d3>images.tar同时导出多个dockersave-oimages.tarelastest/etm:2.4.0elastest/etm-jenkins:1.2.0导入镜像dockerload<images.tar…

  • PermitRootLogin不生效,ssh允许root登录

    PermitRootLogin不生效,ssh允许root登录1、sshd-T|grepetc查看当前sshd的配置文件位置2、修改PermitRootLogin为true3、重启sshd

  • 滴滴安全再升级:乘客醉酒乘车规则拓至全国15城[通俗易懂]

    滴滴安全再升级:乘客醉酒乘车规则拓至全国15城[通俗易懂]滴滴安全再升级:乘客醉酒乘车规则拓至全国15城

  • 树莓派 gpio usb_树莓派gpio编程

    树莓派 gpio usb_树莓派gpio编程概览树莓派最令人兴奋的特点之一是它有一个GPIO连接器可以用来接其他的硬件设备。GPIO连接器实际上是由许多不同类型的接口组成的:真正的GPIO(GeneralPurposeInputOutput,通用输入/输出)针脚,你可以用来控制LED灯的开和关。I2C(Inter-IntegratedCircuit)接口针脚,使你能够仅使用2个控制针脚连接硬件模块。SPI(SerialPeriph…

    2022年10月14日
  • NET-> SplitContainer控件说明

    NET-> SplitContainer控件说明拆分器控件Splitcontainer,是一个含有Splitter拆分条的容器,它包含两个面板容器Panel1,Panel2,可以移动拆分条,对面板大小进行控制!控件学习示例程序!属性介绍;//拆分条的是否启用禁用boolIsSplitterFixed{get

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号