springboot和flask整合nacos,使用openfeign实现服务调用,使用gateway实现网关的搭建(附带jwt续约的实现)

环境准备:

插件版本
jdk21
springboot

3.0.11

springcloud

2022.0.4

springcloudalibaba

2022.0.0.0

nacos2.2.3(稳定版)
python3.8

nacos部署(docker)

先创建目录,分别创建config,logs,data目录,单独创建一个容器

docker run -d \
-e MODE=standalone \
-p 8848:8848 \
-p 9848:9848 \
-p 7848:7848 \
-v /data/nacos/conf:/mnt/data3/dockerfiles/nacos/config \
-v /data/nacos/logs:/mnt/data3/dockerfiles/nacos/logs \
-v /data/nacos/data:/mnt/data3/dockerfiles/nacos/data \
--name nacos-mysql \
--restart=always \
nacos/nacos-server:v2.2.3

 将配置文件拷贝出来(主要是application.properties和logback.xml)

docker cp nacos-mysql:/home/nacos/conf ./

修改mysql的信息(修改文件application.properties)

再次运行

docker run -d \
-e MODE=standalone \
-p 8848:8848 \
-p 9848:9848 \
-p 7848:7848 \
-v /data/nacos/conf:/mnt/data3/dockerfiles/nacos/config \
-v /data/nacos/logs:/mnt/data3/dockerfiles/nacos/logs \
-v /data/nacos/data:/mnt/data3/dockerfiles/nacos/data \
--name nacos-mysql \
--restart=always \
nacos/nacos-server:v2.2.3

开启服务器端口:

centos开启防火墙端口

 访问 ip:port/nacos

出现此页面即为安装成功。

springboot注册到nacos

先贴一个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>3.0.11</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>platform</artifactId><version>0.0.1-SNAPSHOT</version><name>platform</name><description>platform</description><properties><java.version>21</java.version><spring-cloud.version>2022.0.0</spring-cloud.version><spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.2</version></dependency>
<!--        <dependency>-->
<!--            <groupId>org.springframework.cloud</groupId>-->
<!--            <artifactId>spring-cloud-starter-openfeign</artifactId>-->
<!--        </dependency>--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.2</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter-test</artifactId><version>3.0.2</version><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>edge-SNAPSHOT</version></dependency><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>2.0.1.Final</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.41</version></dependency><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.4.0</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-loadbalancer</artifactId></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><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${spring-cloud-alibaba.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><repositories><repository><id>projectlombok.org</id><url>https://projectlombok.org/edge-releases</url></repository></repositories><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

配置文件bootstrap.yml

spring:application:name: platformcloud:nacos:server-addr: ip:portconfig:file-extension: ymlgroup: DEFAULT_GROUPprefix: ${sping.application.name}

springboot启动类

@SpringBootApplication
@EnableFeignClients
@EnableCaching
@EnableScheduling
@EnableDiscoveryClient
@RefreshScope
public class PlatformApplication {public static void main(String[] args) {SpringApplication.run(PlatformApplication.class, args);}}

启动后就可以将服务注册到nacos中

python集成flask注册到nacos

首先下载nacos的sdk包

pip install nacos-sdk-python

python代码

import glob
import nacos
import threading
from flask import request, send_file
from flask import Flask, Response# nacos注册中心配置
SERVER_ADDRESS = "http://ip:port"
client = nacos.NacosClient(SERVER_ADDRESS)def service_register():"""ephemeral参数:是否是临时服务,应为false; 刚才上面也提到了,如果是 非临时实例,客户端就无需主动完成心跳检测。因此此处将服务注册为 非临时实例"""client.add_naming_instance("train", "ip", "port", ephemeral=False)# 测试nacos
@app.route("/testNacos/<testId>", methods=["GET"])
def testNacos(testId):resMap = {}print("nacos: {}".format(testId))resMap["code"] = "200"resMap["message"] = "hello nacos"resMap["data"] = str(testId)response = Response(json.dumps(resMap), status=200,content_type='application/json')return responseif __name__ == "__main__":# main()threading.Timer(5, service_register).start()app.run("0.0.0.0", 12352)

启动后就可以将服务注册到nacos中

到这里,服务注册到nacos已经完成了

使用openfeign进行服务间的调用

@FeignClient("train")
public interface InferRpcService {@GetMapping("/testNacos/{testId}")VitsResponse testNacos(@PathVariable String testId);
}

测试类

@Test
public void testNacosPy(){System.out.println(trainService.testNacos("232323"));
}

执行后

经测试没有问题

gateway网关服务

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>3.0.11</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>gateway</artifactId><version>0.0.1-SNAPSHOT</version><name>gateway</name><description>gateway</description><properties><java.version>21</java.version><spring-cloud.version>2022.0.4</spring-cloud.version><spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version></properties><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.4.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.41</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></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><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${spring-cloud-alibaba.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>

配置文件(bootstrap.yml)

spring:application:name: gatewaycloud:nacos:server-addr: ip:portconfig:file-extension: ymlgroup: DEFAULT_GROUPprefix: ${sping.application.name}gateway:# 下游服务https配置httpclient:ssl:use-insecure-trust-manager: trueroutes:- id: platformuri: lb://platformpredicates:- Path=/api/platform/**filters:- StripPrefix=2

启动类

@RefreshScope
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {public static void main(String[] args) {SpringApplication.run(GatewayApplication.class, args);}}

jwt续约

工具类

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;import java.time.LocalDateTime;
import java.util.*;@Slf4j
public class JWTUtils {private static final String SING = "auth";public static String getToken(Map<String, String> map) {Calendar instance = Calendar.getInstance();instance.add(Calendar.MINUTE, 30);JWTCreator.Builder builder = JWT.create();map.forEach((k, v) -> {builder.withClaim(k, v);});String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SING));return token;}public static DecodedJWT verify(String token) {return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);}/*** 查看是否需要续约** @param jwtToken 前端的* @return -1过期,不需要续约  0 不需要操作  1 需要续约*/public static int renewed(String jwtToken) {DecodedJWT verify = null;try {verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(jwtToken);if (Objects.nonNull(verify)) {log.info("过期时间: {}", verify.getExpiresAt());Date date = verify.getExpiresAt();if (date.before(new Date())) {log.info("token已过期");return -1;} else if (DateUtils.toLocalDateTime(date).minusMinutes(15L).isAfter(LocalDateTime.now())) {log.info("token处于正常状态");return 0;} else if (DateUtils.toLocalDateTime(date).minusMinutes(15L).isBefore(LocalDateTime.now())) {log.info("token需要续签");return 1;}}} catch (JWTVerificationException | IllegalArgumentException e) {log.info("token已过期");return -1;}log.info("token已过期");return -1;}public static String doRenewed(String number) {Map<String, String> map = Collections.singletonMap("openid", number);return getToken(map);}
}
public class DateUtils {public static LocalDateTime toLocalDateTime(Date date){return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();}
}

