SpringCloud系列教程(十一):token验证

embedded/2025/3/4 17:27:38/

之前我们完成了gateway传递token到微服务中,但是这还不够,因为有时候我们微服务是一个调用链路,每个微服务的请求可以来自于网关也可以来自于其他微服务,我们只完成了gateway传递token,还没有完成微服务之间使用openfeign发送请求时的token传递。

1、我们在common项目里加一个类,把之前我们创建的那个openfeign-demo项目(时间过去有点久了,翻看一下前文)中的DefaultFeignConfig文件复制到common的config包下。openfeign框架给我们预留了一个拦截器RequestInterceptor,所以我们把openfeign的依赖复制到common的pom文件里并添加拦截器。

        <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
package com.mj.common.config;import cn.hutool.core.util.StrUtil;
import com.mj.common.tool.UserTool;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;import java.util.concurrent.TimeUnit;public class DefaultFeignConfig {@Beanpublic Logger.Level feignLogLevel() {return Logger.Level.FULL;}@Beanpublic Request.Options options() {//第一个参数是连接超时时间,第二个参数是处理超时时间return new Request.Options(2000, TimeUnit.MILLISECONDS, 2000, TimeUnit.MILLISECONDS, true);}@Beanpublic RequestInterceptor userRequestInterceptor() {return new RequestInterceptor() {@Overridepublic void apply(RequestTemplate requestTemplate) {String userid = UserTool.getUserId();if (StrUtil.isNotBlank(userid)) {requestTemplate.header("userid", userid);}}};}
}

2、这样就可以清理掉openfeign中的重复文件了,由于我们在学习过程中修改了不少东西,所以之前的openfeign-demo也要再修改一下。修改主启动类,把common里的config类扫描进去。

package com.mj.openfeign;import com.mj.common.config.DefaultFeignConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;@EnableFeignClients(defaultConfiguration = DefaultFeignConfig.class)
@SpringBootApplication(scanBasePackages = "com.mj")
public class OpenFeignDemoApplication {public static void main(String[] args) {SpringApplication.run(OpenFeignDemoApplication.class, args);}
}

3、修改NacosClientDemoClient文件,添加调用talk接口,并且要把更新的接口地址修改好。

package com.mj.openfeign.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;@FeignClient("nacos-client-demo")
public interface NacosClientDemoClient {@GetMapping("/nacos-client-demo/api/call")String testCall();@GetMapping("/nacos-client-demo/api/talk")String testTalk();
}

4、修改NacosClientController,添加一个调用talk的测试接口。

package com.mj.openfeign.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;@FeignClient("nacos-client-demo")
public interface NacosClientDemoClient {@GetMapping("/nacos-client-demo/api/call")String testCall();@GetMapping("/nacos-client-demo/api/talk")String testTalk();
}

5、网关里要添加对openfeign-demo的路由配置。

spring:main:# gateway组件中的spring-boot-starter-webflux和springboot作为web项目启动必不可少的spring-boot-starter-web出现冲突web-application-type: reactiveapplication:name: gateway-democloud:nacos:server-addr: 192.168.3.54:80username: nacospassword: nacosdiscovery:group: devopsnamespace: sitconfig:namespace: sitgroup: devopsgateway:routes:- id: nacos-client-demo #指定服务名uri: lb://nacos-client-demo #去注册中心找这个服务名predicates: #断言,匹配访问的路径- Path=/nacos-client-demo/api/**    #服务访问路径filters: # 过滤器- AddRequestHeader=headername, I am a header! # 添加请求头- My=zhangsan,lisi,wangwu- id: open-feign-demouri: lb://open-feign-demopredicates:- Path=/open-feign-demo/api/**config:import: nacos:${spring.application.name}?refresh=true
server:port: 8888

6、重启服务,通过curl命令带有token进行调用openfeign-demo,再由openfeign-demo调用nacos-client-demo中的talk接口。

curl -H "token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6InpoYW5nc2FuIiwidXNlcklkIjoiMTIzIiwiZXhwIjoxN zQwNzU1NDE2fQ.Xqpgk_lqhpxIIvxSo70mb3LQuozREIOituLyZKKYYaA" http://127.0.0.1:8888/open-feign-demo/api/talkhi,123

可见返回结果页正确解析到了userId,这样我们就基本完成了token在微服务体系中的传递功能,当然在日常工作中还会有其他的做法,万变不离其宗,大家就按照咱们练习的样子去改造就可以了。


http://www.ppmy.cn/embedded/169976.html

相关文章

5G学习笔记之BWP

我们只会经历一种人生&#xff0c;我们选择的人生。 参考&#xff1a;《5G NR标准》、《5G无线系统指南:如微见著&#xff0c;赋能数字化时代》 目录 1. 概述2. BWP频域位置3. 初始与专用BWP4. 默认BWP5. 切换BWP 1. 概述 在LTE的设计中&#xff0c;默认所有终端均能处理最大2…

openssl下aes128算法xts模式加解密运算实例

aes128算法xts接口 加密 int openssl_aes128_encrypt_xts(unsigned char *key,unsigned char *iv, unsigned char *in_buf, int in_len, unsigned char *out_buf,int* out_len) {int len 0;// 创建并初始化加密上下文EVP_CIPHER_CTX *ctx EVP_CIPHER_CTX_new();if (!ctx) {p…

R 语言科研绘图第 29 期 --- 密度图-山脊线

在发表科研论文的过程中&#xff0c;科研绘图是必不可少的&#xff0c;一张好看的图形会是文章很大的加分项。 为了便于使用&#xff0c;本系列文章介绍的所有绘图都已收录到了 sciRplot 项目中&#xff0c;获取方式&#xff1a; R 语言科研绘图模板 --- sciRplothttps://mp.…

网络通信库

服务端和客户端 1.建立连接。服务端对接多个客户端&#xff0c;用连接池&#xff08;对象池&#xff09;优化 2.收发消息&#xff0c;类和对象通过序列化和反序列化程二进制来通信 3.其他库函数 1.信号量 2.原子操作 -- 3.SocketAsyncEventArgs SocketAsyncEventArgs是一…

Python 绘制迷宫游戏,自带最优解路线

1、需要安装pygame 2、上下左右移动&#xff0c;空格实现物体所在位置到终点的路线&#xff0c;会有虚线绘制。 import pygame import random import math# 迷宫单元格类 class Cell:def __init__(self, x, y):self.x xself.y yself.walls {top: True, right: True, botto…

探秘基带算法:从原理到5G时代的通信变革【一】引言

文章目录 一、引言1.1 研究背景与意义1.2 研究目的与方法1.3 研究内容与创新点 本博客为系列博客&#xff0c;主要讲解各基带算法的原理与应用&#xff0c;包括&#xff1a;viterbi解码、Turbo编解码、Polar编解码、CORDIC算法、CRC校验、FFT/DFT、QAMtiaozhi/解调、QPSK调制/解…

51c自动驾驶~合集52

我自己的原文哦~ https://blog.51cto.com/whaosoft/13383340 #世界模型如何推演未来的千万种可能 驾驶世界模型&#xff08;DWM&#xff09;&#xff0c;专注于预测驾驶过程中的场景演变&#xff0c;已经成为追求自动驾驶的一种有前景的范式。这些方法使自动驾驶系统能够更…

Tailwind CSS 问题:npm error could not determine executable to run

问题与处理策略 问题描述 npx tailwindcss init -p在使用 Tailwind CSS 的前端项目中&#xff0c;执行上述指令&#xff0c;即初始化 Tailwind CSS 时&#xff0c;报如下错误 npm error could not determine executable to run# 报错npm 错误无法确定要运行的可执行文件问题…