全局过滤器

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.gateway.constant.Constant;
import com.example.gateway.constant.LoginConstant;
import com.example.gateway.constant.VitsCloneConstant;
import com.example.gateway.dto.response.CommonResponse;
import com.example.gateway.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
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;@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();ServerHttpResponse response = exchange.getResponse();// 获取请求路径String path = request.getPath().toString();log.info("path:{}", path);// 当前过滤器        if (StringUtils.contains(path, VitsCloneConstant.API_PREFIX)) {// 如果是登录接口,直接放行if (StringUtils.contains(path, LoginConstant.LOGIN_PATH)) {return chain.filter(exchange);}// 获取请求头中的Authorization字段String token = request.getHeaders().getFirst(LoginConstant.AUTHORIZATION_HEADER);// 如果校验失败,返回未授权状态if (StringUtils.isEmpty(token)) {CommonResponse<String> error = CommonResponse.error("无效的授权信息", "无效的授权信息");response.setStatusCode(HttpStatus.UNAUTHORIZED);return response.writeWith(Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(error))));}int renewed = JWTUtils.renewed(token);if (renewed == -1) {log.info("token已过期");CommonResponse<String> error = CommonResponse.error("无效的授权信息", "无效的授权信息");response.setStatusCode(HttpStatus.UNAUTHORIZED);return response.writeWith(Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(error))));} else if (renewed == 0) {log.info("jwtToken状态正常,无需操作");DecodedJWT verify = JWTUtils.verify(token);String openid = verify.getClaims().get("openid").asString();ServerHttpRequest modifiedRequest = exchange.getRequest().mutate().header("openId", openid).build();return chain.filter(exchange.mutate().request(modifiedRequest).build());} else {DecodedJWT verify = JWTUtils.verify(token);String openid = verify.getClaims().get("openid").asString();log.info("当前需要续约的jwtToken的用户手机号码: {}", openid);token = JWTUtils.doRenewed(openid);response.getHeaders().set(LoginConstant.AUTHORIZATION_HEADER, token);ServerHttpRequest modifiedRequest = exchange.getRequest().mutate().header("openId", openid).build();return chain.filter(exchange.mutate().request(modifiedRequest).build());}}return chain.filter(exchange);}@Overridepublic int getOrder() {return -900;}}

常量类

public interface Constant {String TOKEN = "token";
}
public interface LoginConstant {String LOGIN_PATH = "/login";String AUTHORIZATION_HEADER = "token";
}
public interface VitsCloneConstant {String API_PREFIX="/api/platform/";
}

启动网关后,就可以通过网关访问服务了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/157424.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机数据库中了locked勒索病毒怎么解决,勒索病毒解密,数据恢复

网络的发展为企业的生产生活提供了极大的便利&#xff0c;但是&#xff0c;随之而来的网络安全威胁也不断增加&#xff0c;从11月份以来&#xff0c;云天数据恢复中心陆续接到很多企业的求助&#xff0c;企业的计算机数据库遭到了locked勒索病毒攻击&#xff0c;所有数据库中的…

sql-50练习题11-15

sql-50练习题11-15 前言数据库表结构介绍学生表课程表成绩表教师表 1-1 查询没有学全所有课程的同学的信息1-2 查询至少有一门课与学号为01的同学所学相同的同学的信息1-3 查询和1号的同学学习的课程完全相同的其他同学的信息1-4 查询没学过张三老师讲授的任一门课程的学生姓名…

Nginx简介,Nginx搭载负载均衡以及Nginx部署前端项目

目录 一. Nginx简介 Nginx的优点 二. Nginx搭载负载均衡 2.1 Nginx安装 2.1.1 安装依赖 2.1.2 解压nginx安装包 2.1.3 安装nginx 2.1.4 启动nginx服务 2.2 tomcat负载均衡 2.3 Nginx配置 三. Nginx前端部署 一. Nginx简介 NGINX&#xff08;读作&#xff1a;engi…

Ant Design Vue Table 表格内容高度自适应+固定表头踩坑

前言 对于非专业前端开发者来使用 Ant Design UI 组件来开发企业级后台管理系统来说是非常不错的选择&#xff0c;但这并不意味着我们能够用好这个框架&#xff0c;因为 UI 交互上和有许多细节上的问题对于非专业前端来说并不容易解决&#xff0c;最近在使用 Table 组件时就遇…

echart 饼图怎么让图形铺满整个div

1.原效果&#xff08;未铺满&#xff09;&#xff1a;原配置 2.如果想要铺满&#xff0c;需要设置radius &#xff0c;radius的意思是 第一个元素为内环半径&#xff0c;第二个参数为外环半径&#xff1b; 如果想要填满的话直接写[0,100%],不过第一个为0后就不是圆环里&#…

FPGA实现HDMI转LVDS视频输出,纯verilog代码驱动,提供4套工程源码和技术支持

目录 1、前言免责声明 2、目前我这里已有的图像处理方案3、本 LVDS 方案的特点4、详细设计方案设计原理框图视频源选择静态彩条IT6802解码芯片配置及采集ADV7611解码芯片配置及采集silicon9011解码芯片配置及采集纯verilog的HDMI 解码模块奇偶场分离并串转换LVDS驱动 5、vivado…

【JavaScript】前端一定要砍的 Promise 用法详细解析

每一个前端都要学的 Promise 用法详细解析 文章目录 前言一. 认识Promise1.1. 异步回调处理1.2. 什么是Promise1.3. Promise重构 二. Promise对象方法2.1. Executor2.2. then方法 2.2.1. then方法两个参数2.2.2. then方法多次调用2.2.3. then方法的返回值2.3. catch方法2.3.1.…

HarmonyOS鸿蒙原生应用开发设计- 元服务(原子化服务)图标

HarmonyOS设计文档中&#xff0c;为大家提供了独特的元服务图标&#xff0c;开发者可以根据需要直接引用。 开发者直接使用官方提供的元服务图标内容&#xff0c;既可以符合HarmonyOS原生应用的开发上架运营规范&#xff0c;又可以防止使用别人的元服务图标侵权意外情况等&…

动手学深度学习 - 学习环境配置

学习环境配置 1、安装 Miniconda1.1 下载 miniconda31.2 环境变量配置1.3 安装成功测试1.4 配置文件1.5 使用conda创建、使用、删除环境1.6 conda 常用命令 2、使用 miniconda 安装 d2l2.1 下载 d2l 安装包2.2 安装 d2l 1、安装 Miniconda 参考&#xff1a; https://www.jb51.n…

Http代理与socks5代理有何区别?如何选择?(二)

上篇文章我们基本分别了解了http代理与socks5代理的定义与优缺点&#xff0c;接下来我们继续来了解http代理与socks5代理之间的比较与区别。 一、两者的比较 1、功能比较 HTTP代理专门用于Web流量&#xff0c;并在处理HTTP和HTTPS协议方面非常高效。它们可以修改正在传输的数…

MySQL笔记--Ubuntu安装MySQL并基于C++测试API

目录 1--安装MySQL 2--MySQL连接 3--代码案例 1--安装MySQL # 安装MySQL-Server sudo apt install mysql-server# 设置系统启动时自动开启 sudo systemctl start mysql # sudo systemctl enable mysql# 检查MySQL运行状态 sudo systemctl status mysql# 进入MySQL终端 sudo…

Appium 移动端自动化测试 —— 触摸(TouchAction) 与多点触控(MultiAction)

一、触摸 TouchAction 在所有的 Appium 客户端库里&#xff0c;TouchAction 触摸对象被创建并被赋予一连串的事件。 规范里可用的事件有&#xff1a; * 短按(press) * 释放(release) * 移动到(moveTo) * 点击(tap) * 等待(wait) * 长按(longPress) * 取消(cancel) * 执行(per…